Я расширил свою модель пользователя профилем и сделал так, чтобы объект профиля создавался, когда пользователь это делает. Сейчас я пытаюсь добавить свои поля при регистрации, описании и фото. Однако у меня возникли проблемы с этим. Я не уверен, что я получаю эту ошибку, поскольку я чувствую, что я разделил две модели в forms.py, поэтому я не уверен, откуда исходит ошибка.
Ошибка:
AttributeError at /register/
type object 'Profile' has no attribute 'USERNAME_FIELD'
Request Method: GET
Request URL: http://localhost:8000/register/
Django Version: 3.0.5
Exception Type: AttributeError
Exception Value:
type object 'Profile' has no attribute 'USERNAME_FIELD'
Exception Location: /Users/papichulo/Documents/DatingApp/11_env/lib/python3.7/site-packages/django/contrib/auth/forms.py in __init__, line 109
Python Executable: /Users/papichulo/Documents/DatingApp/11_env/bin/python
Python Version: 3.7.3
Python Path:
['/Users/papichulo/Documents/DatingApp',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/papichulo/Documents/DatingApp/11_env/lib/python3.7/site-packages']
views.py
def register(request):
form1 = UserForm(prefix="user")
form2 = ProfileForm(prefix="profile")
if request.method == "POST":
form1 = UserForm(request.POST, prefix="user")
form2 = ProfileForm(request.POST,request.FILES, prefix="profile")
if form1.is_valid() and form2.is_valid():
# Save form1 with no commit
user = form1.save(commit=False)
user.username = form1.cleaned_data['username']
user.email = form1.cleaned_data['email']
# user.email = form1.cleaned_data['email']
user.save()
user.profile.user = user
user.profile.description = form2.cleaned_data['description']
user.profile.photo = form2.cleaned_data['photo']
user.profile.save()
# Some return statement you choose
return redirect('dating_app:home')
# ***
return render(request, 'dating_app/register.html', {"form1": form1, "form2": form2})
models.py
from django.contrib.auth.models import User
from django.db import models
from dating_project import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)
description = models.TextField(default="")
matches = models.ManyToManyField(User,blank=True, related_name='+')
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
def __str__(self):
return self.user.username
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from dating_app.models import Profile
from dating_app.models import User
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ("username","email","password1","password2")
class ProfileForm(UserCreationForm):
class Meta:
model = Profile
fields = ('photo','description')
регистр. html
<form class="form-horizontal" role="form" action="{% url 'dating_app:register' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form1}}
{{form2}}
<br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>