3

Django version: 4.0.2 Django-Registration version: 0.8 App name: userAccounts

PROBLEM: Im trying to create a user type called professor extending the user model. I can complete the registration process, the problem is that only the user is saved on the DB, the professor table keep empty. So i think the problem could be in the save method. Some clue about what could be the problem?

SETTINGS.PY

AUTH_PROFILE_MODULE = "userAccounts.Professor"

MODELS.PY - Here i create the model that extending from user and a example field

from django.db import models
from django.contrib.auth.models import User

class Professor(models.Model):
  user = models.ForeignKey(User, unique=True)
  exampleField = models.CharField(max_length=100)

FORMS.PY - When a user is saved, i save a new_profile in the professor table.

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

class CustomRegistrationForm(RegistrationForm):
  exampleField = forms.CharField()

  def save(self, profile_callback=None):
    new_user = RegistrationProfile.objects.create_inactive_user(
        username=self.cleaned_data['username'],
        password=self.cleaned_data['password1'],
        email = self.cleaned_data['email'])
    new_professor = Professor(
        user=new_user, 
        exampleField=self.cleaned_data['exampleField'])
    new_professor.save()
    return new_user

NOTE: Im following this post: Registration form with profile's field

Community
  • 1
  • 1
Adrian Lopez
  • 2,601
  • 5
  • 31
  • 48
  • FYI, the Professor model does not extend the User model, it is creating a foreign key reference to the User model. – matt snider Feb 08 '13 at 01:27
  • Also, what is the error that Django is throwing? – matt snider Feb 08 '13 at 01:28
  • There's no error, i can complete the registration process. The problem is that the userAccounts_profile table keep empty in MySQL, while the user is added correctly. – Adrian Lopez Feb 08 '13 at 01:42
  • Where are you defining the Profile model? The code above should error, as Profile is not defined/included anywhere. If you replace Profile with Professor, it should save to the userAccount_professor table. – matt snider Feb 08 '13 at 01:48
  • Thanks for your help! The profile model was from an previous try. I fixed it, sadly the problem persist. I updated the code. – Adrian Lopez Feb 08 '13 at 02:21
  • Hm... not sure, but you could also try to replace the instantiation and save lines with Professor.objects.create(user=new_user,exampleField=self.cleaned_data['exampleField']) – matt snider Feb 08 '13 at 02:52
  • Are you familiar with pdb? if you put "import pdb; pdb.set_trace()" in your code right after the user is created, then you can step through it and do some debugging. Django would error, if it couldn't save the model correctly, so there are really 3 possibilities: you have overwritten the save function, it is writing to another table than the one your are checking, or there is an error that is being captured and swallowed. – matt snider Feb 08 '13 at 19:27
  • @mattsnider, good idea. Make sure the lines of code are being executed first. – Victor 'Chris' Cabral Feb 08 '13 at 19:39
  • problem solved, post updated. All working. Thanks!! – Adrian Lopez Feb 12 '13 at 20:24

1 Answers1

4

PROBLEM SOLVED - SOLUTION

Have been some days but i got it! :D i found this post from shacker: Django-Registration & Django-Profile, using your own custom form

apparently in django-registration 0.8 save() method can't be override. so, the other two options are: Use signals or Rewrite the backend.

both solutions are explained in the post i linked. If someone have the same problem i'll try to help in the comments :)

NOTE: Using signals worked fine but i had some problems taking the values from the form. So i implemented the backend method and everything went ok. I strongly recomend you read shacker's post but, if you are really desesperate, theres my code:

my forms.py

class RegistrationForm(forms.Form):
    username = forms.RegexField(regex=r'^\w+$',
                            max_length=30,
                            widget=forms.TextInput(attrs=attrs_dict),
                            label=_("Username"),
                            error_messages={'invalid': _("This value must contain only letters, numbers and underscores.")})
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
                                                           maxlength=75)),
                         label=_("Email address"))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                            label=_("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                            label=_("Password (again)"))

    #ADITIONAL FIELDS
    #they are passed to the backend as kwargs and there they are saved
    nombre = forms.CharField(widget=forms.TextInput(attrs=attrs_dict),
                            label=_("Nombre"))

__init__.py (app/user_backend/__init__.py)

class DefaultBackend(object):
def register(self, request, **kwargs):
        username, email, password, nombre = kwargs['username'], kwargs['email'], kwargs['password1'], kwargs['nombre']
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                                password, site)
        signals.user_registered.send(sender=self.__class__,
                                 user=new_user,
                                 request=request)

        usuario(user = User.objects.get(username=new_user.username), nombre=nombre).save()
        return new_user

root URLS.PY before this line -> url(r'profiles/', include('profiles.urls')),

    url(r'^accounts/registrar_usuario/$',
'registration.views.register',
{'backend': 'Hesperides.apps.accounts.user_regbackend.DefaultBackend','form_class':user_RegistrationForm},        
name='registration_register'
),

Thanks

mattsnider for your patience and for show me the very, very usefull pdb. Regards from spain. and: shacker and dmitko for show me the way

Community
  • 1
  • 1
Adrian Lopez
  • 2,601
  • 5
  • 31
  • 48