1

I'm trying to extend the User model in Django using inheritance. Here's my model:

class Paciente (User):
    Carteira = models.CharField(max_length=50, 
        verbose_name="Num Carteira Plano Saude",unique=True)
    Convenio = models.ForeignKey(Operadora,'Descricao', related_name="convenio", 
        verbose_name="Convenio",unique=True)
    DDD = models.CharField(max_length=2, verbose_name="DDD")
    Telefone = models.CharField(max_length=10, verbose_name="Telefone")

And here's my view:

def paciente_register(request):
    PacienteFormSet = modelformset_factory(Paciente)

    if request.method == 'POST':
        form = PacienteFormSet(request.POST or None, 
            request.FILES or None, queryset=Paciente.objects.none(), 
            initial=[{
                'is_staff': False,
                'is_active': True, 
                'is_superuser': False, 
                'date_joined': datetime.now(), 
                'last_login': datetime.now()
            }]
        ) #incluir
        if form.is_valid():
            instance = form.save(commit=False) #pre-salva o registro
            for logvalue in instance:  # repoe os valores 'hidden' de log
                logvalue.is_staff = False
                logvalue.is_active = True
                logvalue.is_superuser = False
                logvalue.date_joined = datetime.now()
                logvalue.last_login = datetime.now()
            for reform in instance:  # salva no banco
                reform.save()
        else:
            return HttpResponseRedirect('/erro/')
    else:
        form = PacienteFormSet(queryset=Paciente.objects.none(), 
            initial=[{
                'is_staff':False,
                'is_active': True,
                'is_superuser': False,
                'date_joined': datetime.now(),
                'last_login': datetime.now()
            }]
        ) #incluir
    return render_to_response('register.html', {'form': form,}, context_instance=RequestContext(request))

And, last but not least, my template:

<form enctype="multipart/form-data" method="POST" action="/paciente_register/" >{% csrf_token %}
{{ form.management_form }}
   {% for formy in form.forms %}
      {{ formy.username.label_tag}}:{{formy.username}}<br>
      {{ formy.password.label_tag}}:{{formy.password}}<br>
      {{ formy.Carteira.label_tag}}:{{formy.Carteira}}<br>
      {{ formy.Convenio.label_tag}}:{{formy.Convenio}}<br>
      {{ formy.DDD.label_tag}}:{{formy.DDD}}<br>
      {{ formy.Telefone.label_tag}}:{{formy.Telefone}}<br>
      {{formy.is_staff.as_hidden}}
      {{formy.is_active.as_hidden}}
      {{formy.is_superuser.as_hidden}} 
      {{formy.date_joined.as_hidden}}
      {{formy.last_login.as_hidden}}

    {% endfor %}   
    <input type="submit" name="submit" value="Salvar" />
</form>

The user is supposed to register himself, but he will only have access to edit some of the fields, because the others I am setting inside the view and in the template, I am hiding them.

But the thing is that my form is not validating. I did a lot of research, but just a few examples over the internet use inheritance to extend User model. And this ones, does not show how would be the view that makes the registration of the user inside the application.

Any help would be very appreciated! :)

supervacuo
  • 9,072
  • 2
  • 44
  • 61
  • Well, it's almost impossible to help you if you don't tell us what the problem is: what does "it's not validating" mean? Is there a specific validation error you believe shouldn't be there? – Yuji 'Tomita' Tomita Aug 21 '12 at 23:16
  • I'm sorry I wasn't very clear when I posted the question. A close friend gave me some help and solved my problem. I'm going to post the answer right away. But thank you, anyway! –  Aug 22 '12 at 14:26
  • [Indentation is important](https://en.wikipedia.org/wiki/Python_programming_language#Indentation) in Python! I've fixed it here, but please be careful when copying-and-pasting code samples (it's much easier to help if we don't need to guess at what the original code looked like). You might find [this userscript for (un)indenting code](http://stackapps.com/questions/3247/better-handling-of-indentation-and-the-tab-key-when-editing-posts) helpful. – supervacuo Aug 22 '12 at 15:37
  • That's odd, I know indentation is important in Python, otherwise my code wouldn't work. And I appreciate you edited it for a better indentation, but I revised my question like 5 times before posting, taking care specially of the indentation. –  Aug 22 '12 at 16:16

2 Answers2

0

The problem was on the view, after all. I was forcing the fields "date_joined" and "last_login" to receive datetime.now() because I was following the Django admin template. Sadly, this wasn't correct and everytime I tried to add a user, it was jumping to the error template, which means that the form wasn't filled properly. The solution was to make those fields receive date.today() and now it works fine.

I think this model inheritance is still not working very good (Python 2.7 and Django 1.3). When you use it in your models, be sure of what kind of field Django is creating inside your database, and this will save you a lot of trouble.

  • Regarding model inheritance, is this just a gut feeling, or can you share any facts with us? – schacki Aug 22 '12 at 16:07
  • Well, I'm using it for the first time in this project I'm doing right now. But I read a lot of tutorials and forums, and people complain that the User model inheritance inside Django is not behaving like an inheritance would normally behave in Python. Like in my example, you create a class that inherit User model and Django would add information inside the database to both models (Paciente and User). This looks like a sloppy thing made just to contemplate the developers request for Django to have it. –  Aug 23 '12 at 03:11
0

In general, I think the model inheritance is working fine and without significant issues. With regard to the User model, I do not have too much experience, but maybe your issues result from the fact that you are not doing it as proposed by Django ?

Just in case that your are intersted, some more interesting posts: h

Community
  • 1
  • 1
schacki
  • 9,401
  • 5
  • 29
  • 32
  • I was implementing properly, in fact, I was doing it in a way that was supported by Django, otherwise it wouldn't work at all. You can do it the way I did or adding a foreign key which points to the user inside User class. Either way, you should pay attention to which kind of field is being created inside your database by Django, otherwise the validation of the form would not work anyway. –  Nov 16 '12 at 17:07
  • Besides, tutorials always deals with simple examples which will always work. When you try to put some more complex logic on it, you would see that it won't work unless you keep observing what the framework is doing with your database. –  Nov 16 '12 at 17:10