Search code examples
djangopython-3.xdjango-formsdjango-authenticationdjango-users

create a user in Django 2.1 that is associated with an existing model


In my models.py file I have the following code ->

from django.db import models

class Blogger(models.Model):
    username = models.CharField(max_length=20)
    email = models.EmailField()
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    password = models.CharField(max_length=30, default='')

I want to associate the Blogger model with a User and create the User upon form submission. Here is the forms.py file ->

from django import forms
from blog.models import Blogger
class BloggerForm(models.ModelForm):
    class Meta:
        model = Blogger
        fields = ['username', 'email', 'first_name', 'last_name', 'password']

And here is the views.py ->

class BlogView(FormView):
    template_name = 'blogform.html'
    form_class = BloggerForm
    success_url = 'blog/'

How do I create a new user on the submission of this form ?


Solution

  • All fields in blogger already exists in User model, actually you don't need this Blogger model at all, just use the User model directly.