Django Relationship :- User Email Not Showing

I Have Created Project Using Custom User Model & I Have Used Relationships To Get Users, But I Am Unable To Get User Email Addresses In Relationship Field

Here Is File

from django.db import models
from django.contrib.auth.models import (

# Create your models here.
class User_Manager(BaseUserManager):
    use_in_migrations = True
    username = None

    def create_user(self, email=None, password=None, **extra_fields):
        user = self.model(email=self.normalize_email(email))
        return user

    def create_superuser(self, email=None, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_active", True)
        extra_fields.setdefault("is_admin", True)

        if extra_fields.get("is_staff") is not True:
            raise ValueError("Superuser must have is_staff=True.")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("Superuser must have is_superuser=True.")

        return self.create_user(email, password, **extra_fields)

class User_signup(AbstractBaseUser, PermissionsMixin):
    joined_on = models.DateTimeField(auto_now_add=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    FirstName = models.CharField(max_length=20)
    LastName = models.CharField(max_length=20)
    email = models.CharField(unique=True, max_length=100)
    code = models.CharField(max_length=8)
    mobile = models.CharField(max_length=13)
    state = models.CharField(max_length=30)
    city = models.CharField(max_length=30)
    Gender = models.CharField(max_length=8)
    password = models.CharField(max_length=20)
    password2 = models.CharField(max_length=20)

    objects = User_Manager()
    USERNAME_FIELD = "email"

    def __str__(self):

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

class Contact_website(models.Model):
    user_email = models.ForeignKey(User_signup,on_delete=models.CASCADE,null=True)
    issue_date = models.DateTimeField(auto_now_add=True)
    message = models.CharField(max_length=2000, null=True)

Here Is File

from django import forms
import re
from .models import User_signup,Submit_problem,Online_survey,Contact_website
from django.core.validators import FileExtensionValidator
from django.core.exceptions import ValidationError
from django.contrib.auth.forms import AuthenticationForm

class User_signup_form(forms.ModelForm):
    class Meta:
        model = User_signup
        fields = '__all__'
    FirstName = forms.CharField(error_messages={'required': 'First Name Required'}, label='First Name', widget=forms.TextInput(
        attrs={'placeholder': 'Your First Name', 'class': 'input1'}))
    LastName = forms.CharField(error_messages={'required': 'Last Name Required'}, label='Last Name', widget=forms.TextInput(
        attrs={'placeholder': 'Your Last Name', 'class': 'input2'})) 
    email = forms.EmailField(error_messages={'required': 'Email Id Required'}, label='Email Id', widget=forms.EmailInput(
        attrs={'placeholder': 'Your Email ID', 'class': 'input3'}))
    code = forms.CharField(disabled=True, initial='(+91)', label='Code',
                           widget=forms.TextInput(attrs={'class': 'countrycode'}))
    mobile = forms.CharField(error_messages={'required': 'Mobile Number Required'}, label='Mobile', widget=forms.NumberInput(
        attrs={'placeholder': 'Your Mobile Number', 'class': 'input4'}))
    state = forms.CharField(label='State', widget=forms.Select(
        choices=STATES, attrs={'class': 'select2'}))
    city = forms.CharField(label='City', widget=forms.Select(
        choices=CITY, attrs={'class': 'select3'}))
    Gender = forms.CharField(error_messages={'required': 'Select Gender'}, label='Gender :- ',
                             widget=forms.RadioSelect(choices=CHOICES, attrs={'class': 'radio1'}))
    password = forms.CharField(error_messages={'required': 'Choose Password'}, label='Password', widget=forms.PasswordInput(
        attrs={'placeholder': 'Choose Password', 'class': 'input5'}))
    password2 = forms.CharField(error_messages={'required': 'Reenter Password Agian'}, label='Reenter Password', widget=forms.PasswordInput(
        attrs={'placeholder': 'Choose Same Password Again', 'class': 'input6'}))

    def clean_FirstName(self):
        cleaned_data = super(User_signup_form, self).clean()
        valFname = cleaned_data.get('FirstName')
        valpat = '[0-9\~\`\!\@\#\$\%\^\&\*\(\)\-\_\|\[\]{\}\;\:\"\,\.\/\?\=\+\<\>]'
        if len(valFname) < 3:
            raise forms.ValidationError('Minimum 3 Character Required')
        if (, valFname)):
            raise forms.ValidationError('Numbers & Symbols Not Allowed')
        return valFname

    def clean_LastName(self):
        cleaned_data = super(User_signup_form, self).clean()
        vallname = cleaned_data.get('LastName')
        valFname = cleaned_data.get('FirstName')
        valpat1 = '[0-9\~\`\!\@\#\$\%\^\&\*\(\)\-\_\|\[\]{\}\;\:\"\,\.\/\?\=\+\<\>]'
        if (, vallname)):
            raise forms.ValidationError('Numbers & Symbols Not Allowed')
        if vallname == valFname:
            raise forms.ValidationError("First & Last Name Should'nt Be Same")
        return vallname

    def clean_mobile(self):
        cleaned_data = super(User_signup_form, self).clean()
        mobile = cleaned_data.get('mobile')
        regex3 = '[~\`\!\@\#\$\%\^\&\*\(\)\-\_\|\[\]{\}\;\:\"\,\.\/\?\=\+\<\>\']'
        userfilter = User_signup.objects.filter(mobile=mobile)
        if userfilter:
            raise forms.ValidationError('Mobile Already Registered')
        if len(mobile) < 8:
            raise forms.ValidationError('Mobile Too Short')
        if len(mobile) > 13:
            raise forms.ValidationError('Mobile Too Long')
        if (, mobile)):
            raise forms.ValidationError('Alphabets & Symbols Not Allowed')
        return mobile

    def clean_email(self):
        cleaned_data = super(User_signup_form, self).clean()
        username = cleaned_data.get('email')
        userfilter = User_signup.objects.filter(email=username)
        if userfilter:
            raise forms.ValidationError('Email Already Registered')
        return username

    def clean_password(self):
        cleaned_data = super(User_signup_form, self).clean()
        password = cleaned_data.get('password')
        regex1 = '[0-9]'
        regex2 = '[A-Z]'
        regex3 = '[a-z]'
        regex4 = '[~\`\!\@\#\$\%\^\&\*\(\)\-\_\|\[\]{\}\;\:\"\,\.\/\?\=\+\<\>]'
        if len(password) < 8:
            raise forms.ValidationError('Password Must Contain 8 Characters')
        if not (, password)):
            raise forms.ValidationError(
                'Password Must Contain 1 Digit Between[0-9]')
        if not (, password)):
            raise forms.ValidationError(
                'Password Must Have 1 Uppercase Between[A-Z]')
        if not (, password)):
            raise forms.ValidationError(
                'Password Must Have 1 Lowercase Between[a-z]')
        if not (, password)):
            raise forms.ValidationError(
                'Password Must Have 1 Symbol Eg.[@,$,%,&,*]')
        return password

    def clean_rpassword(self):
        cleaned_data = super(User_signup_form, self).clean()
        password = cleaned_data.get('password')
        rpassword = cleaned_data.get('rpassword')

        if rpassword != password:
            raise forms.ValidationError('Password Does Not Match')
        return rpassword

    def clean_state(self):
        cleaned_data = super(User_signup_form, self).clean()
        state = cleaned_data.get('state')
        valstn = 'Select'

        if state == valstn:
            raise forms.ValidationError('Select State')
        return state

    def clean_city(self):
        cleaned_data = super(User_signup_form, self).clean()
        city = cleaned_data.get('city')
        valct = 'Select'

        if city == valct:
            raise forms.ValidationError('Select City')
        return city

class Contact_website_form(forms.ModelForm):
    class Meta:
        model = Contact_website
        fields = ['message']

    message = forms.CharField(
        error_messages={'required': 'Enter Your Message'},
                'class': 'contact_website_message',
                'placeholder': 'Enter Your Message Here'
        label='Enter Your Message')  

Here Is File

def userregistration(request):
    if not request.user.is_authenticated:
        if request.method == 'POST':
            fm = User_signup_form(request.POST)
            if fm.is_valid():
                firstName = fm.cleaned_data.get('FirstName')
                lastname = fm.cleaned_data.get('LastName')
                email = fm.cleaned_data.get('email')
                confirm_email = email.lower()
                code = fm.cleaned_data.get('code')
                mobile = fm.cleaned_data.get('mobile')
                state = fm.cleaned_data.get('state')
                city = fm.cleaned_data.get('city')
                gender = fm.cleaned_data.get('Gender')
                password = make_password(fm.cleaned_data.get('password'))
                password2 = make_password(fm.cleaned_data.get('password2'))
                user1 = User_signup(
                return redirect('success')
            fm = User_signup_form()
    if request.user.is_authenticated:
        return redirect('/submitproblemafterlogin/')        
    return render(request, 'jobglobel/usersignup.html',{'form': fm})

def contact_website_view(request):
    if request.method == 'POST':
        fm = Contact_website_form(request.POST)
        if fm.is_valid():
            message = fm.cleaned_data.get('message')

            user1 = Contact_website(
            return redirect('aftercontactingwebsite')
        fm = Contact_website_form()
    return render(request, 'jobglobel/contact_website.html', {'form': fm})

You need to post the relevant code (and/or) templates here showing what you’re trying to do.

Note, when posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted, which is critical with Python.

Sir, I Just Edited The Code

Yep, I see that. So what specifically in that code is not working as intended?

Everything is Fine, First It Was Showing Me An Error Due To Not Adding null=True In Relationship Field In Model " Django Integrity Error : NULL Constrained Failed "

After That i Kept null=True In Relationship Field Then It Is Stop Showing Me Error But It is Not Showing Me User Email Which Is Unique Field In My User Model

Have You Find Any Error In Coding ?

Changing null=True is addressing the symptom and not the real problem.

You’ve got a couple different issues here.

  • Your contact_website_view does not set the user_email field in the instance of Contact_website being created.

  • Your user_email field in Contact_website is misnamed. It’s a foreign key field, which means it’s a reference to an instance of the User_signup model, not the email field within that instance.

  • Your validation of first and last names not being the same don’t belong in a clean_fieldname method. Validation accessing more than one field should be done in the form’s clean method.

  • You have a clean_rpassword method that doesn’t appear like it’s ever going to be used.

  • You shouldn’t be calling super().clean() within a clean method. The form class makes the cleaned_data dict available as an attribute of that class, accessible using self.

  • You have a lot of code to copy values in your fm.is_valid block that aren’t needed when you use a model form.

  • There’s no reason to make both password and password2 fields in your model.

  • To avoid confusion in the future, I strongly suggest you adopt Django’s coding conventions regarding class and attribute names.

And these are just the things I spotted right off-hand.

I suggest you review the docs for:

You may also consider it worthwhile to look at the forms created by the Admin for the built-in user class.

I Made Changes To Identify User in Contact Website Form As Below

def contact_website_view(request):
    if request.method == 'POST':
        fm = Contact_website_form(request.POST)
        if fm.is_valid():
            success_id = 3
            return redirect(f'/success_responce/{success_id}/')
        fm = Contact_website_form()
    return render(request, 'news/contact_website.html', { 'user': request.user,'form': fm})```

But It Is Still Not Saving Form, And Not Even Showing Any Error .

The easiest way to diagnose this would be to add some print statements at the appropriate points within this view to see what the data is that you are receiving and understanding why certain code-paths are being taken.

In I Have Used Below Code

class Contact_website_form(forms.Form):
    class Meta:
        model = Contact_website
        fields = '__all__'

I Tried With forms.ModelForm And Tried To Print Output But It Is Not Saving Form And I Am Unable To Access Another Model Using User Model by Applying Query Like {{user.Contact_website.website_message}}

For Above Code I Have Written View Code Like This

def contact_website_view(request):
    if request.method == 'POST':
        fm = Contact_website_form(request.POST)
        if fm.is_valid():
            website_message  = fm.cleaned_data.get('website_message')
            user1 = Contact_website(
                                  user_name = request.user,
            success_id = 3
            return redirect(f'/success_responce/{success_id}/')
        fm = Contact_website_form()
    return render(request, 'news/contact_website.html', { 'user': request.user,'form': fm})

And With Using Forms.ModelForm
I Had Wrote View Like This, But Is Was Unable To Save Form

def contact_website_view(request):
    if request.method == 'POST':
        fm = Contact_website_form(request.POST)
        if fm.is_valid():
            success_id = 3
            return redirect(f'/success_responce/{success_id}/')
        fm = Contact_website_form()
    return render(request, 'news/contact_website.html', { 'user': request.user,'form': fm})```

I have suggested you add some print statements to your view to show you what data you’re working with at each step.

Please post the view with the print statements you have added along with the output generated by those statements from your console.