简体   繁体   中英

Django- Registering user with foreign-key and multiple forms

Django newb here. I'm trying to create a registration page with multiple forms (company_form and user_form) such that a "company" is created and then the "user" is created and assigned to that company. (This is so that later on more users can be associated/registered with that one company.)

As of now, I get the error "column "company_id" of relation "custom_user_customuser" does not exist" when trying to submit information on the user registration page. I'm pretty sure that I'm making a fundamental amateur mistake, any help is appreciated. Thanks!

models.py

class Company(models.Model):
    company_name = models.CharField(max_length=200)

class CustomUser(AbstractBaseUser):
    your_name   = models.CharField(max_length=254, blank=True)
    company     = models.ForeignKey(Company)
    email       = models.EmailField(blank=True, unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'your_name',]

    objects = CustomUserManager()

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')    

views.py

def register_user(request):
    if request.method == 'POST':
        company_form = CompanyForm(request.POST, prefix = "company")
        user_form = CustomUserCreationForm(request.POST, prefix = "user")

        if company_form.is_valid() and user_form.is_valid():
            company = company_form.save
            user_form.cleaned_data["company"] = company
            user = user_form.save()
            return HttpResponseRedirect('/accounts/register_success')

    else:
        company_form = CompanyForm(prefix = "company")
        user_form = CustomUserCreationForm(prefix = "user")

    args = {}
    args.update(csrf(request))

    args['company_form'] = company_form
    args['user_form'] = user_form

    return render(request, 'register.html', args)

forms.py

class CompanyForm(forms.ModelForm):

class Meta:
    model = Company
    fields = ('company_name',)

class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and
password.
"""

def __init__(self, *args, **kargs):
    super(CustomUserCreationForm, self).__init__(*args, **kargs)
    del self.fields['username']

class Meta:
    model = CustomUser
    exclude = ('company',)
    fields = ("your_name", "email",)

register.html

{% extends "base.html" %}
{% load bootstrap_toolkit %}

{% block content %}

<div class = "container">

  <h2>Register</h2>

  {% for field in form %}
    {{field.error}}

  {% endfor %}

  <form action="/accounts/register/" method="post">
  {% csrf_token %}
  {{ company_form|as_bootstrap }}
  {{ user_form|as_bootstrap }}



  <input type="submit" value="Register" />

  </form>

{% endblock %}
</div>

In your view the parens are missing after company_form.save so you don't actually call the method but get back a reference to it instead that you pass to your UserForm.

For the "column "company_id" of relation "custom_user_customuser" does not exist" message: could it be you added the field in your models after the initial manage.py syncdb and did not update your database schema ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM