N
N
Nikolino2018-05-12 23:29:51
Django
Nikolino, 2018-05-12 23:29:51

How to display a registration form with additional fields?

There is a model that extends the standard User model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    producer_name = models.CharField(max_length=100, verbose_name="Producer name", blank=True)

There is a form:
class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username', 'email', 'password']

How to add the producer_name field to this or another form, so that when registering, in addition to the standard fields, there is also an additional one?
Tried like this:
def register2(request):
    FormSet = inlineformset_factory(User, Profile, fields=('producer_name', 'username'))
    if request.method == "POST":
        formset = FormSet(request.POST)
        if formset.is_valid():
            pass
    else:
        formset = inlineformset_factory(User, Profile, fields=('producer_name', 'username'))
    return render(request, 'blog/register-second.html', {'formset': formset})

Swears when displaying the form:
Unknown field(s) (username) specified for Profile
If you remove 'username', then the form displays, but you can only change 'producer_name'.
Then this form is suitable for editing, not registration.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin Malyarov, 2018-05-13
@Konstantin18ko

Two forms:
userForm
formProfile
userForm.as_p
formProfile.as_p
And when accepting forms, save them one by one:
userForm.is_valid()
formProfile.is_valid()
PS I did it through an abstract model .

A
AlexandrBirukov, 2018-05-13
@AlexandrBirukov

My example,
models.py should help:

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

class User(AbstractUser):
    is_client = models.BooleanField("Статус клиента", default=False)


class Client(models.Model):
    """Профиль клиентов"""

    user = models.OneToOneField(User,
                                on_delete=models.CASCADE,
                                primary_key=True)
    entity = models.CharField("Организация", max_length=255, blank=True)
    address = models.TextField("Адрес организации", blank=True)
    mode = models.CharField("Режим работы", max_length=255, blank=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta():
        verbose_name = "Профиль клиента"
        verbose_name_plural = "Профили клиентов"
        ordering = ["-created"]

    def __str__(self):
        return self.name

forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from main.models import Client, User

class ClientCreationForm(UserCreationForm):
    entity = forms.CharField(required=False, label='Организация')
    address = forms.CharField(required=False, widget=forms.Textarea, label='Адрес')
    mode = forms.CharField(required=False, label='График работы')

    class Meta(UserCreationForm.Meta):
        model = User

    @transaction.atomic
    def save(self):
        user = super().save(commit=False)
        user.is_client = True
        user.save()
        Client.objects.create(user=user,
                              entity=self.cleaned_data.get('entity'),
                              address=self.cleaned_data.get('address'),
                              mode=self.cleaned_data.get('mode'))
        return user

+ in settings.py, you must definitely override AUTH_USER_MODEL with your own, and to display the new user model in the admin panel, you need to do something like this:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from .models import User


class MyUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = User


class MyUserAdmin(UserAdmin):
    form = MyUserChangeForm

    fieldsets = UserAdmin.fieldsets + (
        ('Статус', {'fields': ('is_client', )}),
    )

admin.site.register(User, MyUserAdmin)

M
ma3xak, 2018-05-13
@ma3xak

I can’t tell you specifically on the code, but I advise you to start digging about the output through related models

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question