I'm trying to add additional attributes to my "Person" model, namely, "age", "city", and "state." I've been struggling with this for a few days now and have looked up the documentation on how to "Extend the User class" in Django. But, I'm stuck, and when I try to create a new account I get the following error:
TypeError at /polls/signup/add
'age' is an invalid keyword argument for this function
Person model:
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
city = models.CharField(max_length=200, null=True)
state = models.CharField(max_length=200, null=True)
age = models.CharField(max_length=50, null=True)
Create account view (I'm pretty sure this is where the problem is occurring):
def create_account(request):
if request.method == 'POST':
new_user = User(username = request.POST["username"],
email=request.POST["email"],
first_name=request.POST["first_name"],
last_name=request.POST["last_name"],
age=request.POST["age"],
city=request.POST["city"],
state=request.POST["state"])
new_user.set_password(request.POST["password"])
new_user.save()
Person.objects.create(user=new_user,
first_name=str(request.POST.get("first_name")),
last_name=str(request.POST.get("last_name")),
email=str(request.POST.get("email")),
age=str(request.POST.get("age")),
city=str(request.POST.get("city")),
state=str(request.POST.get("state")))
new_user.is_active = True
new_user.save()
return redirect('../')
else:
return render(request, 'polls/create_account.html')
Any ideas on how I can solve this problem and allow users to add these bonus fields that aren't included with the generic User model?
You should use the Person model instead of User.
if request.method == 'POST':
new_user = User(username = request.POST["username"],
email=request.POST["email"],
first_name=request.POST["first_name"],
last_name=request.POST["last_name"],
)
new_user.set_password(request.POST["password"])
new_user.save()
Person.objects.create(user=new_user,
age=str(request.POST.get("age")),
city=str(request.POST.get("city")),
state=str(request.POST.get("state")))
new_user.is_active = True
new_user.save()
return redirect('../')
else:
return render(request, 'polls/create_account.html')
Related
#HELP in python (DJANGO 4)
I send this message here because I have not been able to find an answer elsewhere.
Currently I’m on a project where I have to create a booking form.
The goal is that when the user submit the Reservation form, I send the data in BDD, and I retrieve the user's id by a relation (ForeignKey).
And my difficulty is in this point precisely, when I send my form in BDD I recover the information, except the id of the user…
I did a Foreignkey relationship between my 2 tables and I see the relationship in BDD but I don’t receive the id of the User table, but null in the place….
Does anyone of you know how to help me please?
Thank you all.
--My model.py --
class Reservation(models.Model):
fullName = models.CharField('Nom Complet', max_length=250, null=True)
adress = models.CharField('Adresse', max_length=100, null=True)
zip_code = models.IntegerField('Code Postal', null=True)
city = models.CharField('Vile', max_length=100, null=True)
email = models.EmailField('Email', max_length=250, null=True)
phone = models.CharField('Telephone', max_length=20, null=False)
date = models.CharField('Date', max_length=20, null=True, blank=True)
hour = models.CharField('Heure', max_length=20, null=True, blank=True)
message = models.TextField('Message', null=True)
accepted = models.BooleanField('Valide', null=True)
created_at = models.DateTimeField('Date Creation', auto_now_add=True, null=True)
modified_at = models.DateTimeField('Date Mise Jour', auto_now=True, null=True)
user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.fullName
-- my views.py --
#login_required()
def user_new_reservation(request, pk=None):
user = User.objects.get(id=pk)
if request.method == 'POST':
form = ReservationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Votre réservation a bien été envoyé!')
return redirect('reservation:user_reservation', pk=request.user.id)
else:
form = ReservationForm()
context = {'form': form}
return render(request, 'reservation/new_reservation.html', context)
-- My Form.py --
class ReservationForm(forms.ModelForm):
class Meta:
model = Reservation
fields = [
'fullName',
'adress',
'zip_code',
'city',
'email',
'phone',
'date',
'hour',
'message',
]
Thank you all.
Inside your form.save use:
user = form.save(commit=False)
user.user = request.user
user.save()
user=your field name in your model
request user= in django when you use authentication you can access some of information based on request like user and other
Good luck
When I do this exactly as provided below, a shipping address object is created without the customer assigned in the shipping address foreignkey field, I can add it from the admin panel manually but I'm not able to make it work through code
**models.py**
class Customer(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=150)
class ShippingAddress(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
address_one = models.CharField(max_length=200)
address_two = models.CharField(max_length=200)
...
**views.py**
def checkout(request):
if request.method == 'POST':
form = ShippingForm(request.POST)
customer = request.user.customer
if form.is_valid():
# how to add the customer object to the foreignkey field of the shipping address
form.save()
return redirect('store:checkout_shipping')
else:
form = ShippingForm()
else:
form = ShippingForm()
context = {"form": form}
return render(request, 'store/checkout.html', context)
ShippingAddress.objects.get(customer=customer)
This returns a ShippingAddress, but
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True)
requires a CustomUser. These are incompatible, so you cannot assign them.
But you are already getting the user:
customer = request.user.customer
Just reduce this a little:
user = request.user
now you have a user object.
I am assuming that you have correctly set up the CustomUser class in the Django settings.
I have a registration form made of 2 forms, from which email field gets saved in both User and Student models. Now, I made an update account info view. Problem is, I want that email will get updated the in both models. But I get error:
'StudentEditForm' object has no attribute 'email'
Here is my code:
class StudentEditForm(forms.ModelForm):
email = forms.EmailField(required=False)
name = forms.CharField(max_length=30)
surname = forms.CharField(max_length=50)
photo = forms.ImageField(required=False)
phone = forms.CharField(max_length=15, required=False)
class Meta:
model = Student
fields = ('email', 'name', 'surname', 'phone', 'photo')
class User(AbstractUser):
pass
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
name = models.CharField(max_length=30, null=True, blank=True, default=None)
surname = models.CharField(max_length=50, null=True, blank=True, default=None)
email = models.EmailField(unique=True, null=True, blank=True, default=None)
student_ID = models.CharField(unique=True, max_length=14,
validators=[RegexValidator(regex='^.{14}$',
message='The ID needs to be 14 characters long.')],
null=True, blank=True, default=None)
photo = models.ImageField(upload_to='students_images', null=True, blank=True, default=None)
phone = models.CharField(max_length=15, null=True, blank=True, default=None)
def __str__(self):
return self.surname
User.student = property(lambda p: Student.objects.get_or_create(user=p)[0])
def profile_edit(request):
user = request.user
student = request.user.student
if request.method != 'POST':
form = StudentEditForm(instance=student)
else:
form = StudentEditForm(request.POST, instance=student)
user.email = form.email
form.save()
return render(request, 'index.html')
context = {
"form": form,
}
return render(request, "registration/profile_edit.html", context)
Again, I need that I will be able to update the email fields. And the email will get saved in User email but also I want it saved to Student email.
call form.is_valid() and then use form.cleaned_data['email'], see https://docs.djangoproject.com/en/1.11/topics/forms/
I had to add
form.is_valid()
and
user.email = form.cleaned_data['email']
but also to add user.save() which solved this issue.
Whenever I create a new account, the information I enter "first_name", "last_name", "username", "age", "city", "state", "email" gets split between the built-in User model and the Person model I created. I can see this happening on the admin site, when I click on a user I just created.
Person model:
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
username = models.CharField(max_length=200, null=True)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
city = models.CharField(max_length=200, null=True)
state = models.CharField(max_length=200, null=True)
age = models.CharField(max_length=50, null=True)
View for creating an account:
def create_account(request):
if request.method == 'POST':
new_user = User(username = request.POST["username"],
email=request.POST["email"],
first_name=request.POST["first_name"],
last_name=request.POST["last_name"])
new_user.set_password(request.POST["password"])
new_user.save()
Person.objects.create(user=new_user,
age=str(request.POST.get("age")),
city=str(request.POST.get("city")),
state=str(request.POST.get("state")))
new_user.is_active = True
new_user.save()
return redirect('../')
else:
return render(request, 'polls/create_account.html')
I know the problem is in this model and view, I just can't conceptualize how to put all of the information I submit into the Person model (since the User model only has "first_name", "last_name", "email" attributes).
Since your Person model has a one-to-one with the User, you don't need to store username, first_name, and last_name fields on it. Just leave them on the User model and access them through the relation, you are after all using a relational database.
I have custom user model by extending AbstractUser class. I want to make form to change user's fullname and website field.
My user:
class Hacker(AbstractUser):
name = models.CharField(max_length=255)
team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True, null=True)
description = models.CharField(max_length=255, blank=True, null=True)
website = models.URLField(max_length=200, blank=True, null=True)
def __str__(self):
if self.name:
return self.name
else:
return self.username
And forms.py:
class ProfileForm(forms.ModelForm):
"""
Edit profile form
"""
name = forms.CharField(label=_("Name"),
widget=forms.TextInput(attrs={'placeholder': _('Name')}))
description = forms.CharField(label=_("Description,Position"), required=False,
widget=forms.TextInput(attrs={'placeholder': _('Description, Position')}))
website = forms.URLField(label=_("Website"), required=False,
widget=forms.TextInput(attrs={'placeholder': _('Website URL')}))
class Meta:
model = get_user_model()
fields = ['name', 'description', 'website']
In page I use {{ field }} to add inputs and in POST part of views:
form = ProfileForm(request.POST)
if form.is_valid():
form.save(commit=True)
...
But form.save gives UNIQUE constraint failed: common_hacker.username error. What can be problem here?
Adding instance=request.user when creating form fixed problem:
form = ProfileForm(request.POST, instance=request.user)