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')
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 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.
I wrote the following code which creates a new user and tries to create a profile for that user:
class RegisterForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = CustomUser
fields = ('username', 'email', 'password1', 'password2')
#login_required(login_url="/login")
def index(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
profile = Profile().save()
user = form
user.profile = profile
user.save()
return redirect('users')
else:
print(form.errors)
else:
form = RegisterForm()
user_model = get_user_model()
users = user_model.objects.all()
paginator = Paginator(users, 15)
page = request.GET.get('page')
users = paginator.get_page(page)
return render(request, 'users/index.html', {'users': users, 'form': form})
class Profile(models.Model):
has_premium_until = models.DateTimeField(null=True, blank=True)
has_premium = models.BooleanField(default=False)
has_telegram_premium_until = models.DateTimeField(null=True, blank=True)
has_telegram_premium = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
class CustomUser(AbstractUser):
email = models.EmailField(max_length=255, unique=True)
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True)
When I'm submitting the form the user as well as the profile is created but the profile is not stored in the user (the profile_id stays null).
Anyone who can help me out?
Your user is actually just a reference to the ProfileForm you constructed. You can obtain the user that has logged in with request.user. So you can update the user with:
#login_required(login_url='/login')
def index(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
profile = Profile().save()
user = request.user
user.profile = profile
user.save()
return redirect('users')
else:
print(form.errors)
else:
form = RegisterForm()
# …
I am trying to store user details with the PhoneBook and Contacts he creates so that I will be able to show the PhoneBook and Contacts that have been created by them.
I don't want the user to explicitly add the details himself. It should be handled by the backend.
I am successfully able to store the user details with the PhoneBook he created, but when I try to do the same thing with contacts, I am getting an attribute error.
models.py
class PhoneBook(models.Model):
name = models.CharField(max_length=10, blank=False)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class Contact(models.Model):
first_name = models.CharField(max_length=50, blank=False)
last_name = models.CharField(max_length=50, blank=False)
phone_number = models.CharField(max_length=13, blank=False, unique=True)
phone_book = models.ManyToManyField(PhoneBook, related_name='phone_book')
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.phone_number
views.py
#login_required
def create_phone_book(request):
form = CreatePhoneBookForm(request.POST or None)
form.instance.user = request.user
if form.is_valid():
form.save()
form = CreatePhoneBookForm()
context = {'form': form}
return render(request, 'CallCenter/create_phone_book.html', context)
#login_required
def add_to_phone_book(request):
form = AddToPhoneBookForm(request.POST or None)
form.instance.user = request.user
if form.is_valid():
form.save()
form = AddToPhoneBookForm()
context = {'form': form}
return render(request, 'CallCenter/add_to_phone_book.html', context)
forms.py
class AddToPhoneBookForm(forms.Form):
class Meta:
model = Contact
fields = ['first_name', 'last_name', 'phone_number', 'phone_book']
class CreatePhoneBookForm(forms.Form):
class Meta:
model = PhoneBook
fields = ['name']
The error I am getting is
AttributeError at /call-center/add/
'AddToPhoneBookForm' object has no attribute 'instance'
You should make use of a ModelForm, not a Form. A Form itself has no instance, so you can define:
class AddToPhoneBookForm(forms.ModelForm):
class Meta:
model = Contact
fields = ['first_name', 'last_name', 'phone_number', 'phone_book']
class CreatePhoneBookForm(forms.ModelForm):
class Meta:
model = PhoneBook
fields = ['name']
Usually when you make a successful post request, you should redirect, to implement the Post/Redirect/Get pattern [wiki].
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)