Hello everyone,
This is my first time in a forum like this, so I hope I’m doing everything right.
My problem is that I want to display a box with the profile data on my page, which should also allow me to edit the data. Therefore I wanted to display the data in a structured way in a CSS table with different forms.
Since I wanted to display the email and the user name in different places, I created two forms, both of which have User as their model.
The forms as such are also displayed correctly, but the user data from the loaded instance cannot be displayed, or they are not accessible in the forms. I tried to output the email in the forms, but it cannot be output, so it is just an empty string. The username, on the other hand, is still displayed correctly in the forms, but cannot be displayed as initial on the page.
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from user.models import UserProfile
####################################################################################################
# user registration form
## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class MyUserRegisterForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=200)
last_name = forms.CharField(max_length=200)
termsOfRight = forms.BooleanField(
required=True,
label='Ich bin mit der Speicherung und Verarbeitung meiner Daten einverstanden',
help_text='Durch die Registierung werden Ihre Daten gespeichert und verarbeitet. Genauere Informationen dazu finden Sie unten im Impressum der Webseite.')
mailNotification = forms.BooleanField(
required=False,
label='Biite informiert mich über Neuigkeiten',
help_text='Dies ist kein Newsletter, sondern lediglich zur Kundtuung von Neuerungen für die Nutzer.')
class Meta:
fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2']
model = User
####################################################################################################
# user and profile update forms
## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class UsernameUpdateForm(forms.ModelForm):
#username = forms.CharField(max_length=150, label='', help_text='', required=False)
class Meta:
model = User
fields = ['username']
def __init__(self, *args, **kwargs):
super(UsernameUpdateForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'ProfileBoxUserInformation'
self.fields['username'].label = ''
self.fields['username'].help_text = ''
self.fields['username'].required = False
## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class EmailUpdateForm(forms.ModelForm):
email = forms.EmailField(label='', error_messages={}, required=False)#max_length=150, label='', help_text='')
class Meta:
model = User
fields = ['email']
def __init__(self, *args, **kwargs):
super(EmailUpdateForm, self).__init__(*args, **kwargs)
self.fields['email'].widget.attrs['class'] = 'ProfileBoxUserInformation'
part of views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import MyUserRegisterForm, UsernameUpdateForm, EmailUpdateForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group, User
####################################################################################################
@login_required
def home(request):
if request.method == 'POST':
print('Im POST angekommen')
usernameUpForm = UsernameUpdateForm(request.POST, instance=request.user) #request.FILES, enctype="multipart/form-data"
emailUpForm = EmailUpdateForm(request.POST, instance=request.user)
if usernameUpForm.is_valid():
usernameUpForm.save()
# returning message
messages.success(request, f'Der Username wurde geändert zu')
if emailUpForm.is_valid():
emailUpForm.save()
# returning message
messages.success(request, f'Die Email wurde geändert zu')
return redirect('user-profile')
else:
usernameUpForm = UsernameUpdateForm(instance=request.user)
emailUpForm = EmailUpdateForm(instance=request.user)
ich = request.user
#print(request.user.username, request.user.first_name, request.user.last_name)
print(ich.email)
context = {
'usernameUpForm' : usernameUpForm,
'emailUpForm' : emailUpForm
}
return render(request, 'user/profile.html', {'title':'user - Profile', 'context':context})
part of profile.html:
<div class="ProfileBoxUserInfoBox">
<span class="ProfileBoxUserTitle"> Nutzername </span>
<form method="POST" enctype="multipart/form-data" action="{% url 'user-profile' %}">
{% csrf_token %}
{{ context.usernameUpForm }}
<!-- <input type="text" value="{{user.username}}" class="ProfileBoxUserInformation" readonly='true' ondblclick='this.readOnly="";'> -->
</form>
<div style="grid-column-start: 1;grid-column-end: 3;"><hr></div>
<span class="ProfileBoxUserTitle"> Vorname </span>
<div>
<!-- <input type="text" value="{{user.first_name}}" class="ProfileBoxUserInformation" disabled> -->
</div>
<span class="ProfileBoxUserTitle"> Nachname </span>
<div>
<!-- <input type="text" value="{{user.last_name}}" class="ProfileBoxUserInformation" disabled> -->
</div>
<div style="grid-column-start: 1;grid-column-end: 3;"><hr></div>
<span class="ProfileBoxUserTitle"> Email Adresse </span>
<!-- <form method="POST" action="{% url 'user-profile' %}">
{% csrf_token %}
{{ context.emailUpForm }}
</form> -->
<div class="ProfileBoxUserTitle" style="grid-column-start: 1;grid-column-end: 3;text-align: center;margin-top: 0.2em;">
Ich erlaube Benachrichtigung per Mail:
<input type="checkbox" class="ProfileBoxUserInformation" {% if user.userprofile.mailNotification %} checked {% endif %}></input>
</div>
<div style="grid-column-start: 1;grid-column-end: 3;"><hr></div>
<div style="grid-column-start: 1;grid-column-end: 3;text-align: center;margin-top: 0.2em; height: fit-content;">
<button class="ProfileBoxButton" type="submit">Änderungen übernehmen / Passwort ändern</button>
</div>
<div></div>
</div>
I also tried to use only one of the forms and also to get access to the username and the email in both forms seperate, but it doesn’t work at all.
Thank you very much for your help and effort