Profil użytkownika Django
Próbuję utworzyć formularz "Edytuj Profil"w interfejsie. Co się dzieje, że mój formularz (Nie jestem 100% pewien) próbuje utworzyć użytkownika zamiast znaleźć bieżącego użytkownika i zaktualizować jego profil. Więc myślę, że w tym problem. Sprawdziłem wiele pytań tutaj, ale żadne nie było wystarczająco jasne. Pola, które próbuję edytować, to adres e-mail, imię i nazwisko. (Również chciałbym dodać uda
Forms.py
class UpdateProfile(forms.ModelForm):
username = forms.CharField(required=True)
email = forms.EmailField(required=True)
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name')
def clean_email(self):
username = self.cleaned_data.get('username')
email = self.cleaned_data.get('email')
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError('This email address is already in use. Please supply a different email address.')
return email
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
Views.py
def update_profile(request):
args = {}
if request.method == 'POST':
form = UpdateProfile(request.POST)
form.actual_user = request.user
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('update_profile_success'))
else:
form = UpdateProfile()
args['form'] = form
return render(request, 'registration/update_profile.html', args)
2 answers
Jesteście bardzo blisko. Kiedy tworzysz instancję formularza, musisz przekazać obiekt User
, który modyfikujesz jako argument instance
.
From the docs:
Podklasa ModelForm może zaakceptować istniejącą instancję modelu jako argument słowa kluczowego
instance
; jeśli jest podany, save () zaktualizuje ten przypadek.
W Twoim kodzie wyglądałoby to tak:
form = UpdateProfile(request.POST, instance=request.user)
if form.is_valid():
...
Możesz sprawdzić więcej informacji tutaj: https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#the-save-method
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-21 20:34:01
Lub jeśli chcesz przejść do widoku opartego na klasach, używając UpdateView, możesz zrobić coś takiego w views.py:
class UpdateProfile(UpdateView):
model = MyProfile
fields = ['first_name', 'last_name', 'image', 'url', 'biography', '...'] # Keep listing whatever fields
# the combined UserProfile and User exposes.
template_name = 'user_update.html'
slug_field = 'username'
slug_url_kwarg = 'slug'
Gdzie masz coś takiego do MyProfile w models.py:
class MyProfile(AbstractUser):
image = models.ImageField(upload_to='uploads/profile/')
url = models.URLField()
biography = models.CharField(max_length=1000)
I twoje urls.py podobnie (zakładając, że używasz django allauth i chcesz uhonorować konwencję url):
....
url(r'^accounts/update/(?P<slug>[\-\w]+)/$', views.UpdateProfile.as_view(), name='update_user'),
....
Reszta to zabawa Django! Polecam napisać mniej kodu, jeśli można do podstawowych zadań CRUD, chyba że jest to naprawdę konieczne, aby zrobić coś niestandardowego, z których nawet nadal możesz uciec, rozszerzając widoki oparte na klasach.
I jeśli jesteś w więcej, zobacz tutaj: Django Docs on Class Based Views
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-25 21:18:18