instance not getting user information when calling in form

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

Couple of thoughts here.

First, anytime you’re working with multiple Django forms within the same HTML form, you need to use a prefix for your forms. (This ensures that unique names are used for the elements within the form so that Django knows what fields are associated with which forms.)

Second, unless you want each of those two forms to be submitted separately, there’s no need to create two different forms. You can render the fields individually and independently.

Third, I’m not sure, based upon what you have posted here, what you mean by:

What “user data” are you talking about here?

First of all, thank you very much for your fast answer.

Yes, my main idea was to get for all fields separate forms to have them all individually and independently. But that isn’t so necessary for me, so I tried to split the form and to take the whole form whoever I get it, but the issue stays.
Also adding the prefix, even to one form at the html file, nothing changes.

Sorry for my difficulties with English. What I mean was that with no changes, I’m getting the mail address inside the form.

updated forms.py:

class UsernameUpdateForm(forms.ModelForm):
	#username = forms.CharField(max_length=150, label='', help_text='', required=False)
	email = forms.EmailField(label='', error_messages={}, required=False)
	prefix = "username"

	class Meta:
		model = User
		fields = ['username', 'email']

	def __init__(self, *args, **kwargs):
		super(UsernameUpdateForm, self).__init__(*args, **kwargs)

		print('Mail -> ', kwargs['instance'].email, '<-')

		self.fields['username'].widget.attrs['class'] = 'ProfileBoxUserInformation'
		self.fields['username'].label = ''
		self.fields['username'].help_text = ''
		self.fields['username'].required = False

		self.fields['email'].widget.attrs['class'] = 'ProfileBoxUserInformation'

## # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#	unused
class EmailUpdateForm(forms.ModelForm):
	email = forms.EmailField(label='', error_messages={}, required=False)#max_length=150, label='', help_text='')
	prefix = "email"

	class Meta:
		model = User
		fields = ['email']

	def __init__(self, *args, **kwargs):
		super(EmailUpdateForm, self).__init__(*args, **kwargs)
		
		self.fields['email'].widget.attrs['class'] = 'ProfileBoxUserInformation'

updated views.py:

@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})

updated profile.html:

<div class="ProfileBoxInnerMainBox">
			<div></div>
			

			<div class="ProfileBoxPictureBox">
				<div class="ProfileBoxPictureButtonBox">
					<button class="ProfileBoxPictureButton">
						Bearbeiten
					</button>
				</div>
				<img src="{{user.userprofile.image.url}}" class="ProfileBoxPicture"></img>
			</div>

			
			<div class="ProfileBoxUserInfoBox">
				<span class="ProfileBoxUserTitle"> Nutzername </span>
					
					<form method="POST" enctype="multipart/form-data" action="{% url 'user-profile' %}">
						{% csrf_token %}

						{{ context.usernameUpForm.email }}
						<!-- <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>
			<div></div>
		</div>

Output of print() in forms.py:

System check identified no issues (0 silenced).
February 21, 2024 - 20:53:32
Django version 5.0.2, using settings 'V1_first_try.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Mail ->   <-

[21/Feb/2024 20:53:34] "GET /profile/ HTTP/1.1" 200 13096
   ...

I’m not seeing anything wrong here, so the next step would be to verify that you’re using and referencing the data that you think you’re using.

I’d add more prints statements to this, like a print(request.user) in the view in the else clause before the usernameUpForm definition.

I’d also add prints for kwargs before and after the super call in __init__

I’ve added some outputs now at various parts, but the output is always the same. I also added some output in the html file, but the result was equal. Only the mail address couldn’t be displayed.

Terminal output


Output inside form before super():

Instance ->  Gregor <-
Mail ->   <-
First name ->  Gregor <-
Last name ->  Welling <-
Username ->  Gregor <-
Id ->  1 <-
self created model userprofile from this app ->  User Profile Gregor <-

Output inside form after super():

Instance ->  Gregor <-
Mail ->   <-
First name ->  Gregor <-
Last name ->  Welling <-
Username ->  Gregor <-
Id ->  1 <-
self created model userprofile from this app ->  User Profile Gregor <-
Output inside else statement:

Instance ->  Gregor <-
Mail ->   <-
First name ->  Gregor <-
Last name ->  Welling <-
Username ->  Gregor <-
Id ->  1 <-
self created model userprofile from this app ->  User Profile Gregor <-

At that point I wanted to be sure, so I looked inside the admin page, where I was surprised to discover that the email must have been deleted during a previous request.

With this new info, I started changing some things, but had to make some complicated if queries to get the forms working.
I first tried to use one form and to split it, but every time I send the form I was getting the problem, that every field I haven’t changed was deleted. Even if I used has_changed() the fields were deleted, even there were first displayed the old information.
Is that normal, or what should I do here?

My workaround now:

forms.py:

class UsernameUpdateForm(forms.ModelForm):
	username = forms.CharField(max_length=150, label='', help_text='', required=False)
	prefix = "username"

	class Meta:
		model = User
		fields = ['username']

	def __init__(self, *args, **kwargs):
		super(UsernameUpdateForm, self).__init__(*args, **kwargs)

		self.fields['username'].initial = kwargs['instance'].username
		print('Initial: ', self.fields['username'].initial)

		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='')
	prefix = "email"

	class Meta:
		model = User
		fields = ['email']

	def __init__(self, *args, **kwargs):
		super(EmailUpdateForm, self).__init__(*args, **kwargs)

		self.fields['email'].initial = kwargs['instance'].email
		print('Initial: ', self.fields['email'].initial)

		self.fields['email'].widget.attrs['class'] = 'ProfileBoxUserInformation'

views.py:

@login_required
def home(request):
	if request.method == 'POST':
		usernameUpForm = UsernameUpdateForm(request.POST, instance=request.user) #request.FILES, enctype="multipart/form-data"
		emailUpForm = EmailUpdateForm(request.POST, instance=request.user)

		# if input is valid
		if usernameUpForm.is_valid() and ('username-username' in usernameUpForm.data.keys()):
			# if field has been changed   AND   field isn't empty/unchange/unclicked
			if (usernameUpForm.fields['username'].initial != usernameUpForm.data['username-username']) and (usernameUpForm.data['username-username'] != None):
				print('\nneuer username\n')
				usernameUpForm.save()

			# returning message
			#messages.success(request, f'Der Username wurde geändert zu')

		# if input is valid
		if emailUpForm.is_valid() and ('email-email' in emailUpForm.data.keys()):
			#field has been changed   AND   field isn't empty/unchange/unclicked
			if (emailUpForm.fields['email'].initial != emailUpForm.data.get('email')) and (emailUpForm.data.get('email') != None):
				print('\nneue email\n')
				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)

	context = {
		'usernameUpForm' : usernameUpForm,
		'emailUpForm' : emailUpForm
	}

	return render(request, 'user/profile.html', {'title':'user - Profile', 'context':context})

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 }}
						
					</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" enctype="multipart/form-data" 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>
			<div></div>