Re: Need help with my Form.save() method. Trouble with ForeignKey and ManyToMany Fields.
Yep. I used Firebug to look at the HTTP information and "username" is in there. Here's what firebug shows: Parametersapplication/x-www-form-urlencoded address P.O. Box 56868 areas 1 birth_date 1979-10-09 cityPuyallup country USA csrfmiddlewaretoken 0258a209df8a7df0ccca24ce789a448e email someem...@hotmail.com first_name Toby last_name Beal password1 1234 password2 1234 phone 253-555-555 state_province WA usernametobybeal zip_code98379 I believe that the problem isn't with the form creation or submission but with my save method. The error seems to be specific to the way in which I'm trying to create a new user. Here's my save method from the form again. # Taken from registration.forms.py def save(self): # User new_user = User.objects.create_user(username=self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password1']) new_user.first_name = self.cleaned_data['first_name'] new_user.last_name = self.cleaned_data['last_name'] new_user.is_active = True new_user.save() # Profile new_profile = UserProfile.objects.create() new_profile.user = User.objects.get(username__exact=self.cleaned_data['username']) new_profile.phone = self.cleaned_data['phone'] new_profile.address = self.cleaned_data['address'] new_profile.city = self.cleaned_data['city'] new_profile.state_province = self.cleaned_data['state_province'] new_profile.country = self.cleaned_data['country'] new_profile.zip_code = self.cleaned_data['zip_code'] new_profile.birth_date = self.cleaned_data['birth_date'] new_profile.areas = self.cleaned_data['areas'] new_profile.save() return What should I be doing differently with this snippet? new_user = User.objects.create_user(username=self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password1']) Thanks. ~trb On Aug 5, 4:32 am, Paulo Almeida wrote: > Can you check the POST data and see if 'username' is there? You can do it > easily with Firefox's Firebug extension. > > - Paulo > > On Thu, Aug 5, 2010 at 6:24 AM, strayhand wrote: > > So I'm rolling out my own registration form that should update the > > following models: > > > - User (auth module) > > - UserProfile > > > Everything seems to be coming together but I'm having a hard time with > > the save() method for the form. My UserProfile model has a couple of > > fields that refer to other models and I'm having difficulty setting > > them up properly. I keep getting an error telling me: > > > Exception Type: IntegrityError at /registration/ > > Exception Value: auth_user.username may not be NULL > > > I know where the problems are: > > > new_user = > > User.objects.create_user(username=self.cleaned_data['username'], > > email=self.cleaned_data['email'], > > password=self.cleaned_data['password1']) > > > and I'm getting this similar error for defining the user profile on > > the line below. > > > new_profile.user = > > User.objects.get(username__exact=self.cleaned_data['username']) > > > I'm just not sure how else to write this stuff. I'm including my form, > > model and the exact error message that I'm getting below. Any insight > > that you have is greatly appreciated. Thank you. > > > # registration.forms.py > > > import re > > from django import forms > > from django.db import models > > from django.contrib.localflavor.us.forms import USPhoneNumberField > > from django.contrib.auth.models import User > > from ylbbq.areas.models import Area > > from ylbbq.profiles.models import UserProfile > > > STATES = ( > > ('WA', 'Washington'), > > ('AK', 'Alaska'), > > ('AL', 'Alabama'), > > ('AR', 'Arkansas'), > > ('AZ', 'Arizona'), > > ('CA', 'California'), > > ('CO', 'Colorado'), > > ('CT', 'Connecticut'), > > ('DE', 'Delaware'), > > ('FL', 'Florida'), > > (
Need help with my Form.save() method. Trouble with ForeignKey and ManyToMany Fields.
So I'm rolling out my own registration form that should update the following models: - User (auth module) - UserProfile Everything seems to be coming together but I'm having a hard time with the save() method for the form. My UserProfile model has a couple of fields that refer to other models and I'm having difficulty setting them up properly. I keep getting an error telling me: Exception Type: IntegrityError at /registration/ Exception Value: auth_user.username may not be NULL I know where the problems are: new_user = User.objects.create_user(username=self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password1']) and I'm getting this similar error for defining the user profile on the line below. new_profile.user = User.objects.get(username__exact=self.cleaned_data['username']) I'm just not sure how else to write this stuff. I'm including my form, model and the exact error message that I'm getting below. Any insight that you have is greatly appreciated. Thank you. # registration.forms.py import re from django import forms from django.db import models from django.contrib.localflavor.us.forms import USPhoneNumberField from django.contrib.auth.models import User from ylbbq.areas.models import Area from ylbbq.profiles.models import UserProfile STATES = ( ('WA', 'Washington'), ('AK', 'Alaska'), ('AL', 'Alabama'), ('AR', 'Arkansas'), ('AZ', 'Arizona'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DE', 'Delaware'), ('FL', 'Florida'), ('GA', 'Georgia'), ('HI', 'Hawaii'), ('IA', 'Iowa'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('MA', 'Massachusetts'), ('MD', 'Maryland'), ('ME', 'Maine'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MO', 'Missouri'), ('MS', 'Mississippi'), ('MT', 'Montana'), ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('NE', 'Nebraska'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NV', 'Nevada'), ('NY', 'New York'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PA', 'Pennsylvania'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'), ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VT', 'Vermont'), ('VA', 'Virginia'), ('WI', 'Wisconsin'), ('WV', 'West Virginia'), ('WY', 'Wyoming'), ('AB', 'Alberta'), ('BC', 'British Columbia'), ('MB', 'Manitoba'), ('NB', 'New Brunswick'), ('NL', 'Newfoundland and Labrador'), ('NS', 'Nova Scotia'), ('NT', 'Northwest Territories'), ('NU', 'Nunavut'), ('ON', 'Ontario'), ('PE', 'Prince Edward Island'), ('QC', 'Quebec'), ('SK', 'Saskatchewan'), ('YT', 'Yukon'), ) COUNTRIES = ( ('USA', 'United States'), ('Canada', 'Canada') ) POSTAL_CODE_PATTERN = re.compile(r'^\d{5}-\d{4}|\d{5}|[A-Z]\d[A-Z] \d[A-Z]\d$') class RegisterForm(forms.Form): username = forms.CharField(max_length=30, help_text='Create a user name for this Web site.') first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) password1 = forms.CharField(max_length=60, label='Password', widget=forms.PasswordInput) password2 = forms.CharField(max_length=60, label='Password Confirmation', widget=forms.PasswordInput) email = forms.EmailField(help_text='Enter a valid e-mail address.') phone = USPhoneNumberField(max_length=12, help_text='Enter your phone number in the following format: 253-123-5678.') address = forms.CharField(max_length=70, help_text='Enter mailing address.') city = forms.CharField(max_length=50) state_province = forms.ChoiceField(choices=STATES, label='State or Province') country = forms.ChoiceField(choices=COUNTRIES) zip_code = forms.CharField(max_length=10, label='Mailing Code', help_text='Enter your zip code (US or Canadian).') birth_date = forms.DateField(help_text='Enter your birthdate in the following format: 1979-09-29 (-MM-DD).') areas = forms.ModelMultipleChoiceField(queryset=Area.objects.all(), label='Preferred Areas', help_text='Select the areas that you\'d like to serve.') def clean_username(self): data = self.cleaned_data['username'] try: User.objects.get(username=data) except User.DoesNotExist: return raise forms.ValidationError('The username "%s" is already taken.' % data) def clean_zip
Re: How do I populate a multi-select field with a single column from a model?
Sweet. That did the trick. I found an example here: http://www.djangoproject.com/documentation/models/str/ # Areas Model UPDATED from django.db import models # Create your models here. class Area(models.Model): name = models.CharField(max_length=40) city = models.CharField(max_length=50) phone = models.CharField(max_length=12) email = models.EmailField() def __unicode__(self): return self.name On Jul 31, 4:31 am, Daniel Roseman wrote: > On Jul 31, 10:07 am, strayhand wrote: > > > I want to grab a single column in a model and use it to populate a > > multi-select form field. Here's the code that I'm currently using: > > > areas = forms.ModelMultipleChoiceField(queryset=Area.objects.all(), > > label='Preferred Areas', help_text='Select the areas that you\'d like > > to serve.') > > > This code returns the entire Model. I tried using > > queryset=Area.values('name') and it didn't work. How am I suppose to > > grab a single column out of a model? My model and form code have been > > provided below. Thanks. > > I don't know what you mean by 'returns the entire Model'. Model choice > fields use as their display values the __unicode__ value of the items > in the queryset. If that isn't defined, you'll get something like > "Area object". The solution is simply to define a __unicode__ method, > which is good practice anyway. > -- > DR. -- 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: How do I populate a multi-select field with a single column from a model?
Ah... Well that's exactly what's happening. I'm getting "Area Object" for each element in the select box. I've seen the __unicode__ method on a few model examples, but my book and other resources never really showed or explained it. I'll see if I can find some explanation of it. Thanks for the clue. On Jul 31, 4:31 am, Daniel Roseman wrote: > On Jul 31, 10:07 am, strayhand wrote: > > > I want to grab a single column in a model and use it to populate a > > multi-select form field. Here's the code that I'm currently using: > > > areas = forms.ModelMultipleChoiceField(queryset=Area.objects.all(), > > label='Preferred Areas', help_text='Select the areas that you\'d like > > to serve.') > > > This code returns the entire Model. I tried using > > queryset=Area.values('name') and it didn't work. How am I suppose to > > grab a single column out of a model? My model and form code have been > > provided below. Thanks. > > I don't know what you mean by 'returns the entire Model'. Model choice > fields use as their display values the __unicode__ value of the items > in the queryset. If that isn't defined, you'll get something like > "Area object". The solution is simply to define a __unicode__ method, > which is good practice anyway. > -- > DR. -- 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.
How do I populate a multi-select field with a single column from a model?
I want to grab a single column in a model and use it to populate a multi-select form field. Here's the code that I'm currently using: areas = forms.ModelMultipleChoiceField(queryset=Area.objects.all(), label='Preferred Areas', help_text='Select the areas that you\'d like to serve.') This code returns the entire Model. I tried using queryset=Area.values('name') and it didn't work. How am I suppose to grab a single column out of a model? My model and form code have been provided below. Thanks. #register.forms from django import forms from django.db import models from django.forms import ModelForm from ylbbq.areas.models import Area STATES = ( ('AK', 'Alaska'), ... ('YT', 'Yukon'), ) COUNTRIES = ( ('USA', 'United States'), ('Canada', 'Canada') ) class RegisterForm(forms.Form): username = forms.CharField(max_length=30) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) password1 = forms.CharField(max_length=60) password2 = forms.CharField(max_length=60) email = forms.EmailField(help_text='Enter a valid e-mail address.') phone = forms.CharField(max_length=12) address = forms.CharField(max_length=70) city = forms.CharField(max_length=50) state_province = forms.ChoiceField(choices=STATES, label='State or Province') country = forms.ChoiceField(choices=COUNTRIES) zip_code = forms.CharField(max_length=5) birth_date = forms.DateField() areas = forms.ModelMultipleChoiceField(queryset=Area.objects.all(), label='Preferred Areas', help_text='Select the areas that you\'d like to serve.') # areas.model from django.db import models class Area(models.Model): name = models.CharField(max_length=40) city = models.CharField(max_length=50) phone = models.CharField(max_length=12) email = models.EmailField() -- 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: User Registration: Looking for tips
Euan, Thank you for the response. I agree with what you're saying and it seems that I have two options before me. 1. Define simple form class for my registration process. Write a save method that posts to both the "User" model and the "UserProfile" model. I could start this process from scratch but I came across this post that I'm interested in. Have you by chance looked at any of the work James Bennett (http://www.b-list.org/) has done with registration? He has essentially taken the UserCreationForm as a guide and reworked it to save the form to two models. In this example he's storing activation key in the UserProfile model. http://www.b-list.org/weblog/2006/sep/02/django-tips-user-registration/ I think that I could use what he's demonstrating here and add my own fields. What are your thoughts on this code? There are a few comments below his post that I'll need to keep in mind. My main concern is how old the post is. I don't want to waste a lot of time with this approach only to find out that Django has gone in a different direction. 2. The second option would be to try the django-registration module and make some tweaks. Do you (or anyone else out there) have any experience with this module? http://bitbucket.org/ubernostrum/django-registration/overview Seems like this would get me up and running with a registration system a little more advanced than I currently have but it would still need to be tweaked to include all of my profile fields. Here's a blog post about tweaking the django-registration form by extending the class: http://dewful.com/?p=70 Please let me know if you guys have opinions one way or another about these two approaches. Thank you. On Jul 28, 11:47 pm, "euan.godd...@googlemail.com" wrote: > For the UserProfle model you've provided you won't be able to user > the UserCreationForm as there are a load of extra fields. Moreover > because User is a foreign key from that model it isn't a straight- > forward matter of using a model form. To get a single model form to > split the work to two underlying models would be a fair bit of work. > > Although ModelForm is great, if you want to do things which are a bit > off what they were intended to do I'd use a simple Form and create a > custom save method that writes out the data to the two models. That's > how we do our registration process since we create at least 6 model > instances at join time. > > Euan > > On 29 July, 06:45, strayhand wrote: > > > I'm using the auth module for my project and I've got a registration > > form that's based on the "UserCreationForm" provided by > > "django.contrib.auth.forms" but it's only showing the username and > > password fields. > > > I want a registration process that requires users to fill out ALL of > > the "User" fields plus the fields in my "UserProfile" model. > > > If someone has some basic suggestions for how to modify the > > UserCreationForm to include these additional fields I'm all ears. I > > managed to find some basic examples of how to hide certain ModelForm > > fields or change their labels but nothing about adding additional > > fields, particularly from other models. > > > In addition to modifying the UserCreationForm I've come across a > > couple of leads: > > > 1. Build my own registration process following this example: > > >http://www.b-list.org/weblog/2006/sep/02/django-tips-user-registration/ > > > I'm concerned with how old this post is. Is this approach still valid > > given that it was posted in 2006? The author is using both the User > > model and his own UserProfile model. I think that I could adapt this > > for my purpose. > > > 2. Use the django-registration package provided by the same author > > >http://bitbucket.org/ubernostrum/django-registration/overview > > > I'm concerned with having to install additional packages into Django. > > It seems like this will make deploying my application on a Web host > > more difficult. Can anyone speak to this? > > > Thank you for your suggestions. I've provided my code thus far below. > > > # forms.py > > > from django import forms > > from django.contrib.auth.forms import UserCreationForm > > from django.http import HttpResponseRedirect > > from django.shortcuts import render_to_response > > from django.template import RequestContext > > > def register(request): > > if request.method == 'POST': > > form = UserCreationForm(request.POST) > > if form.is_valid(): > > n
User Registration: Looking for tips
I'm using the auth module for my project and I've got a registration form that's based on the "UserCreationForm" provided by "django.contrib.auth.forms" but it's only showing the username and password fields. I want a registration process that requires users to fill out ALL of the "User" fields plus the fields in my "UserProfile" model. If someone has some basic suggestions for how to modify the UserCreationForm to include these additional fields I'm all ears. I managed to find some basic examples of how to hide certain ModelForm fields or change their labels but nothing about adding additional fields, particularly from other models. In addition to modifying the UserCreationForm I've come across a couple of leads: 1. Build my own registration process following this example: http://www.b-list.org/weblog/2006/sep/02/django-tips-user-registration/ I'm concerned with how old this post is. Is this approach still valid given that it was posted in 2006? The author is using both the User model and his own UserProfile model. I think that I could adapt this for my purpose. 2. Use the django-registration package provided by the same author http://bitbucket.org/ubernostrum/django-registration/overview I'm concerned with having to install additional packages into Django. It seems like this will make deploying my application on a Web host more difficult. Can anyone speak to this? Thank you for your suggestions. I've provided my code thus far below. # forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("/somewhere/") else: form = UserCreationForm() return render_to_response("registration/register.html", {'form':form,}, context_instance=RequestContext(request)) # profiles.models.py from django.db import models from django.contrib.auth.models import User from ylbbq.areas.models import Area class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) phone = models.CharField(max_length=12) address = models.CharField(max_length=70) city = models.CharField(max_length=50) STATES = ( ('AK', 'Alaska'), ... ) state_province = models.CharField(max_length=2, choices=STATES, verbose_name='State or Province') COUNTRIES = ( ('USA', 'United States'), ('Canada', 'Canada') ) country = models.CharField(max_length=20, choices=COUNTRIES) zip_code = models.CharField(max_length=5) birth_date = models.DateField() areas = models.ManyToManyField(Area) # templates/registration/register.html {% extends "base.html" %} {% block title %} Account Registration {% endblock %} {% block content %} Create an account {% csrf_token %} {{ form.as_p }} {% endblock %} -- 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: DateTimeField Validation Error
Doah! Thanks. On Jul 27, 2:04 am, Daniel Roseman wrote: > On Jul 27, 6:34 am, strayhand wrote: > > > I don't get why I'm getting a validation error with my code. I thought > > that all of the built in fields are referenced inside of "from > > django.db import models". Thanks for any help that you may offer. > > > > > status = models.CharField(max_length=7, choices=STATUS_OPTIONS) > > submit_date = DateTimeField(auto_now_add=True) > > change_date = DateTimeField(auto_now=True) > > They are, but you're not referring to it there. Everywhere else, you > use models.Field - but for some reason on these two > DateTimeFields you've missed off the 'models.' reference. > -- > DR. -- 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.
DateTimeField Validation Error
I don't get why I'm getting a validation error with my code. I thought that all of the built in fields are referenced inside of "from django.db import models". Thanks for any help that you may offer. ERROR NameError: name 'DateTimeField' is not defined CODE #shifts.models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Shift(models.Model): SHIFT_OPTIONS = ( ('Shift A', 'Shift A'), ('Shift B', 'Shift B'), ('Shift C', 'Shift C'), ('Shift D', 'Shift D'), ) name = models.CharField(max_length=7, choices=SHIFT_OPTIONS, verbose_name='Shift Name') date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() class Schedule(models.Model): # Shift shift = models.ForeignKey(Shift, unique=True) # User user = models.ForeignKey(User, unique=True) # Other STATUS_OPTIONS = ( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Denied', 'Denied'), ) status = models.CharField(max_length=7, choices=STATUS_OPTIONS) submit_date = DateTimeField(auto_now_add=True) change_date = DateTimeField(auto_now=True) -- 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: Newbie Question: Syntax Error - Form Class, trying to set e-mail field to required=False
S. Thanks! I'm completely new to Python (guess I should have paid more attention to variable names). I might have tried removed the dash sooner but I was following how it was typed in the book. I'll have to file a type with the author. Thanks again. On Jul 22, 5:56 am, Simon Holness wrote: > "e-mail" can't have a hyphen in it. Python thinks you're "assigning" > to the operation e - mail > > just type into a shell to see. > > e-mail = "blah" > SyntaxError: can't assign to operator > > rename to e_mail or email or something and you should be good to go > > On 22 July 2010 06:10, strayhand wrote: > > > I apologize in advance if i'm posting this question in the wrong area. > > I'm learning about django's form class in "The Definitive Guide To > > Django" and for some reason that's beyond me I keep getting a syntax > > error. I've been over my code a dozen times and I'm hoping that > > someone can point me in the right direction. > > > (Taken from page 133-134) > > > contactforms.py > > > from django import forms > > > class ContactForm(forms.Form): > > subject = forms.CharField() > > e-mail = forms.EmailField(required=False) > > message = forms.CharField() > > > When I jump into the shell and type the following I get the syntax > > error: > > > from contactforms import ContactForms > > Traceback (most recent call last): > > File "", line 1, in > > File "/Users/bealtr/Personal/YLBBQ/Django Projects/ylbbq/ > > contactforms.py", line 5 > > e-mail = forms.EmailField(required=False) > > SyntaxError: can't assign to operator > > > What am I doing wrong? > > > -- > > 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.
Newbie Question: Syntax Error - Form Class, trying to set e-mail field to required=False
I apologize in advance if i'm posting this question in the wrong area. I'm learning about django's form class in "The Definitive Guide To Django" and for some reason that's beyond me I keep getting a syntax error. I've been over my code a dozen times and I'm hoping that someone can point me in the right direction. (Taken from page 133-134) contactforms.py from django import forms class ContactForm(forms.Form): subject = forms.CharField() e-mail = forms.EmailField(required=False) message = forms.CharField() When I jump into the shell and type the following I get the syntax error: from contactforms import ContactForms Traceback (most recent call last): File "", line 1, in File "/Users/bealtr/Personal/YLBBQ/Django Projects/ylbbq/ contactforms.py", line 5 e-mail = forms.EmailField(required=False) SyntaxError: can't assign to operator What am I doing wrong? -- 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.