Not getting model form values in template - python

Django user profile model form data is not getting displayed on the template, not even giving me an error!
I am learning to create Django registration form with user profile models I have created the registration form and profile form successfully but I am not getting any values from models.py file.
Models.py
class ExtenduserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(null=True, blank=True)
age = models.IntegerField()
def __str__(self):
return self.user.username
#receiver(post_save,sender=User)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile =
ExtenduserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
forms.py
class userprofile(forms.ModelForm):
birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD')
class Meta:
model = ExtenduserProfile
fields = ('age','birth_date')
views.py
#login_required()
def UserProfile(request,pk=None):
profile = ExtenduserProfile.objects.all()
return render(request,'dashboard/profile.html',{'profile':profile})
#login_required()
def HomeScreen(request):
if request.user.is_authenticated:
username = request.user.username
else :
username = 'not logged in'
context = {'username':username,'user':user}
return render(request,'dashboard/Home.html',context)
def singup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
user_profile = userprofile(request.POST)
if form.is_valid() and user_profile.is_valid():
user = form.save()
profile = user_profile.save(commit=False)
profile.user = user
profile.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username = username, password = password)
login(request,user)
return redirect(login_view)
else:
form = SignupForm()
user_profile = userprofile()
context = {'form':form, 'user_profile':user_profile }
return render(request,'account/signup.html',context)
HTML file
{% extends 'dashboard/base.html' %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Profile</title>
</head>
{% block content%}
<body>
<h3>Welcome to profile page</h3><br>
{% if user.is_authenticated %}
<h4>Name = {{user.first_name}} {{user.last_name}}</h4>
<h4>Email = {{user.email}}</h4>
<h4>Age = {{user.ExtenduserProfile.age}} </h4>
<h4>DOB = {{user.ExtenduserProfile.birth_date}} </h4>
{% endif %}
</body>
{% endblock%}
</html>
my expected output should be
name: xyz
email: abc#abc.com
age: 24
DOB: 1994-04-21

What is a Custom User Model Extending AbstractUser?
It is a new User model that inherit from AbstractUser. It requires a special care and to update some references through the settings.py. Ideally it should be done in the begining of the project, since it will dramatically impact the database schema. Extra care while implementing it.
When should I use a Custom User Model Extending AbstractUser?
You should use it when you are perfectly happy with how Django handles the authentication process and you wouldn’t change anything on it. Yet, you want to add some extra information directly in the User model, without having to create an extra class.
I suggest to you to use Abstract User
Which is easier and best practice for your case
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
Also add this to your setting :
AUTH_USER_MODEL = 'appname.User'
Check this tutorial for more information

Well, when you are using reverse relation in OneToOne, the class name should be in all lowercase(documentation). For example:
<h4>Age = {{user.extenduserprofile.age}} </h4>
<h4>DOB = {{user.extenduserprofile.birth_date}} </h4>
Also, why are you sending profile = ExtenduserProfile.objects.all() to template via context from your profile view? Because as I can see, you are not using it. So I think you can remove that part of code as well.
Also, you can remove the {% if user.is_authenticated %} and {%endif%} from template. As, this template can't be accessible unless you are logged in. You have restricted that via login_required decorator.

Related

How to automatically link the users table to another table once a user gets registered in django

I am trying to create an e-commerce website, in which I have used the functionality of the Django authentication to allow users to register and login. However, in the registration form, I take the information from 2 tables at once, like this...
In my models.py...
class Profile (models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mobileNumber = models.CharField(max_length=13)
address = models.ForeignKey(Shipping, on_delete=models.DO_NOTHING, default=False)
guest = models.BooleanField(default=False)
class Shipping(models.Model):
addressLine1 = models.CharField(max_length=100)
addressLine2 = models.CharField(max_length=100)
city = models.CharField(max_length=40)
postalCode = models.CharField(max_length=5)
landmark = models.CharField(blank=True, max_length=80)
And my forms.py...
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
from store.models import Shipping
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
mobile_number = forms.CharField()
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'mobile_number', 'email', 'password1', 'password2']
class AddressRegisterForm(forms.ModelForm):
class Meta:
model = Shipping
fields = ['addressLine1', 'addressLine2', 'city', 'postalCode', 'landmark']
My signals.py...
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
My views.py...
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
from .forms import AddressRegisterForm
from .models import Profile
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from . import signals
import django.dispatch
# Create your views here.
def register(request):
if not request.user.username :
if request.method == 'POST':
form = UserRegisterForm(request.POST)
form1 = AddressRegisterForm(request.POST)
if form.is_valid() and form1.is_valid():
email = form.cleaned_data.get('email')
if not User.objects.filter(email=email).exists():
username = form.cleaned_data.get('username')
messages.success(request, f"The Account created for {username}! You are now able to login.")
form1.save()
form.save()
return redirect('login')
else:
messages.warning(request, f"The email is either invalid or already used to create an account")
else:
form1 = AddressRegisterForm()
form = UserRegisterForm()
return render (request, 'register.html', {"form":form, "form1":form1})
else:
username = request.user.username
messages.warning(request, f"You are already logged in as {username}!")
return redirect ('home')
And finally my template...
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block title %}Register{% endblock %}
{% block content %}
<div class="content-section mb-5">
<form method="POST">{% csrf_token %}
<div style="display: flex; width: 100%; justify-content: space-around;">
<fieldset class="form-group mt-4" style="width: 48%;">
<legend class="border-bottom mb-4">Register</legend>
{{ form | crispy }}
</fieldset>
<fieldset class="form-group mt-3" style="width: 48%;">
<legend class="border-bottom mb-4">Shipping info</legend>
{{ form1 | crispy }}
</fieldset>
</div>
<div class="form-group mt-3">
<button class="btn btn-outline-info" type="submit">Sign up</button>
<small class="text-muted ml-3">Forgot Password?</small>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">Already have an account? Sign in</small>
</div>
</div>
{% endblock %}
My information gets stored in the relevant tables, however, there seems to be no effect on the Profile table and remains to be empty...
Is there any way I can fire off django to link the user and the address in the Profile table once the user is registered.
Any help would be appreciated,
Thanks a lot!!
You need to load the signals in the ready() function of your app configuration:
Where should this code live?
Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code.
In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, import the signals submodule inside ready().
yourapp/apps.py:
class YourAppConfig(AppConfig):
name = "yourapp"
def ready(self):
from . import signals
That should be enough to get the signals registered at the correct time.
Regarding two issues:
Existing user models in your database won't get updated, only new ones. Either drop your db and create new users or add a data migration if your database is live or you want to keep the current.
Models connected by signals must be created without having any data for them. So you either must have nullable fields or fields with defaults.
Two forms
So you've posted 2 forms as one form in the HTML, this works because your forms don't share field names (except primary key, which isn't posted). For future reference, you can use a form prefix to deal with duplicate field names and even use the same form for different purposes (shipping and billing address for example).
On signals
Signals are used when an event happens (user is saved, user logs in), that is part of 3rd party code (in this case Django). But when you're the one creating the event, they are not needed as you can just do whatever you want right at where you create the event.
Logged in or not
The correct test is:
if not request.user.is_authenticated:
On to the solution
When saving related models with one or more forms, you should first create the models that can be saved without the other model of the relationship existing. These are:
The model a foreign key points to (Shipping).
The model of a OneToOneField, where the OneToOneField is not defined (User)
Due to the signal, our profile model will be created with empty values, but the form does not know that the mobile_number belongs on the Profile model, because it is a ModelForm bound to the User Model. It treats mobile_number as a field that you will handle yourself. So let's do that:
user = form.save() # save returns the model instance created
profile = user.profile
profile.mobile_number = form.cleaned_data['mobile_number']
As said, we can create the address without problems and then we can link it to the profile:
address = form1.save() # save returns the model instance created
profile.address = address
And now we can save the profile:
profile.save()
So putting it all together:
def register(request):
if not request.user.is_authenticated: # The correct way to test for logged in user
if request.method == "POST":
form = UserRegisterForm(request.POST)
form1 = AddressRegisterForm(request.POST)
if form.is_valid() and form1.is_valid():
email = form.cleaned_data.get("email")
if not User.objects.filter(email=email).exists():
username = form.cleaned_data.get("username")
messages.success(
request,
f"The Account created for {username}! You are now able to login.",
)
user = form.save()
profile = user.profile
profile.mobile_number = form.cleaned_data['mobile_number']
address = form1.save()
profile.address = address
profile.save()
return redirect("login")
else:
messages.warning(
request,
f"The email is either invalid or already used to create an account",
)
else:
form1 = AddressRegisterForm()
form = UserRegisterForm()
return render(request, "register.html", {"form": form, "form1": form1})
else:
username = request.user.username
messages.warning(request, f"You are already logged in as {username}!")
return redirect("home")
You can add all the fields related to the shipping address in the "profile" model.
When you want to access that data, you can simply use querysets.
In the models
class Profile (models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mobileNumber = models.CharField(max_length=13)
address = models.ForeignKey(Shipping, on_delete=models.DO_NOTHING, default=False)
guest = models.BooleanField(default=False)
addressLine1 = models.CharField(max_length=100)
addressLine2 = models.CharField(max_length=100)
city = models.CharField(max_length=40)
postalCode = models.CharField(max_length=5)
landmark = models.CharField(blank=True, max_length=80)
and when you want to access the data, you can simply use querysets

one user viewing another users profile in django

I would like to implement a functionality where another user A clicks the picture of a different user B and is automatically redirected to the profile of user B. how do I do this? please look at my HTML where I stated something about a link
view.py
class profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
bio = models.TextField(blank=True)
def __str__(self):
return f'{self.user.username} profile'
html:
{% for post in posts %}
<div class="icl-NavigationList-item">
<div class="icl-NavigationList-link icl-NavigationList--primary">
<div class="icl-NavigationList-text">
<h2 class="icl-NavigationList-title">
<div class="upperText">
<h2 class="card-title"style="background-color:{{post.post_colours}};">{{post.job_title}}</h2>
<a class="a-tags" href="*{{ i need to link the post author's profile here}}*" data-tippy-content="#dribble_handle">
<img src="{{post.author.profile.profile_pic.url}}" style="border-radius: 100%;float:right;"
alt="author"width="30" height="30"></a></div>
<div class="lowerText"> <p class="card-text">{{post.currency}} {{post.salary}}</p>
<p class="card-text"> Posted on {{post.date_posted}} by {{post.author}} </p>
<br>
{% if user.is_authenticated %}
my model
class profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
bio = models.TextField(blank=True)
category = models.CharField(max_length= 1000, choices =
Select_category,default='other')
def get(self, request, *args, **kwargs):
username = self.kwargs['username']
user_profile = profile.objects.get(user__username=username)
gigs = Gig.objects.filter(user__username=username, status=True)
print(user_profile.values())
return render(request, 'blog/profile.html', {'user_profile': user_profile, 'gigs': gigs,'name': username})
Alright, here’s an edited answer. I took a look at your code, and you don’t have the post model on here, so this is just me trying to put some pieces together to try. Ultimately, our goal should be to have the href look like this:
href="{{ post.author.get_absolute_url }}"
Note here that it is NOT {{ post.author.profile.get_absolute_url }}. It probably seems counter-intuitive to leave out profile in the url, but remember that the username argument passed is part of the User model, not the profile model.
(Note: the url will definitely depend on what the model for your post looks like. If the author is a ForeignKey to the user model, use what I’m typing here. If it is a ForeignKey relating to the profile model, you would replace author with author.user)
If that doesn’t work, make sure your urls.py is set up correctly.
urls.py
...
path(‘URL_YOU_WANT/<username>/, views.VIEW_NAME, name=“NAME”),
...
(Note: keep “<username>” exactly like that. It’s how Django knows to expect the username argument passed by your href.)
If things still aren’t working, I would rewrite your views.py view to be clearer. There is a bit of redundancy and confusion with your views.py and models.py. Here’s how I would go about it:
models.py
class profile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
bio = models.TextField(blank = True)
def __str__(self):
return f’{self.user.username} profile’
views.py
def user_profile(request, username):
user = User.objects.get(username = username)
user_profile = profile.objects.get(user = user)
gigs = Gig.objects.filter(user = user, status = True)
return render(request, ‘blog/profile.html’, {‘user_profile’: user_profile, ‘gigs’: gigs, ‘name’: username})
Let me know if this helps!

Display record from database to template

Hi i am building a project where there is a form which login user submits , so the user can submit the form multiple times i have used ForeignKey .
Now i am struggling to display all the records associated with the user .
for example : user 'abc' has fill form and he comes again and fill form so i want to show both the form details of user abc in my template , I am missing something as new to django
views.py
def PostTest(request):
if request.method == 'POST':
test = UserTest()
test.user = request.user
test.name = request.POST['name']
test.email = request.POST['email']
test.location = request.POST['location']
test.time = request.POST['time']
test.save()
return render(request, 'posts/test.html')
test.html
{{ user.usertest.location }}
models.py
class UserTest(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
email = models.EmailField()
location = models.CharField(max_length=255)
time = models.IntegerField()
test_submitted = models.BooleanField()
so i want to get the location filed in my template as user fill multiple times the form so i want all the location of that user in my django template , something looping may work but as newbie don't know how to use it.
If there is a ForeignKey relation between UserTest and User, like this:
class UserTest(models.Model)
user = models.ForeignKey(User)
Then you can simply get the location data like this:
{% for ut in user.usertest_set.all %}
{{ ut.location }}
{% endfor %}
I am using reverse relation between User and UserTest model to make this query.
You need to iterate over all the forms saved by the user, so either send them from the views.py file in context in render or get them in the template itself
def PostTest(request):
if request.method == 'POST':
test = UserTest()
test.user = request.user
test.name = request.POST['name']
test.email = request.POST['email']
test.location = request.POST['location']
test.time = request.POST['time']
test.save()
submitted_form = UserTest.objects.filter(user=request.user)
return render(request, context={'forms': submitted_form}, 'posts/test.html')
in html file
{% for form in forms %}
{{ form.location }}
{% endfor %}
Go through the doc for Django for better understanding

Unable to save data from both forms

I am trying to get Seller information, username, password, name, mobile number and address. I have used User to get the username and password, connected the username to my model through OneToOneField relationship and later save the information.
I have made a model named SellerDetails which gets the user field from OneToOneField with User and rest all details are provided as follows:
#models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class SellerDetails(models.Model):
"""docstring for SellerDetails."""
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=128, null = True)
address = models.CharField(max_length=256)
mobile_number = models.IntegerField(primary_key=True)
def __str__(self):
return self.user.username
then I have made two forms in my forms.py
#forms.py
from django import forms
from django.contrib.auth.models import User
from avkara.models import SellerDetails, VendorDetails
class UserForm(forms.ModelForm):
password = forms.CharField(widget = forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'password')
class SellerDetailsForm(forms.ModelForm):
"""docstring for SellerDetailsForm."""
class Meta:
model = SellerDetails
fields = ('name','address','mobile_number')
#Then I tried established a relation while saving the form
#views.py
def Signup_seller(request):
seller_registered = False
if request.method == "POST":
user_form = UserForm(data = request.POST)
user_details = SellerDetailsForm(data = request.POST)
if user_form.is_valid() and user_details.is_valid():
seller = user_form.save()
seller.set_password(seller.password)
seller.save()
#saving user_details now
other_details = user_details.save(commit= False)
other_details.user = seller
other_details.save()
seller_registered = True
else:
user_form = UserForm()
user_details = SellerDetailsForm()
return render(request, 'avkara/signup_seller.html',{'seller_registered': seller_registered , 'user_form' : user_form, 'user_details' : user_details})
#Then I tried serving both forms through Html form. Here is my html
#signup_seller.html
<div class="container jumbotron">
<h2>Sign up</h2><br><br><br>
<form class="form-horizontal" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
{{ user_details.as_p }}
<input type="submit" value="Submit">
</form>
</div>
#The desired out should be Thank you for registering but I get following error
IntegrityError at /avkara/signup_seller
NOT NULL constraint failed: avkara_sellerdetails.password
#This is error it is showing
F:\Webpage\python\techforstock\avkara\views.py in Signup_seller
other_details.save() <!--error part --!>
I have worked one it for hours, but no luck, Can Anyone help me out with this.
I want the username and password to be registered in users section and other information saved in Sellerdetails when I open Admin interface, but it should be with respect to the specific username.

How to extend django UserCreationForm model to include phone number field

I cant seem to find any posts here regarding extending the Django UserCreationForm model to include a phone number field for users to enter their number and then validate the phone number using phonenumbers.parse in the backend to check if the number is in the respective format and whether it exists or not. I need to know what code I should include in my forms.py under my "users" app.
I've tried including normal html text field for the phonenumbers and it does not belong to the default UserCreationForm model in Django and neither can it be stored in the database. (I need it to be stored in the database for the phone numbers). I am only using forms.py, views.py and register.html to be rendered in views as shown below, currently I am not using models.py.
/* forms.py */
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# from validate_email import validate_email
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
phone_number = forms.IntegerField(required=True)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
/* views.py */
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('blog-home')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
/* register.html */
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign
Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
ALready Have An Account? <a class="ml-2" href="#">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
I need to include a phone number field as part of the UserCreationForm in django and validate the number to check if it exists or not and then save the number in the database.
I usually extend Django User Model using OneToOneLink
models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=11, blank=True) # change the field to watever works for you
# This will auto create a profile of user with blank phone number that can be updated later.
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('phone')
views.py
def create_user(request):
if request.method == 'POST':
user_form = UserForm(request.POST, instance=request.user)
profile_form = ProfileForm(request.POST, instance=request.user.user_profle)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, _('New user created successfully'))
return redirect('settings:profile')
else:
messages.error(request, _('Please correct the error below.'))
else:
user_form = UserForm(instance=request.user)
profile_form = ProfileForm(instance=request.user.user_profile)
return render(request, 'template_name.html', {
'user_form': user_form,
'profile_form': profile_form
})
template:
<form method="post">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<button type="submit">Save changes</button>
</form>
UPDATE to initial answer. I decided while the solution below worked it was preferable to inherit the AbstractUser model and add my own requirements in my own bespoke user model. Once in place it's far more straight forward dealing with views and templates. I hesitated at first as I didn't feel confident enough to mess around with the default User model, but it is actually very simple. It also helped me understand abstracting models in general via.
class Meta:
abstract = True
The posts here were very helpful.
How to Extend Django User model using AbstractUser
Extending User Model
Previous post:
I've been struggling with this issue also. I've found a solution that works ok, but may have some pitfalls, which it would be good to get views on. My solution is a combination of the other answer to this question, with two modifications. Firstly the code above should be used to update a user rather than create one, because at registration no user profile exists so can't be called. Secondly, I removed the create_user_profile method on the model and used the answer posted here How to Extend UserCreateForm
to save the extended user information at registration. The reason for removing the create_user_profile was to prevent interference with the save() method on the form. The extended model i'm using is called Account.
I also found this article useful extending the django user model, and I'm still considering whether one of the other options might be more appropriate.
My code looks like this:
Views:
def register_view(request):
form = AccountRegisterForm(request.POST or None)
if form.is_valid():
form.save()
return redirect("accounts:login")
context = {"form": form}
return render(request, "accounts/register.html", context)
def user_update_view(request):
user_obj = User.objects.get(username=request.user)
account_obj = Account.objects.get(user=request.user)
user_form = UserForm(request.POST or None, instance=user_obj)
account_form = AccountForm(request.POST or None, instance=account_obj)
if user_form.is_valid() and account_form.is_valid():
user_form.save()
account_form.save()
return redirect(reverse("accounts:detail"))
context = {
"account_form": account_form,
"user_form": user_form,
}
return render(request, "accounts/account_update.html", context)
Forms
class AccountRegisterForm(UserCreationForm):
group = forms.ModelChoiceField(queryset=Group.objects)
dir = forms.ModelChoiceField(queryset=Directorate.objects)
class Meta:
model = User
fields = (
"username",
"first_name",
"last_name",
"group",
"dir",
)
def save(self, commit=True):
if not commit:
raise NotImplementedError(
"Can't create User and UserProfile without database save"
)
user = super(AccountRegisterForm, self).save(commit=True)
user_account = Account(
user=user,
group=self.cleaned_data["group"],
dir=self.cleaned_data["dir"],
)
user_account.save()
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ("username", "first_name", "last_name")
class AccountForm(forms.ModelForm):
class Meta:
model = Account
fields = (
"group",
"dir",
)

Categories

Resources