Django: Как сохранить поле OneToOneField
У меня есть код, который должен назначать "био" каждому пользователю. До сих пор каждый раз, когда создается пользователь, создается и UserProfile, в котором есть "Bio", "Birthday"...
models.py
from django.db import models
from django.contrib.auth.models import User
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)
bio = models.TextField(max_length=500, blank=True)
phone_number = models.CharField(max_length=12, blank=True)
birth_date = models.DateField(null=True, blank=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
forms.py
from django import forms
from django.contrib.auth import get_user_model
from .models import Profile
non_allowed_usernames = ['abc']
User = get_user_model()
class RegisterForm(forms.Form):
username = forms.CharField()
email = forms.EmailField()
password1 = forms.CharField(
label='Password',
widget=forms.PasswordInput(
attrs={
"class": "form-control",
"id": "user-password"
}
)
)
password2 = forms.CharField(
label='Confirm Password',
widget=forms.PasswordInput(
attrs={
"class": "form-control",
"id": "user-confirm-password"
}
)
)
def clean_username(self):
username = self.cleaned_data.get("username")
qs = User.objects.filter(username__iexact=username)
if username in non_allowed_usernames:
raise forms.ValidationError(
"This is an invalid username, please pick another.")
if qs.exists():
raise forms.ValidationError(
"This is an invalid username, please pick another.")
return username
def clean_email(self):
email = self.cleaned_data.get("email")
qs = User.objects.filter(email__iexact=email)
if qs.exists():
raise forms.ValidationError("This email is already in use.")
return email
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(
attrs={
"class": "form-control"
}))
password = forms.CharField(
widget=forms.PasswordInput(
attrs={
"class": "form-control",
"id": "user-password"
}
)
)
def clean_username(self):
username = self.cleaned_data.get("username")
# thisIsMyUsername == thisismyusername
qs = User.objects.filter(username__iexact=username)
if not qs.exists():
raise forms.ValidationError("This is an invalid user.")
if qs.count() != 1:
raise forms.ValidationError("This is an invalid user.")
return username
class BioForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
'bio'
]
views.py
def test_view(request):
form = BioForm(request.POST or None)
if BioForm.is_valid():
#any code to the the Bio to the specific user
return render(request, 'test.html', {'form': form})
Как мне теперь сохранить "био" для конкретного пользователя с помощью формы в HTML шаблоне? Так, чтобы у меня была "био" для каждого пользователя в профиле и я мог получить ее в других шаблонах.
Большое спасибо :-)