Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello.
I am creating a simple project using the Django framework. I have a model in
Python
models.py
Here is its code:

Python
from django.db import models
from django.db.models.fields import EmailField
from django.contrib.auth.models import User

# Create your models here.

class MyUser(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    mobile_number = models.CharField(max_length=20, unique=True)
    birthday = models.DateField()
    profile_photo = models.ImageField(default="images.png", null=True, 
    blank=True,upload_to='media/profiles')
    date_joined = models.DateTimeField(auto_now_add=True, null=True)
    country = models.CharField(max_length=15)
    city = models.CharField(max_length=15)
    region = models.CharField(max_length=15)
    address = models.TextField(null=True, blank=True)
    postal_code = models.CharField(max_length=10, unique=True)
    is_active = models.BooleanField(default=True)
    user_email = models.EmailField(null=False, blank=False)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"
User.profile = property(lambda u : MyUser.objects.get_or_create(user = u)[0])


And I also have two forms in
Python
forms.py

Their code is :
Python
from django.contrib.auth import models
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms import fields, ModelForm
from .models import *

class MyUserProfile(forms.ModelForm):
    class Meta:
        model= MyUser
        fields = (
            'first_name',
            'last_name',
            'mobile_number',
            'birthday',
            'profile_photo',
            'country',
            'city',
            'region',
            'address',
            'postal_code',
            'user_email'
        )

class NewUserForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ("username" 
                    , "email" 
                    , "password1" 
                    , "password2")

    def save(self, commit=True):
        user = super(NewUserForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user


I have used the second form for authentication(login, register, logout), but now I want to use the first form and
Python
MyUser
model to create a profile for my users, so I write this function in
Python
views.py
to save the data:

Python
@login_required(login_url='login')
def accountSettings(request):
    if request.method == "POST":
        user_account_form = MyUserProfile(request.POST , request.FILES, instance=request.user.profile)
        if user_account_form.is_valid():
            user_account_form.save()
            messages.success(request, ('Your profile was successfully created!!'))
        else:
            messages.error(request, 'Error saving form')

        return redirect("http://127.0.0.1:8000/")
    
    else:
        user = request.user
        profile = user.profile
        user_account_form = MyUserProfile(instance=profile)

    context = {'form' : user_account_form}
    return render(request , 'user/user.html' , context)



I am also using django-crispy-forms and bootstrap to make my website prettier but unfortunately, I do not know why the inputs and fields are not rendered. Here is the code of my user.html :
HTML
<!DOCTYPE html>
{% extends "base.html" %}

{% block content%}

{% load crispy_forms_tags %}


<style>
	.profile-pic{
		max-width: 200px;
		max-height:200px;
		margin: 0 auto;
		border-radius: 50%;
	}
</style>

<br>
<div class="row">
	<div class="col-md-3">
		<div class="card card-body">
			<a class="btn btn-warning" href="{% url 'Posts:home' %}"> ← Back to Home</a>
			<hr>
			<h3 style="text-align: center">Account Settings</h3>
			<hr>
			<img class="profile-pic" src="{{request.user.profile_photo.url}}" >
		</div>
	</div>
	<div class="col-md-9">
		<div class="card card-body">
			
			<form method="POST" action="" enctype="multipart/form-data">
				{% csrf_token %}
				{{user_account_form.as_p}}
		
			<input class="btn btn-primary" type="submit" name="Update Information">
			</form>
		</div>
	</div>
</div>



{% endblock %}


What I have tried:

I have searched about this problem and it has been told that the problem is because of views.py function and we must add an else
block to our method for when the request is GET, but anyway it does not show the fields.
I will be grateful for your help.
Posted
Updated 30-Aug-21 6:10am
v2

1 solution

I found the problem-_- I should write in my template form.as_p because I set "form" as the key of my object and for using crispy-forms I should write {{form|crispy}}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900