Re: Performing an action on model.save() but not on update
Nick, Thanks very much. That worked! I can't work out why my code didn't though (or rather, worked twice). -Jim On Apr 23, 6:37 pm, Nick Serra wrote: > Try this out and see what happens: > > def _hook_post_save_answer(instance, created, sender, **kwargs): > if created: > if instance.user: > quser = instance.user.get_profile() > quser.increment_answers() > instance.question.increment_responses() > > post_save.connect(_hook_post_save_answer, sender=Answer) > > On Apr 23, 6:20 pm, Jim N wrote: > > > > > OK, that makes total sense. > > > I've implemented it like so: > > > def _hook_post_save_answer(instance, sender, **kwargs): > > if 'created' in kwargs and kwargs['created'] == True: > > if instance.user: > > quser = instance.user.get_profile() > > quser.increment_answers() > > instance.question.increment_responses() > > > post_save.connect(_hook_post_save_answer, sender=Answer) > > >http://dpaste.de/897o/ > > > But now, it increments TWICE! > > > Is there some glaring error in my logic above? > > > On Apr 23, 4:50 pm, Nick Serra wrote: > > > > I didn't even think of that. It's not very common to be specifying > > > pk's on create anyway, so yours would probably be fine. I just think > > > signals are cleaner and use them when I can :) > > > > On Apr 23, 4:47 pm, Skylar Saveland wrote: > > > > > Yeah, and I think my suggestion fails for a user-defined rather than > > > > auto-incrementing pk. > > > > > On Apr 23, 4:21 pm, Nick Serra wrote: > > > > > > A post save signal seems better suited for this. The post save signal > > > > > has an attribute 'created' that will be true or false depending on if > > > > > the object is being created or updated. Check out the post_save > > > > > documentation:http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.si... > > > > > > On Apr 23, 3:32 pm, Skylar Saveland wrote: > > > > > > > On Apr 23, 3:27 pm, Jim N wrote: > > > > > > > > Hi, > > > > > > > > I have overridden the default save() on a model so that I can > > > > > > > update > > > > > > > some counts every time a save occurs. Unfortunately, I don't > > > > > > > want to > > > > > > > perform these actions every time the model is updated, which > > > > > > > seems to > > > > > > > happen. > > > > > > > > Is there another approach I can take that distinguishes between > > > > > > > save > > > > > > > and update? > > > > > > > > class Answer(models.Model): > > > > > > > answer = models.TextField() > > > > > > > user = models.ForeignKey(User, null=True) > > > > > > > submit_date = models.DateTimeField('Date Submitted', > > > > > > > default=datetime.datetime.now) > > > > > > > question = models.ForeignKey(Question) > > > > > > > permalink = models.CharField(max_length=300, blank=True) > > > > > > > > def save(self, *args, **kwargs): > > > > > > > super(Answer, self).save(*args, **kwargs) # Call the > > > > > > > "real" > > > > > > > save() method. > > > > > > > if(self.user): > > > > > > > quser = self.user.get_profile() > > > > > > > quser.increment_answers() # <-- I don't want to do > > > > > > > this > > > > > > > on an update. > > > > > > > self.question.increment_responses() # <-- I don't > > > > > > > want to > > > > > > > do this either. > > > > > > > > Or in more readable form:http://dpaste.de/I2IR/ > > > > > > > Before you call super you can see if bool(self.pk) is True or False. > > > > > > It will be False before the first save. > > > > > > > -- > > > > > > You received this message because you are subscribed to the Google > > > > > > Groups "Django users" group. > > > > > > To post to this group, send ema
Re: Performing an action on model.save() but not on update
OK, that makes total sense. I've implemented it like so: def _hook_post_save_answer(instance, sender, **kwargs): if 'created' in kwargs and kwargs['created'] == True: if instance.user: quser = instance.user.get_profile() quser.increment_answers() instance.question.increment_responses() post_save.connect(_hook_post_save_answer, sender=Answer) http://dpaste.de/897o/ But now, it increments TWICE! Is there some glaring error in my logic above? On Apr 23, 4:50 pm, Nick Serra wrote: > I didn't even think of that. It's not very common to be specifying > pk's on create anyway, so yours would probably be fine. I just think > signals are cleaner and use them when I can :) > > On Apr 23, 4:47 pm, Skylar Saveland wrote: > > > > > Yeah, and I think my suggestion fails for a user-defined rather than > > auto-incrementing pk. > > > On Apr 23, 4:21 pm, Nick Serra wrote: > > > > A post save signal seems better suited for this. The post save signal > > > has an attribute 'created' that will be true or false depending on if > > > the object is being created or updated. Check out the post_save > > > documentation:http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.si... > > > > On Apr 23, 3:32 pm, Skylar Saveland wrote: > > > > > On Apr 23, 3:27 pm, Jim N wrote: > > > > > > Hi, > > > > > > I have overridden the default save() on a model so that I can update > > > > > some counts every time a save occurs. Unfortunately, I don't want to > > > > > perform these actions every time the model is updated, which seems to > > > > > happen. > > > > > > Is there another approach I can take that distinguishes between save > > > > > and update? > > > > > > class Answer(models.Model): > > > > > answer = models.TextField() > > > > > user = models.ForeignKey(User, null=True) > > > > > submit_date = models.DateTimeField('Date Submitted', > > > > > default=datetime.datetime.now) > > > > > question = models.ForeignKey(Question) > > > > > permalink = models.CharField(max_length=300, blank=True) > > > > > > def save(self, *args, **kwargs): > > > > > super(Answer, self).save(*args, **kwargs) # Call the "real" > > > > > save() method. > > > > > if(self.user): > > > > > quser = self.user.get_profile() > > > > > quser.increment_answers() # <-- I don't want to do this > > > > > on an update. > > > > > self.question.increment_responses() # <-- I don't want to > > > > > do this either. > > > > > > Or in more readable form:http://dpaste.de/I2IR/ > > > > > Before you call super you can see if bool(self.pk) is True or False. > > > > It will be False before the first save. > > > > > -- > > > > You received this message because you are subscribed to the Google > > > > Groups "Django users" group. > > > > To post to this group, send email to django-us...@googlegroups.com. > > > > To unsubscribe from this group, send email to > > > > django-users+unsubscr...@googlegroups.com. > > > > For more options, visit this group > > > > athttp://groups.google.com/group/django-users?hl=en. > > > > -- > > > You received this message because you are subscribed to the Google Groups > > > "Django users" group. > > > To post to this group, send email to django-us...@googlegroups.com. > > > To unsubscribe from this group, send email to > > > django-users+unsubscr...@googlegroups.com. > > > For more options, visit this group > > > athttp://groups.google.com/group/django-users?hl=en. > > > -- > > You received this message because you are subscribed to the Google Groups > > "Django users" group. > > To post to this group, send email to django-us...@googlegroups.com. > > To unsubscribe from this group, send email to > > django-users+unsubscr...@googlegroups.com. > > For more options, visit this group > > athttp://groups.google.com/group/django-users?hl=en. > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To post to this group, send email to django-us...@googlegroups.com. > To unsubscribe from this group, send email to > django-users+unsubscr...@googlegroups.com. > For more options, visit this group > athttp://groups.google.com/group/django-users?hl=en. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Performing an action on model.save() but not on update
Hi, I have overridden the default save() on a model so that I can update some counts every time a save occurs. Unfortunately, I don't want to perform these actions every time the model is updated, which seems to happen. Is there another approach I can take that distinguishes between save and update? class Answer(models.Model): answer = models.TextField() user = models.ForeignKey(User, null=True) submit_date = models.DateTimeField('Date Submitted', default=datetime.datetime.now) question = models.ForeignKey(Question) permalink = models.CharField(max_length=300, blank=True) def save(self, *args, **kwargs): super(Answer, self).save(*args, **kwargs) # Call the "real" save() method. if(self.user): quser = self.user.get_profile() quser.increment_answers() # <-- I don't want to do this on an update. self.question.increment_responses() # <-- I don't want to do this either. Or in more readable form: http://dpaste.de/I2IR/ TIA! -Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: determining if a one-to-many relation exists
Yes! That's it! Thank you. On Apr 12, 1:21 pm, Nick Serra wrote: > You could query like this: > > Question.objects.filter(answer__isnull=False) > > This would give you a set of questions where an answer exists. Setting > it to True would give you a set where answers don't exist. > > On Apr 12, 12:20 pm, Jim N wrote: > > > Just to clarify, I'm trying to filter questions that have an answer, > > but I don't know the particular answer. I just want to determine > > whether or not an answer object exists, with the foreign key of this > > question. > > > I could do > > > Answer.objects.filter(question = my_question) > > > but I am filtering questions on a number of parameters, such as text > > of the question. > > > Thanks, > > Jim > > > On Apr 12, 11:50 am, Jim N wrote: > > > > Hi Djangoists, > > > > I have a model "question" which has a one-to-many relationship with > > > "answer". > > > > class Question(models.Model): > > > text = models.TextField() > > > > class Answer(models.Model): > > > text = models.TextField() > > > question = models.ForeignKey(Question) > > > > I can't figure out how to construct a filter that will give me > > > > - just questions where there isn't an answer > > > - just questions where there is an answer > > > > Is this really easy and I'm just not seeing it? > > > > Thanks, > > > Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: determining if a one-to-many relation exists
Just to clarify, I'm trying to filter questions that have an answer, but I don't know the particular answer. I just want to determine whether or not an answer object exists, with the foreign key of this question. I could do Answer.objects.filter(question = my_question) but I am filtering questions on a number of parameters, such as text of the question. Thanks, Jim On Apr 12, 11:50 am, Jim N wrote: > Hi Djangoists, > > I have a model "question" which has a one-to-many relationship with > "answer". > > class Question(models.Model): > text = models.TextField() > > class Answer(models.Model): > text = models.TextField() > question = models.ForeignKey(Question) > > I can't figure out how to construct a filter that will give me > > - just questions where there isn't an answer > - just questions where there is an answer > > Is this really easy and I'm just not seeing it? > > Thanks, > Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
determining if a one-to-many relation exists
Hi Djangoists, I have a model "question" which has a one-to-many relationship with "answer". class Question(models.Model): text = models.TextField() class Answer(models.Model): text = models.TextField() question = models.ForeignKey(Question) I can't figure out how to construct a filter that will give me - just questions where there isn't an answer - just questions where there is an answer Is this really easy and I'm just not seeing it? Thanks, Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
another many-to-many filtering question
Hi All, I have a many-to-many relationship of User to Question through Asking. I want to get Questions that a given User has not asked yet. That is, Questions where there is no Asking record for a given User. I have the User's id. Models look like: class Question(models.Model): text = models.TextField() question_type = models.ForeignKey('QuestionType') user = models.ManyToManyField(User, through='Asking', null=True) class Asking(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question) is_primary_asker = models.BooleanField() User is the built-in django.contrib.auth.models User. Thanks! Maybe this is simple and I just am not seeing it. -Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
please ignore: Re: Dashboard plugin/widget development - create new post
Apologies - I posted this to the wrong group! On Apr 5, 12:23 pm, Jim N wrote: > Hi List, > > I thought this would be easy at first. Maybe it is. > > I am developing a dashboard widget that creates a post. Trying to > emulate what QuickPress does, only the title is from a select box, > instead of text input. > > Here is the form. It points at wp-admin/post.php. I get redirected > to edit.php, but no post shows up. No error message > ether. > > function draw_form($instance) { > global $qotd_user_id, $qotd_base_url, $local_url; > > $json = $this->get_questions($qotd_user_id); > ?> > > Question label> > > foreach($json as &$q) { > ?> > $q{'fields'}{'text'} ?> > } > ?> > > Answer label> > > class="mceEditor" > rows="3" cols="15" tabindex="2"> > > > name="conversation_post_ID" value="0" / > > name="_wpnonce" value=" php echo wp_create_nonce( "conversate_$qotd_user_id" ) ?>" /> > id="save-post" > class="button" tabindex="4" value="Save Draft" /> > > id="publish" > accesskey="p" tabindex="5" > class="button-primary" > value="Publish" /> > class="clear" /> > > > > } > ?> > > Thanks in advance for any help or suggestions! > > -JIM > > P.S. > Apologies if this question already posted. I seem to be having > posting issues. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Dashboard plugin/widget development - create new post
Hi List, I thought this would be easy at first. Maybe it is. I am developing a dashboard widget that creates a post. Trying to emulate what QuickPress does, only the title is from a select box, instead of text input. Here is the form. It points at wp-admin/post.php. I get redirected to edit.php, but no post shows up. No error message ether. get_questions($qotd_user_id); ?> Question Answer " /> Thanks in advance for any help or suggestions! -JIM P.S. Apologies if this question already posted. I seem to be having posting issues. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Complex Django query - filtering, joining a many-to-many table
Thanks Nuno, This is what finally worked: if request.GET['is_published'] == '1': # questions that are in the past filters['asking__question_published_date__lt'] = datetime.datetime.now() else: # questions from the FUTURE! filters['asking__question_published_date__gte'] = datetime.datetime.now() Regards, Jim On Apr 1, 1:56 pm, Nuno Maltez wrote: > How about just accessing the "through" models attributes using user__ : > > filters['user__question_published_date'] > > seehttp://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-o... > > Hht, > Nuno > > > > On Thu, Apr 1, 2010 at 3:09 PM, Jim N wrote: > > Hello Djanglers, > > > I am using a named many-to-many table ("Asking") to join "Questions" > > to "Users". Asking has some fields I'd like to filter against. > > > I now use a dictionary called filters: > > > filters = {} > > > if 'question' in request.GET: > > filters['text__icontains'] = request.GET['question'] > > if 'is_visible' in request.GET: > > filters['is_visible'] = request.GET['is_visible'] > > > [...] > > > questions = Question.objects.filter(**filters) > > > I need to add filtering by the publish dates of the question, which > > are stored in the many-to-many join table "Asking", which joins users > > to questions. > > > I can't figure out how I would do such a thing. > > > model Question: > > > class Question(models.Model): > > text = models.TextField() > > question_type = models.ForeignKey('QuestionType') > > user = models.ManyToManyField(User, through='Asking', null=True) > > submit_date = models.DateTimeField('Date Submitted', > > default=datetime.datetime.now) > > responses = models.IntegerField(default=0) > > > model Asking: > > > class Asking(models.Model): > > user = models.ForeignKey(User) > > question = models.ForeignKey(Question) > > is_primary_asker = models.BooleanField() > > is_targeted_answerer = models.BooleanField() > > question_targeted_date = models.DateTimeField(null=True, > > blank=True) > > question_scheduled_post_date = models.DateTimeField(null=True, > > blank=True) > > question_published_date = models.DateTimeField(null=True, > > blank=True) > > > The current filter code: > > > filters = {} > > > if 'question' in request.GET: > > filters['text__icontains'] = request.GET['question'] > > if 'is_visible' in request.GET: > > filters['is_visible'] = request.GET['is_visible'] > > if 'featured_status' in request.GET: > > filters['featured_status'] = request.GET['featured_status'] > > if 'has_responses' in request.GET: > > filters['responses'] = request.GET['has_responses'] > > if 'user_id' in request.GET: > > filters['user'] = request.GET['user_id'] > > > if 'vertical' in request.GET: > > if not request.GET['vertical'].isdigit(): > > # if vertical is passed in by name, get id > > vertical = > > Vertical.objects.filter(vertical=request.GET['vertical'])[0] > > filters['verticals'] = vertical.id > > else: > > filters['verticals'] = request.GET['vertical'] > > > if filters == {}: > > logging.debug("no filters, selecting all.") > > questions = Question.objects.all().order_by(order_by) > > [offset:limit] > > else: > > logging.debug("using filters.") > > questions = > > Question.objects.filter(**filters).order_by(order_by)[offset:limit] > > > Thanks for any suggestions! > > > -Jim > > > -- > > You received this message because you are subscribed to the Google Groups > > "Django users" group. > > To post to this group, send email to django-us...@googlegroups.com. > > To unsubscribe from this group, send email to > > django-users+unsubscr...@googlegroups.com. > > For more options, visit this group > > athttp://groups.google.com/group/django-users?hl=en. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Complex Django query - filtering, joining a many-to-many table
Hello Djanglers, I am using a named many-to-many table ("Asking") to join "Questions" to "Users". Asking has some fields I'd like to filter against. I now use a dictionary called filters: filters = {} if 'question' in request.GET: filters['text__icontains'] = request.GET['question'] if 'is_visible' in request.GET: filters['is_visible'] = request.GET['is_visible'] [...] questions = Question.objects.filter(**filters) I need to add filtering by the publish dates of the question, which are stored in the many-to-many join table "Asking", which joins users to questions. I can't figure out how I would do such a thing. model Question: class Question(models.Model): text = models.TextField() question_type = models.ForeignKey('QuestionType') user = models.ManyToManyField(User, through='Asking', null=True) submit_date = models.DateTimeField('Date Submitted', default=datetime.datetime.now) responses = models.IntegerField(default=0) model Asking: class Asking(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question) is_primary_asker = models.BooleanField() is_targeted_answerer = models.BooleanField() question_targeted_date = models.DateTimeField(null=True, blank=True) question_scheduled_post_date = models.DateTimeField(null=True, blank=True) question_published_date = models.DateTimeField(null=True, blank=True) The current filter code: filters = {} if 'question' in request.GET: filters['text__icontains'] = request.GET['question'] if 'is_visible' in request.GET: filters['is_visible'] = request.GET['is_visible'] if 'featured_status' in request.GET: filters['featured_status'] = request.GET['featured_status'] if 'has_responses' in request.GET: filters['responses'] = request.GET['has_responses'] if 'user_id' in request.GET: filters['user'] = request.GET['user_id'] if 'vertical' in request.GET: if not request.GET['vertical'].isdigit(): # if vertical is passed in by name, get id vertical = Vertical.objects.filter(vertical=request.GET['vertical'])[0] filters['verticals'] = vertical.id else: filters['verticals'] = request.GET['vertical'] if filters == {}: logging.debug("no filters, selecting all.") questions = Question.objects.all().order_by(order_by) [offset:limit] else: logging.debug("using filters.") questions = Question.objects.filter(**filters).order_by(order_by)[offset:limit] Thanks for any suggestions! -Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: About extending User model
Carl, scratch my last message. It does work. Woot! Thanks very much. On Mar 26, 2:39 pm, Jim N wrote: > On Mar 26, 1:39 pm, Carl Zmola wrote: > > > > > > > On 03/25/2010 02:37 PM, Jim N wrote: > > > Very interesting, Tom. > > > > I have inserted this code, substituting my profile model name > > > (QotdUser) for UserProfile. It does create a row in QotdUser, but the > > > row is empty of course. > > > > More importantly, if I create a user via the admin interface (http:// > > > 127.0.0.1:8000/admin/auth/user/add/) there's no apparent way to edit > > > any of the fields of my profile model. > > > > Or if I create the user some other way, would I be able to pass > > > arguments to the User model to populate the profile? > > > > Finally, how do I access the profile, is it like > > > > my_user_profile = User.objects.get(username="jim").get_profile() ? > > > > Thanks for the help. > > > I have done this, and I think the following link will > > helphttp://pyxx.org/2008/08/18/how-to-extend-user-model-in-django-and-ena... > > > You need to unregister the current model admin for the user model and > > create a new one (based on the old one) that includes your user profile > > "inline". > > When you understand that last sentence, you will understand what is > > going on. > > > Good luck. > > > -- > > Carl Zmola > > czm...@woti.com > > Hi Carl, > > I've done just what you spelled out, I think, but I don't see any > change in the Home › Auth › Users admin panel. When editing the > individual users, I can edith the fields that are part of the built-in > User model, but not of the profile model. > > Here is the code:http://dpaste.de/OHwA/ > > Here is the relevant part: > > -=-=-=-=-=-=-=-=-=-=-=-= > > class UserProfileInline(admin.TabularInline): > model = QotdUser > fk_name = 'user' > max_num = 1 > list_display = ('identifier', 'service', 'location', > 'featured_status',) > list_filter = ('featured_status', 'service',) > search_fields = ('identifier',) > exclude = ('alternate_id', 'questions_proposed_cnt', > 'questions_published_cnt', 'answers_cnt') > > class MyUserAdmin(UserAdmin): > inlines = [UserProfileInline, ] > > admin.site.unregister(User) > > admin.site.register(User, MyUserAdmin) > > -=-=-=-=-=-=-=-=-=-=-=-= > > Am I missing a class there? > > Regards, > Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: About extending User model
On Mar 26, 1:39 pm, Carl Zmola wrote: > On 03/25/2010 02:37 PM, Jim N wrote: > > Very interesting, Tom. > > > I have inserted this code, substituting my profile model name > > (QotdUser) for UserProfile. It does create a row in QotdUser, but the > > row is empty of course. > > > More importantly, if I create a user via the admin interface (http:// > > 127.0.0.1:8000/admin/auth/user/add/) there's no apparent way to edit > > any of the fields of my profile model. > > > Or if I create the user some other way, would I be able to pass > > arguments to the User model to populate the profile? > > > Finally, how do I access the profile, is it like > > > my_user_profile = User.objects.get(username="jim").get_profile() ? > > > Thanks for the help. > > I have done this, and I think the following link will > helphttp://pyxx.org/2008/08/18/how-to-extend-user-model-in-django-and-ena... > > You need to unregister the current model admin for the user model and > create a new one (based on the old one) that includes your user profile > "inline". > When you understand that last sentence, you will understand what is > going on. > > Good luck. > > -- > Carl Zmola > czm...@woti.com Hi Carl, I've done just what you spelled out, I think, but I don't see any change in the Home › Auth › Users admin panel. When editing the individual users, I can edith the fields that are part of the built-in User model, but not of the profile model. Here is the code: http://dpaste.de/OHwA/ Here is the relevant part: -=-=-=-=-=-=-=-=-=-=-=-= class UserProfileInline(admin.TabularInline): model = QotdUser fk_name = 'user' max_num = 1 list_display = ('identifier', 'service', 'location', 'featured_status',) list_filter = ('featured_status', 'service',) search_fields = ('identifier',) exclude = ('alternate_id', 'questions_proposed_cnt', 'questions_published_cnt', 'answers_cnt') class MyUserAdmin(UserAdmin): inlines = [UserProfileInline, ] admin.site.unregister(User) admin.site.register(User, MyUserAdmin) -=-=-=-=-=-=-=-=-=-=-=-= Am I missing a class there? Regards, Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: About extending User model
Hi Peter, I'm building an app where all logged-in users will be a Django user, rather than creating some new separate class of users just for my own app. But to make it work, these users have to have more than the minimal information contained in the django.contrib.auth.models User. I figure that's a fairly common situation. I may create one class of users through Django's built-in admin. Another class will be created via an API interface to my app. In each case, they need lots of detail missing from User. Is my solution to create the User and update the profile separately every time? I can accept that it is, but was just looking for a more tightly-coupled solution for extending the built-in user. For example, I can't use django.contrib.auth.models User as a foreign key in my models. So how would I link a model instance (row) to a user? This is a question and answer site, so Answer would have a foreign key of User, except that doesn't work. Apologies if this is all spelled out somewhere and I just haven't found it. -Jim On Mar 25, 5:18 pm, Peter Bengtsson wrote: > Generally, try to build your application so that it doesn't blindly > depend on the profile existing. The signal example Tom showed you is > good as it means you won't have to check if the UserProfile instance > exists for the user on every turn. However, don't depend on the data > within. Keep it light and separate. > Why does the admin need the stuff you can put in UserProfile if you > create him via the admin pages? > If he really needs it, tell him to register and then you go in an turn > his created account (in the admin) to a superuser or whatever you > need. > > On 25 Mar, 18:37, Jim N wrote: > > > > > On Mar 11, 1:03 pm, Tom Evans wrote: > > > > On Thu, Mar 11, 2010 at 4:54 PM, russianbandit > > > wrote: > > > > I'm using UserProfile to add one field to my users. However, I know > > > > that I must explicitly create UserProfile for each new user that > > > > registers. So, I make a UserProfile upon registration. Is UserProfile > > > > still the best way to extend the user model? > > > > What about the admin user, or users that the admin creates? Since they > > > > don't go through the registration process, how do I ensure that their > > > > UserProfile gets created? > > > > Add this to your models.py > > > > from django.db.models.signals import post_save > > > from django.contrib.auth.models import User > > > > def _hook_save_user(instance, sender, **kwargs): > > > try: > > > instance.get_profile() > > > except UserProfile.DoesNotExist: > > > UserProfile.objects.get_or_create(user=instance) > > > > post_save.connect(_hook_save_user, sender=User) > > > On Mar 11, 1:03 pm, Tom Evans wrote: > > > > On Thu, Mar 11, 2010 at 4:54 PM, russianbandit > > > wrote: > > > > I'm using UserProfile to add one field to my users. However, I know > > > > that I must explicitly create UserProfile for each new user that > > > > registers. So, I make a UserProfile upon registration. Is UserProfile > > > > still the best way to extend the user model? > > > > What about the admin user, or users that the admin creates? Since they > > > > don't go through the registration process, how do I ensure that their > > > > UserProfile gets created? > > > > Add this to your models.py > > > > from django.db.models.signals import post_save > > > from django.contrib.auth.models import User > > > > def _hook_save_user(instance, sender, **kwargs): > > > try: > > > instance.get_profile() > > > except UserProfile.DoesNotExist: > > > UserProfile.objects.get_or_create(user=instance) > > > > post_save.connect(_hook_save_user, sender=User) > > > Very interesting, Tom. > > > I have inserted this code, substituting my profile model name > > (QotdUser) for UserProfile. It does create a row in QotdUser, but the > > row is empty of course. > > > More importantly, if I create a user via the admin interface (http:// > > 127.0.0.1:8000/admin/auth/user/add/) there's no apparent way to edit > > any of the fields of my profile model. > > > Or if I create the user some other way, would I be able to pass > > arguments to the User model to populate the profile? > > > Finally, how do I access the profile, is it like > > > my_user_profile = User.objects.get(username="jim").get_profile() ? > > > Thanks for the help. > > > -Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: About extending User model
On Mar 11, 1:03 pm, Tom Evans wrote: > On Thu, Mar 11, 2010 at 4:54 PM, russianbandit > wrote: > > I'm using UserProfile to add one field to my users. However, I know > > that I must explicitly create UserProfile for each new user that > > registers. So, I make a UserProfile upon registration. Is UserProfile > > still the best way to extend the user model? > > What about the admin user, or users that the admin creates? Since they > > don't go through the registration process, how do I ensure that their > > UserProfile gets created? > > Add this to your models.py > > from django.db.models.signals import post_save > from django.contrib.auth.models import User > > def _hook_save_user(instance, sender, **kwargs): > try: > instance.get_profile() > except UserProfile.DoesNotExist: > UserProfile.objects.get_or_create(user=instance) > > post_save.connect(_hook_save_user, sender=User) > On Mar 11, 1:03 pm, Tom Evans wrote: > On Thu, Mar 11, 2010 at 4:54 PM, russianbandit > wrote: > > I'm using UserProfile to add one field to my users. However, I know > > that I must explicitly create UserProfile for each new user that > > registers. So, I make a UserProfile upon registration. Is UserProfile > > still the best way to extend the user model? > > What about the admin user, or users that the admin creates? Since they > > don't go through the registration process, how do I ensure that their > > UserProfile gets created? > > Add this to your models.py > > from django.db.models.signals import post_save > from django.contrib.auth.models import User > > def _hook_save_user(instance, sender, **kwargs): > try: > instance.get_profile() > except UserProfile.DoesNotExist: > UserProfile.objects.get_or_create(user=instance) > > post_save.connect(_hook_save_user, sender=User) > Very interesting, Tom. I have inserted this code, substituting my profile model name (QotdUser) for UserProfile. It does create a row in QotdUser, but the row is empty of course. More importantly, if I create a user via the admin interface (http:// 127.0.0.1:8000/admin/auth/user/add/) there's no apparent way to edit any of the fields of my profile model. Or if I create the user some other way, would I be able to pass arguments to the User model to populate the profile? Finally, how do I access the profile, is it like my_user_profile = User.objects.get(username="jim").get_profile() ? Thanks for the help. -Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: basic django auth fails on valid user
Thanks Tim, Yes, I just saw this. I was subclassing auth.User because I didn't know the right way to do it. Now I am on the right track. Just one thing I can't figure out. "When a user profile model has been defined and specified in this manner, each User object will have a method -- get_profile() -- which returns the instance of the user profile model associated with that User. [¶] The method get_profile() does not create the profile, if it does not exist." So the profile is the model that I've created to hold the extra stuff about my user, and it's not automatically created. I can't quite picture where or how it would get created. I have a couple of ways to create a user - through my app when someone takes some actions, or through the django admin. If anyone cares to expound, or share some sample code, that would be great. Thanks, Jim On Mar 24, 7:47 pm, Tim Shaffer wrote: > I think this could all be simplified a bit if you used a UserProfile > model instead of subclassing auth.User. > > http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-... > > Was there a specific reason you were subclassing auth.User? -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: basic django auth fails on valid user
OK, so it seems what's happening is that the password is being stored in `api_qotduser` plain text. I *believe* Django expects a hashed password? More strangeness: I switched to using check_password and NOW Django is querying `api_qotduser`, where before it was querying `auth_user`. New login view: def login_result(request): username = request.POST['u'] password = request.POST['p'] try: user = QotdUser.objects.get(username = username) if user.check_password(password): if user.is_active: login(request, user) t = loader.get_template('login/login_success.html') return HttpResponse(t.render()) else: t = loader.get_template('login/login_disabled.html') return HttpResponse(t.render()) else: # return some error message except QotdUser.DoesNotExist: # return appropriate error message The check_password always fails. The SQL it executes is: SELECT `auth_user`.`id`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`password`, [...] FROM `api_qotduser` INNER JOIN `auth_user` ON (`api_qotduser`.`user_ptr_id` = `auth_user`.`id`) WHERE `auth_user`.`username` = 'ricky' Thanks, Jim On Mar 24, 3:37 pm, Jim N wrote: > Hi, > > I am writing a basic login routine using django users. > > Here is the view: > def login_result(request): > username = request.POST['u'] > password = request.POST['p'] > logging.debug("look for user %s / %s" % (username, password)) > user = authenticate(username=username, password=password) > if user is not None: > logging.debug("found user %s (%s)" % (username, > user.username)) > if user.is_active: > login(request, user) > t = loader.get_template('login/login_success.html') > return HttpResponse(t.render()) > else: > t = loader.get_template('login/login_disabled.html') > return HttpResponse(t.render()) > else: > t = loader.get_template('login/login_no_such_user.html') > u = request.POST['u'] > c = Context({ > 'user': u, > }) > return HttpResponse(t.render(c)) > > It generates the following SQL before returning a login_no_such_user > message (using MySQL backend): > SELECT `auth_user`.`id`, `auth_user`.`username`, > `auth_user`.`first_name`, `auth_user`.`last_name`, > `auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`, > `auth_user`.`is_active`, `auth_user`.`is_superuser`, > `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user` > WHERE `auth_user`.`username` = 'ricky' > > If I run that SQL manually, I get the result I am after. The > submitted passwords also match. > > I suspect my problem may be my user model, subclassed from > django.contrib.auth.models User: > - - - - > class QotdUser(User): > alternate_id = models.CharField(max_length=200, null=True) > identifier = models.CharField(max_length=200, null=True) > service = models.CharField(max_length=200, null=True) > location = models.CharField(max_length=200, null=True, > blank=True) > profile_url = models.URLField(null=True) > questions_proposed_cnt = models.IntegerField(default=0) > questions_published_cnt = models.IntegerField(default=0) > answers_cnt = models.IntegerField(default=0) > featured_status = models.BooleanField("Is Featured", > default=False) > icon = models.ImageField(upload_to=settings.UPLOAD_PATH, > blank=True, null=True) > > def __unicode__(self): > return self.identifier > > def has_answers(self): > return self.answers_cnt > 0 > > def increment_answers(self): > self.answers_cnt = self.answers_cnt + 1 > self.save() > logging.debug("increment answers to %d in QotdUser %s" % > (self.answers_cnt, self.identifier)) > > def decrement_answers(self): > self.answers_cnt = self.answers_cnt - 1 > self.save() > logging.debug("decrement answers to %d in QotdUser %s" % > (self.answers_cnt, self.identifier)) > > - - - - > > That is the user model that I have defined, but Django is doing > something I don't understand. It is referring to the auth_user table > instead. When I create a user using the admin, the user is created in > both auth_user and the user table for my app, api_qotduser. > > Can anyone help me figure out what is going on? Have I subclassed > User from django.contrib.auth.models wrong? > > Thanks, > Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
basic django auth fails on valid user
Hi, I am writing a basic login routine using django users. Here is the view: def login_result(request): username = request.POST['u'] password = request.POST['p'] logging.debug("look for user %s / %s" % (username, password)) user = authenticate(username=username, password=password) if user is not None: logging.debug("found user %s (%s)" % (username, user.username)) if user.is_active: login(request, user) t = loader.get_template('login/login_success.html') return HttpResponse(t.render()) else: t = loader.get_template('login/login_disabled.html') return HttpResponse(t.render()) else: t = loader.get_template('login/login_no_such_user.html') u = request.POST['u'] c = Context({ 'user': u, }) return HttpResponse(t.render(c)) It generates the following SQL before returning a login_no_such_user message (using MySQL backend): SELECT `auth_user`.`id`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`is_superuser`, `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user` WHERE `auth_user`.`username` = 'ricky' If I run that SQL manually, I get the result I am after. The submitted passwords also match. I suspect my problem may be my user model, subclassed from django.contrib.auth.models User: - - - - class QotdUser(User): alternate_id = models.CharField(max_length=200, null=True) identifier = models.CharField(max_length=200, null=True) service = models.CharField(max_length=200, null=True) location = models.CharField(max_length=200, null=True, blank=True) profile_url = models.URLField(null=True) questions_proposed_cnt = models.IntegerField(default=0) questions_published_cnt = models.IntegerField(default=0) answers_cnt = models.IntegerField(default=0) featured_status = models.BooleanField("Is Featured", default=False) icon = models.ImageField(upload_to=settings.UPLOAD_PATH, blank=True, null=True) def __unicode__(self): return self.identifier def has_answers(self): return self.answers_cnt > 0 def increment_answers(self): self.answers_cnt = self.answers_cnt + 1 self.save() logging.debug("increment answers to %d in QotdUser %s" % (self.answers_cnt, self.identifier)) def decrement_answers(self): self.answers_cnt = self.answers_cnt - 1 self.save() logging.debug("decrement answers to %d in QotdUser %s" % (self.answers_cnt, self.identifier)) - - - - That is the user model that I have defined, but Django is doing something I don't understand. It is referring to the auth_user table instead. When I create a user using the admin, the user is created in both auth_user and the user table for my app, api_qotduser. Can anyone help me figure out what is going on? Have I subclassed User from django.contrib.auth.models wrong? Thanks, Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Serializing objects with a many-to-many reference
I just came across manager methods in the docs: http://docs.djangoproject.com/en/dev/topics/db/managers/#adding-extra-manager-methods Could I have used these to create a seriallizable QuerySet, by defining, say, a with_user() method inside the Questions model? -Jim On Mar 3, 10:21 am, Jim N wrote: > Thanks Russell, > > I ended up writing it myself - breaking the QuerySet into a > dictionary, grabbing and plugging in the information from the other > model, and then re-serializing it not using the serializer.serialize, > but the simplejson.dumps. > > I'll check out DjangoFullSerializers for future reference though. It > seems like this kind of thing must come up all the time. > > -Jim > > On Mar 2, 6:45 pm, Russell Keith-Magee wrote: > > > On Wed, Mar 3, 2010 at 12:46 AM, Jim N wrote: > > > Hi, > > > > I am writing a question-and-answer app which serializes data in JSON. > > > I have Question, User, and Asking models. Asking is the many-to-many > > > relationship table for Question and User, because the Asking > > > relationship may be more complicated than it seems. (Several users > > > may ask, and re-ask the same question, and I need to store when the > > > question was asked, whether the asker is primary or secondary, publish > > > date for the question, etc.) > > > > The problem comes when I serialize a Question. I want to get the User > > > information in the serialized object. > > > > Models: > > > > class User(models.Model): > > > alternate_id = models.CharField(max_length=200, null=True) > > > identifier = models.CharField(max_length=200, null=True) > > > > class Asking(models.Model): > > > user = models.ForeignKey(User) > > > question = models.ForeignKey(Question) > > > is_primary_asker = models.BooleanField() > > > > class Question(models.Model): > > > text = models.TextField() > > > user = models.ManyToManyField('User', through='Asking', null=True) > > > > In the view: > > > > questions = Question.objects.filter(**filters) > > > return serializers.serialize("json", questions) > > > > That's not giving me anything but a user Id. > > > > I looked at natural keys, but I'm using Django 1.1.1. > > > > Thanks for any suggestions. > > > The short answer is you can't - at least, not out of the box. This is > > a feature that has been proposed several times [1] in the past. > > Django's serializers are primarily designed for use in the testing > > system, where the exact structure of the serialized output isn't as > > important. > > > At some point, I'm hoping to be able to do a full teardown of the > > serialization infrastructure to make it completely configurable. This > > would enable features like [1], along with many others. > > > In the interim, there is a third-party project called "Django Full > > Serializers" [2] that includes this sort of functionality. > > > [1]http://code.djangoproject.com/ticket/4656 > > [2]http://code.google.com/p/wadofstuff/wiki/DjangoFullSerializers > > > Yours, > > Russ Magee %-) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Serializing objects with a many-to-many reference
Thanks Russell, I ended up writing it myself - breaking the QuerySet into a dictionary, grabbing and plugging in the information from the other model, and then re-serializing it not using the serializer.serialize, but the simplejson.dumps. I'll check out DjangoFullSerializers for future reference though. It seems like this kind of thing must come up all the time. -Jim On Mar 2, 6:45 pm, Russell Keith-Magee wrote: > On Wed, Mar 3, 2010 at 12:46 AM, Jim N wrote: > > Hi, > > > I am writing a question-and-answer app which serializes data in JSON. > > I have Question, User, and Asking models. Asking is the many-to-many > > relationship table for Question and User, because the Asking > > relationship may be more complicated than it seems. (Several users > > may ask, and re-ask the same question, and I need to store when the > > question was asked, whether the asker is primary or secondary, publish > > date for the question, etc.) > > > The problem comes when I serialize a Question. I want to get the User > > information in the serialized object. > > > Models: > > > class User(models.Model): > > alternate_id = models.CharField(max_length=200, null=True) > > identifier = models.CharField(max_length=200, null=True) > > > class Asking(models.Model): > > user = models.ForeignKey(User) > > question = models.ForeignKey(Question) > > is_primary_asker = models.BooleanField() > > > class Question(models.Model): > > text = models.TextField() > > user = models.ManyToManyField('User', through='Asking', null=True) > > > In the view: > > > questions = Question.objects.filter(**filters) > > return serializers.serialize("json", questions) > > > That's not giving me anything but a user Id. > > > I looked at natural keys, but I'm using Django 1.1.1. > > > Thanks for any suggestions. > > The short answer is you can't - at least, not out of the box. This is > a feature that has been proposed several times [1] in the past. > Django's serializers are primarily designed for use in the testing > system, where the exact structure of the serialized output isn't as > important. > > At some point, I'm hoping to be able to do a full teardown of the > serialization infrastructure to make it completely configurable. This > would enable features like [1], along with many others. > > In the interim, there is a third-party project called "Django Full > Serializers" [2] that includes this sort of functionality. > > [1]http://code.djangoproject.com/ticket/4656 > [2]http://code.google.com/p/wadofstuff/wiki/DjangoFullSerializers > > Yours, > Russ Magee %-) -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Serializing objects with a many-to-many reference
Hi, I am writing a question-and-answer app which serializes data in JSON. I have Question, User, and Asking models. Asking is the many-to-many relationship table for Question and User, because the Asking relationship may be more complicated than it seems. (Several users may ask, and re-ask the same question, and I need to store when the question was asked, whether the asker is primary or secondary, publish date for the question, etc.) The problem comes when I serialize a Question. I want to get the User information in the serialized object. Models: class User(models.Model): alternate_id = models.CharField(max_length=200, null=True) identifier = models.CharField(max_length=200, null=True) class Asking(models.Model): user = models.ForeignKey(User) question = models.ForeignKey(Question) is_primary_asker = models.BooleanField() class Question(models.Model): text = models.TextField() user = models.ManyToManyField('User', through='Asking', null=True) In the view: questions = Question.objects.filter(**filters) return serializers.serialize("json", questions) That's not giving me anything but a user Id. I looked at natural keys, but I'm using Django 1.1.1. Thanks for any suggestions. -Jim -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.