I am not able to create a User Registration page using Django where I have used a Profile model with the OnetoOne field with the default User model.
views.py
def SignUpView(request):
if request.method == 'POST':
user_form = SignUpForm(data=request.POST)
profile_form = ProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
new_user = user_form.save(commit=False)
new_profile = profile_form.save(commit=False)
new_profile.user = new_user
userName = new_user.username
password = new_profile.password1
new_user.save(commit=True)
new_profile.save(commit=True)
user = authenticate(username = userName, password = password)
login(request, user)
return redirect('blog-home')
else:
user_form = SignUpForm()
profile_form = ProfileForm()
context = {
'user_form': user_form,
'profile_form': profile_form,
}
return render(request, 'user/signup.html', context=context)
forms.py:
class SignUpForm(UserCreationForm):
class meta:
model = User
fields = ['username', 'first_name', 'last_name', 'password1', 'password2']
class ProfileForm(forms.ModelForm):
class meta:
model = Profile
fields = ['user', 'email']
models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# img =
date_of_birth = models.DateField(blank=True, null=True)
bio = models.CharField(blank=True, max_length=500)
location = models.CharField(blank=True, max_length=50)
email = models.EmailField(unique=True, max_length=200)
def __str__(self):
return f'Profile for {self.user.username}'
It is displaying an error message on the signup page as :
ValueError at /signup/
ModelForm has no model class specified.
It could be because there's a typo in your meta class declaration.
Change it to - class Meta. Note the case.
Did you try this to get the User model?
from django.contrib.auth import get_user_model
User = get_user_model()
Change it to - class Meta
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'password1', 'password2']
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['user', 'email']
If this isn't a form based on a model, don't inherit from forms.ModelForm, just use an ordinary forms.Form.
Related
first post here. Im trying to query the user so i from the form so i can save the user in my database.
This is my code
form = lageBruker(request.POST)
bruker = User.objects.create(format(request.POST['username']))
print()
if request.method == 'POST':
if form.is_valid():
fornavn = request.POST['first_name']
etternavn = request.POST['last_name']
email = request.POST['email']
kunde = Kunde.objects.create(
#bruker = bruker,
fornavn=fornavn,
etternavn=etternavn,
email=email
)
kunde.save()
context = {'form': form}
return render(request, 'ebutikk/registrer.html', context)
Kunde Model:
class Kunde(models.Model):
bruker = models.OneToOneField(
User, null=True, blank=True, on_delete=models.CASCADE)
fornavn = models.CharField(max_length=200, null=True, blank=True)
etternavn = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.etternavn
What im trying to do is, when the registration form is submittet, i want to save the registerd user as a kunde/customer. I dont have a User model, i use the default made by django with the import:
from django.contrib.auth.models import User
I make the form by importing the user creation form given by django and customizing it im my forms.py file.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class lageBruker(UserCreationForm):
class Meta:
model = User
fields = ['username',
'email',
'first_name',
'last_name',
'password1',
'password2']
Normally, you'd simply create the Kunde model like this:
class Kunde(models.Model):
bruker = models.OneToOneField(
User, null=True, blank=True, on_delete=models.CASCADE)
# more fields here, so the model makes sense
#property
def fornavn(self): return self.user.first_name
#property
def etternavn(self): return self.user.last_name
#property
def email(self): return self.user.email
Then all you need to do is:
def customer_signup_view(self, request):
if request.method == "POST":
form = lageBruker(request.POST)
# Saving the model form returns the user created
user = form.save()
# Now use that user to create a new customer
Kunde.objects.create(user=user)
return redirect("success/")
return render(request, 'ebutikk/registrer.html', {"form": lageBruker())
I want to create a user into auth_user. And use its id(primary key) to
fill in an entry into User_Profile to take it as a Foreign key.
Models.py:
class User_Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
contact_number = models.IntegerField()
birth_date = models.DateField(null=False)
address = models.CharField(max_length=200)
role = models.ForeignKey(Role, on_delete=models.CASCADE)
Forms.py:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
class UserProfileForm(forms.ModelForm):
class Meta:
model = User_Profile
fields = [ 'contact_number', 'birth_date', 'address', 'role']
Views.py:
def registration_view(request):
form = UserForm(request.POST)
form2 = UserProfileForm(request.POST)
else:
context = {
'form': form,
'form2': form2
}
return render(request, 'Schoool/registration_form.html', context)
After adding a new field to my model, it doesn't show up in the form.
I have been working on this django app and have extended the already existing User model with my own UserProfile model with extra fields. Recently, I have decided to add an extra field to the UserProfile model (profile_type). I added it to the model and included it in its corresponding form, and ran makemigrations and migrations. I then tried inserting an initial value to this field in my views and found out that it is not showing up in the form through print(), however, all the other fields are.
My UserProfile model
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, related_name='userprofile')
gender = models.CharField(max_length = 10)
city = models.CharField(max_length = 45)
country = models.CharField(max_length = 45)
birthdate = models.DateField(null=True)
phone_number = models.CharField(max_length = 15)
profile_type = models.CharField(max_length = 6)
#receiver(post_save, sender=User)
def save_profile(sender, instance, created, **kwargs):
if created:
profile = UserProfile(user=instance)
profile.save()
My UserProfile forms (UserProfileForm contains the fields necessary for sign up, AdditionalUserProfileForm is the rest)
class UserProfileForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2')
def save(self, commit=True):
user = super(UserProfileForm, self).save(commit=True)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
return user
class AdditionalUserProfileForm(forms.ModelForm):
profile_type = forms.CharField(max_length=6)
class Meta:
model = UserProfile
fields = ('gender', 'city', 'country', 'birthdate', 'phone_number', 'profile_type')
My Sign Up view (I want to add the value to profile_type manually upon instantiation
#transaction.atomic
def signup_view(request):
if request.method == 'POST':
user_profile_form = UserProfileForm(request.POST)
initial = {
'profile_type': 'user'
}
additional_user_profile_form = AdditionalUserProfileForm(request.POST, initial=initial)
valid = user_profile_form.is_valid() * additional_user_profile_form.is_valid()
if valid:
user = user_profile_form.save()
for field in ['gender', 'city', 'country', 'birthdate', 'phone_number']:
setattr(user.userprofile, field,
additional_user_profile_form.cleaned_data.get(field))
user.userprofile.save()
return redirect('login')
else:
user_profile_form = UserProfileForm()
additional_user_profile_form = AdditionalUserProfileForm()
context = {
'user_profile_form': user_profile_form,
'additional_user_profile_form': additional_user_profile_form,
}
return render(request, 'registration/signup.html', context)
Printing out the form fields in the terminal doesn't show that profile_type is one of them. I saw on some thread that it's a bug but the fix did not work for me. It was something about changing the get_fieldsets function in contrib/admin/options.py. Hope this gives you a hint. Thank you!
I am starting to learn python and django framework and messing around with UserChangeForm imported from django.contrib.auth.forms and now attempting to update the User info and User profile at the same time this is by combining the two fields.
Here is my forms.py
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email', 'password')
And here is my view.py
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('/accounts/profile')
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'edit_profile.html', args)
Here is my model.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT)
description = models.CharField(max_length=100, default='')
city = models.CharField(max_length=100, default='')
I was wondering if i can add the fields on my EditProfileForm class if that is possible? any suggestion would be great!
fields = ('first_name', 'last_name', 'email', 'password','city','description')
I try to create registration form. It consists of several forms UserForm, UserProfileForm and CompanyForm which are generated from models.
models.py
from django.db import models
from django.contrib.auth.models import User
class Company(models.Model):
login = models.CharField(max_length=20, null=True)
password = models.CharField(max_length=10, null=True)
is_active = models.BooleanField()
title = models.CharField(max_length=100)
org = models.CharField(max_length=50)
inn = models.BigIntegerField()
kpp = models.BigIntegerField()
class UserProfile(models.Model):
company = models.ForeignKey(Company)
user = models.OneToOneField(User)
department = models.CharField(max_length=100)
position = models.CharField(max_length=100)
forms.py
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.forms import HiddenInput
from django.forms.models import modelformset_factory
from models import Company, UserProfile
class CompanyRegistrationForm(ModelForm):
class Meta:
model = Company
exclude = ('login', 'password', 'is_active')
class UserForm(ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email')
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ('user')
widgets = {'company': HiddenInput()}
I try do this by formsets and inheritance but unfortunately.
I want one form with one custom save method, is it possible?
ps And my views.py is
class RegistrationCreateView(CreateView):
template_name = 'accounts/registration.html'
model = Company
#form_class = CompanyRegistrationForm
success_url = 'thanks/'
def _create_credentials(self):
login_str = random.randint(1000000, 9999999)
password = ''.join([symbol for i in range(10)
for symbol in random.choice(string.letters)])
return login_str, password
def form_valid(self, form):
context = self.get_context_data()
form = context['registration_form']
if form.is_valid():
#TODO(mid): refactor this
self.object = form.save()
company_id = self.object.id
login_str, password = self._create_credentials()
self.object.password = password
self.object.login = login_str
self.object.is_active = True
form.instance = self.object
form.save()
return self.success(login_str, password, company_id)
return self.form_invalid(form)
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self, **kwargs):
context = super(RegistrationCreateView, self).get_context_data(**kwargs)
context['registration_form'] = CompanyRegistrationForm()
context['user_form'] = UserForm()
context['user_profile_form'] = UserProfileForm()
if self.request.POST:
context['registration_form'] = CompanyRegistrationForm(self.request.POST)
context['user_form'] = UserForm(self.request.POST)
context['user_profile_form'] = UserProfileForm(self.request.POST)
return context
def success(self, login_str, password, company_id):
login(self.request, self.object)
self.request.session['company_id'] = company_id
return render_to_response('accounts/thanks.html',
{'login': login_str, 'password': password},
RequestContext(self.request))