سؤال

I am using the SelectDateWidget with django-registration to save a Birth Date at registration. I have tried excluding the birthday and the a profile is created and saved with the extra data. I am not quite sure where everything is going wrong.

models.py

class Profile(models.Model):
    ...
    dob = models.DateField(_('birthday'))

forms.py

from django.forms.extras.widgets import SelectDateWidget

class ProfileRegistration(RegistrationFormTermsOfService):
    ...
    dob = forms.DateField(widget=SelectDateWidget(years=range(1999,1939,-1)),
                          label=_("Birthday"),
                          )

prifilebackend.py

from registration.forms import RegistrationForm
from registration.models import RegistrationProfile

    ...
    class Backend(default.DefaultBackend):
        ...
        p = Profile.objects.get(user=new_user)
        p.dob=kwargs['dob']
        p.save()

The error I am getting when registering the user is: profile_profile.dob may not be NULL

The post data is generating dob_day, dob_month and dob_year. i have tried to clean the data but to no avail. Any assistance would be greatly appreciated.

Solved:

profilebackend.py

signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)

        u = User.objects.get(username=new_user.username)
        u.first_name = kwargs['first_name']
        u.last_name = kwargs['last_name']

        gender = kwargs['gender']
        dob = kwargs['dob']

        p = Profile(user = new_user, gender = gender, dob = dob)
        p.save()
        u.save()
هل كانت مفيدة؟

المحلول

The cleaned data from the bound form instance should include the correct date object, if the form has no errors.

Use this date object to assign it to p.dob

I don't quite get how you process your registration form, but in general it works like this: After the form is submitted by the user, you create a bound form, make sure it is valid and then access the cleaned form data. Something like this:

# forms.py
...
class RegistrationForm(forms.Form):
    ...
    dob = forms.DateField(widget=widgets.SelectDateWidget())

# views.py
...
def myform_view(request):
    ...
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            dob = form.cleaned_data.get('dob')
            # dob is now a python date object
            do_something_with_birthday(dob)

If the dob date object is still None or empty when trying to save it using your backend, I'd suggest you start debugging your code. You can install django_extensions and run a development server with ./manage.py runserver_plus to get a nice interactive stack trace of this exception. Alternatively, you can also debug your code with pdb.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top