Double users created - django

I have an issue with my code in the sense that when a student registers, a double instance of the student is created. I don't know what's the problem with these block of code. Please help out,also I don't know how to make a link between a teacher and a student so as to allow the teacher to add results for students.
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm,UserUpdateForm ,InformationUpdateForm,InformationForm
def home(request):
return render(request, 'student/home.html')
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
a_form=InformationForm(request.POST)
# ####and a_form.is_valid()
if form.is_valid() and a_form.is_valid():
user = form.save()
# form.save()
#finally this get links the models, forms and views for user input and all information is registered
information = a_form.save()
# a_form.save()
user.information.majors=a_form.cleaned_data.get('majors')
user.information.department=a_form.cleaned_data.get('department')
user.information.nationality=a_form.cleaned_data.get('nationality')
user.information.date_of_birth=a_form.cleaned_data.get('date_of_birth')
user.information.passport_number=a_form.cleaned_data.get('passport_number')
user.information.phone_number=a_form.cleaned_data.get('phone_number')
user.information.sex=a_form.cleaned_data.get('sex')
user.save()
information.save()
# for this type user input is for for username,last,first and email is registered
# form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
a_form = InformationForm()
context={'form':form,'a_form':a_form }#,'a_form':a_form
return render(request, 'student/register.html', context)
#login_required
def profile(request):
return render(request, 'student/profile.html')#,context
#login_required
def profile_update(request):
if request.method == 'POST':
u_form=UserUpdateForm(request.POST,instance=request.user)
i_form=InformationUpdateForm(request.POST,request.FILES,instance=request.user.information)
if u_form.is_valid() and i_form.is_valid():
u_form.save()
i_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('profile')
else:
u_form=UserUpdateForm(instance=request.user)
i_form=InformationUpdateForm(instance=request.user.information)
context={'u_form': u_form,
'i_form':i_form}
return render(request, 'student/profile_update.html',context)
models.py
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
# CHOICES=[('M','Male'),
# ('F','Female')]
class Information(models.Model):
M='Male'
F='Female'
SELECT_GENDER_CHOICE=[(M, 'Male'),
(F, 'Female')]
########################################################
B='Bachelors'
Ma='Masters'
P='PhD'
SELECT_DEGREE_CHOICE=[(B, 'Bachelors'),
(Ma, 'Masters'),(P, 'PhD')]
#########################################################
Y1='1 year'
Y2='2 year'
Y3='3 year'
Y4='4 year'
Y5='5 year'
SELECT_YEARS_CHOICE=[(Y1, '1 year'),(Y2, '2 year'),(Y3, '3 year'),(Y4, '4 year'),(Y5, '5 year')]
user = models.OneToOneField(User,null=True,on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='student')
nationality=models.CharField(max_length=120,blank=False)
sex=models.CharField(max_length=8,choices=SELECT_GENDER_CHOICE,default=M)
department=models.CharField(max_length=120,blank=False)
years=models.CharField(max_length=120,blank=False,choices=SELECT_YEARS_CHOICE,default=Y1,null=True)
degree=models.CharField(max_length=120,blank=False,choices=SELECT_DEGREE_CHOICE,null=True)
majors=models.CharField(max_length=500,blank=False)
phone_number=models.CharField(max_length=12,blank=False)
passport_number=models.CharField(max_length=50,blank=False)#unique=True)
date_of_birth=models.CharField(max_length=10,blank=False)
report=models.FileField(default='StudentResults/DEFAULT_SHEET.xlsx',upload_to='StudentResults',max_length=500,blank=True)#,null=True
reg_no=models.CharField(max_length=10,null=True,unique=True)
def __str__(self):
return f'{self.passport_number} Information'
def save(self,*args, **kwargs):
super().save(*args, **kwargs)
img=Image.open(self.image.path)
if img.height>300 or img.width>300:
output_size=(300,300)
img.thumbnail(output_size)
img.save(self.image.path)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Information
# CHOICES=[('M','Male'),
# ('F','Female')]
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}))
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'}))
first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First name'}))
last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last name'}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm'}))
class Meta:
model = User
fields = ['username','first_name','last_name', 'email', 'password1', 'password2']
class InformationForm(forms.ModelForm):
#sex=forms.ChoiceField(choices=CHOICES)
department = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Department'}))
majors = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Majors'}))
nationality = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nationality'}))
date_of_birth = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Date of birth'}))
passport_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Passport number'}))
phone_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone number'}))
class Meta:
model=Information
fields=['department','majors','degree','years','nationality','date_of_birth','passport_number','phone_number','sex']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['email']
# def email(self):
# email = self.cleaned_data.get("email")#this gets the default title but does not override the required field
# #you can have multiple nested if else/elif statements. You can use this for email validation
# if not ".com" in email:
# raise forms.ValidationError("This is not a email")
# else:
# return email
class InformationUpdateForm(forms.ModelForm):
class Meta:
model=Information
fields=['phone_number']
signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Information
#receiver(post_save,sender=User)
def create_information(sender,instance,created,**kwargs):
if created:
Information.objects.create(user=instance)
#receiver(post_save,sender=User)
def save_information(sender,instance,**kwargs):
instance.information.save()
student-profile-page
{% extends "student/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.information.image.url }}">
<div class="media-body">
<p class="text-secondary">Username: {{ user.username }}</p>
<p class="text-secondary">First Name: {{ user.first_name }}</p>
<p class="text-secondary">Last Name: {{ user.last_name }}</p>
<p class="text-secondary">Email: {{ user.email }}</p>
<p class="text-secondary">Passport Number: {{ user.information.passport_number }}</p>
<p class="text-secondary">Date of Birth: {{ user.information.date_of_birth }}</p>
<p class="text-secondary">Sex: {{ user.information.sex }}</p>
<p class="text-secondary">Phone Number: {{ user.information.phone_number }}</p>
<p class="text-secondary">Nationality: {{ user.information.nationality }}</p>
<p class="text-secondary">Majors: {{ user.information.majors }}</p>
<p class="text-secondary">Depatrment: {{ user.information.department }}</p>
<p class="text-secondary">Results: {{ user.information.result }}</p>
<p class="text-secondary">Years: {{ user.information.years }}</p>
<p class="text-secondary">Degree: {{ user.information.degree }}</p>
<a class="btn btn-outline-info" href="{{ user.information.report.url}}">Download your Report</a>
</div>
</div>
{% comment %} <form method="POST">
{% csrf_token %}
<fieldset class="form-group" enctype="multipart/form-data">
<legend class="border-bottom mb-4">Profile Info</legend>
{{ i_form|crispy }}
{{ u_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
</div> {% endcomment %}
{% endblock content %}

That is because you are saving a_form.save() then again saving user.information.save(). You need to change the code like this:
user = form.save()
information = a_form.save(commit=False)
information.user = user
information.save()
messages.success(request, 'Your account has been created! You are now able to log in')
return redirect('login')
You can remove the rest of the code regarding user.information and remove the signals as well. You do not need signals to create Information instance because you have forms to do that.

You are getting double instance of user because of create_information signal.
user = form.save() in following code will save a User instance.
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
a_form =InformationForm(request.POST)
if form.is_valid() and a_form.is_valid():
# form.save() creates a user, and triggers create_information signal
user = form.save()
information = a_form.save()
Now, you have a signal create_information, which is triggered after a User instance is saved (this signal is a post_save singal).
Your user = form.save() will create a user, and will triggers create_information signal.
#receiver(post_save,sender=User)
def create_information(sender,instance,created,**kwargs):
if created:
Information.objects.create(user=instance)
This save another instance of Information, and since Information model has OneToOne mapping to User, another User instance is also saved.
Side note: You have three Information instances saved as well. One created by create_information signal, one by save_information signal, and third by a_form.save() method. This number can be more if cyclic signals are triggered, but not sure about that, so you'll have to check that by yourself.
Solution:
Firstly, get rid of all singals.
Secondly, add User to Information instance before saving it.
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
a_form =InformationForm(request.POST)
if form.is_valid() and a_form.is_valid():
user = form.save()
information = a_form.save(commit=False)
information.user = user
information.save()

Related

Model property displays default value for a field instead of actual value

I am a Django beginner and I started working on my first project. I implemented a model "extendedUser" with a medic_code field, extending User. It appears to be a problem when displaying the medic_code in a template. It doesn't display the actual property of the user, but the default value: "".
Template
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }} </p>
<p class="text-secondary">{{ user.medic_code }}</p> (empty string here)
</div>
</div>
<!-- FORM HERE -->
</div>
{% endblock content %}
models.py:
from django.db import models
from django.contrib.auth.models import User
class extendedUser(User):
medic_code = models.CharField(max_length=20, default='')
users/forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from users.models import extendedUser
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
medic_code = forms.CharField(max_length=20)
class Meta:
model = extendedUser
fields = ['username', 'email', 'medic_code', 'password1', 'password2']
views.py:
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
user = form.save()
#user.refresh_from_db()
user.medic_code = form.cleaned_data.get('medic_code')
user.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You are now able to log in! Your medic code {user.medic_code}') #correct value displayed here
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
#login_required
def profile(request):
user = request.user
return render(request, 'users/profile.html', {'user':user})
Also after I create a user and display the medic_code field in a Django shell for that user, the proper value is displayed. What may be problem?
Thanks!

How to pass request.user / user to message in Django

So I want to let a user message another user. I want the 'sender' field automatically to be 'request.user' and the receiver field to be the user whom the sender clicked on through their profile page. How would I go about passing those into the form?
matches.html
<div class="container">
<p>Username: {{ profile }}</p>
<h5>Your Matches:</h5>
{% for item in match %}
<br>
<p>Username: <br>{{ item.username}}</p>
<img src="{{ item.photo.url }}" width="300">
<p>Bio: <br>{{ item.description }}</p>
<br>
{% endfor %}
</div>
forms.py/InstantMessageForm
class InstantMessageForm(forms.ModelForm):
class Meta:
model = InstantMessage
fields = ('receiver','sender','message')
def save(self, commit=True):
user = super(InstantMessageForm, self).save(commit=False)
user.receiver = cleaned_data['receiver']
user.sender = cleaned_data['sender']
user.message = cleaned_data['message']
if commit:
user.save()
return user
views.py/instant_message
def instant_message(request):
if request.method == 'POST':
form = InstantMessageForm(request.POST)
if form.is_valid():
form.save()
return redirect('dating_app:home')
else:
form = InstantMessageForm()
context = {'form':form}
return render(request, 'dating_app/instant_message_form.html',context)
models.py
class InstantMessage(models.Model):
receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
message = models.TextField()
class InstantMessage(models.Model):
receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
message = models.TextField()
instant_message_form.py
{% extends "dating_app/base.html" %}
{% load bootstrap4 %}
{% block content %}
<h1>Start chatting now!</h1>
<div class='container'>
<form method="post" action="{% url 'dating_app:instant_message' %}" >
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
</div>
{% endblock content %}
You can create a form without the sender field:
class InstantMessageForm(forms.ModelForm):
class Meta:
model = InstantMessage
fields = ('receiver', 'message')
Then in the view, you can inject the request.user as the .sender of .instance wrapped in the form:
from django.contrib.auth.decorators import login_required
#login_required
def instant_message(request):
if request.method == 'POST':
form = InstantMessageForm(request.POST)
if form.is_valid():
form.instance.sender = request.user
form.save()
return redirect('dating_app:home')
else:
form = InstantMessageForm()
context = {'form':form}
return render(request, 'dating_app/instant_message_form.html',context)
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
In order to set the receiver, your url should for example contain the a primary key of the receiver. You can then remove the receiver from the form as well, and thus use:
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
#login_required
def instant_message(request, receiver_id):
if request.method == 'POST':
form = InstantMessageForm(request.POST)
if form.is_valid():
form.instance.sender = request.user
form.instance.receiver = get_object_or_404(get_user_mode(), pk=receiver_id)
form.save()
return redirect('dating_app:home')
else:
form = InstantMessageForm()
context = {'form':form}
return render(request, 'dating_app/instant_message_form.html',context)
You of course need then to alter the urls.py accordingly and the action url, such that it includes the primary key of the receiver.

cannot auto create profile when registered new user from link

Problem :
user's profile hasn't be created through "Sign Up" link(new user register) but able to created in only admin page.
view.py
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
def register_view(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created!!!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register_users.html', {'form': form})
#login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST,
request.FILES,
instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!!!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile_users.html',context)
model.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='abc.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(max_length=30)
class Meta:
model = User
fields = [
'username',
'email',
'password1',
'password2',
]
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField(max_length=30)
class Meta:
model = User
fields = [
'username',
'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
profile_users.html
{% extends 'postorder/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
  <form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile info!</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update!</button>
</div>
 </form>
</div>
{% endblock content %}
register_users.html
{% extends 'postorder/base_postorder.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">SUBMIT NOW!</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up!</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
ALready Have an Account? <a class="ml-2" href="{% url 'login' %}">Sign In!</a>
</small>
</div>
</div>
{% endblock content %}
app.py applied signal
What 's wrong with the code?
Apologize in advance for long code as newbie don't know where is the problem since different approach accumulated.
followed by this video : https://www.youtube.com/watch?v=q4jPR-M0TAQ&t=2292s&list=WL&index=6
Watch this
I think you need to remove form.save() and to ad this code (after if form.is_valid())
views.py
def register_view(request):
....
<your_field_from_registration> = form.cleaned_data.get('<your_field_from_registration>')
user = form.save(commit=False)
user.save()
profile = user.profile
....
profile.<your_field_from_registration> = <your_field_from_registration>
....
profile.save()
....
I had same problem and you have to create a function in apps.py in AppConfig class:
class AccountsConfig(AppConfig):
name = 'accounts'
# for signals.property
def ready(self):
import accounts.signals
Problem solved after adding this script in int.py file , never been thought its need to be edited .
Still helpful if someone can tell the reason.
# _int_.py
default_app_config = 'users.apps.UsersConfig'

Custom django user registration

I am doing a user registration function, this is views
from django.http import HttpResponseGone
from .forms import RegisterForms
from django.shortcuts import render
def register(request):
if request.method == 'POST':
user_forms = RegisterForms(request.POST)
if user_forms.is_valid():
new_userform = user_forms.save(commit=False)
new_userform.set_password(user_forms.cleaned_data['password'])
new_userform.save()
return HttpResponseGone('注册成功')
else:
return HttpResponseGone('注册失败')
else:
user_forms = RegisterForms()
return render(request,'account/register.html',{'form':user_forms})
this is forms
from django import forms
from django.contrib.auth.models import User
class RegisterForms(forms.ModelForm):
password = forms.CharField(label='Password',widget=forms.PasswordInput)
password2 = forms.CharField(label='password again',widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username','email')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('密码输入不一致,请从新输入')
else:
return cd['password']
this is html
<p>欢迎注册</p>
<form action="." method="post">
{% csrf_token %}
<p>username {{ form.username }}</p>
<p>email {{ form.email }}</p>
<p>password {{ form.password }}</p>
<p>password again {{ form.password2 }}</p>
<input type="submit" value="register">
</form>
I found that if I change the name of the clean_password2 method in the views file to clean_password, I can not get the value of password2 in the form
This is the wrong message[enter image description here][4]
My English is not very good I hope someone can help me Thank Thank Thank
from django import forms
from django.contrib.auth.models import User
class RegisterForms(forms.ModelForm):
password = forms.CharField(label='Password',widget=forms.PasswordInput)
password2 = forms.CharField(label='password again',widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username','email','password','password2')
def clean(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('密码输入不一致,请从新输入')
else:
return cd
In short use clean method in such conditions.

Can't get data in edit form

I'm trying to create an edit form for existing users, I have the User model and I associated to it a profile.
The problem is that the fields of profile are empty in the rendered html, however when I created a new user I filled these fields, and when I enter to administration I find the fields are filled.
models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
DEPARTMENT_CHOICES = (('MI', 'Math et info'),
('ST', 'Science et Tech'),
('SM', 'Science de la matiere'))
user = models.OneToOneField(User, on_delete=models.CASCADE)
teacher = models.BooleanField(default=False)
description = models.TextField(blank=True)
department = models.CharField(max_length=35, choices=DEPARTMENT_CHOICES, blank=True)
picture = models.ImageField(upload_to='profile-images', blank=True)
def __str__(self):
return self.user.username
views.py
def profile_view(request):
if request.method == 'POST':
user_form = EditUserForm(request.POST, instance=request.user)
ins = Profile.objects.get(pk=5)
profile_form = EditProfileForm(request.POST, request.FILES, instance=ins)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
return redirect(home)
else:
user_form = EditUserForm(instance=request.user)
profile_form = EditProfileForm(request.FILES, instance=request.user)
return render(request, 'account/profile.html', {'user_form': user_form,
'profile_form': profile_form})
forms.py
class EditProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('description', 'department', 'picture', )
class EditUserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'email', )
profile.html
{% extends 'manhal/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="col-md-6">
<form method="post" enctype="multipart/form-data" action="{% url 'profile' %}" class="form-horizontal">{% csrf_token %}
<fieldset>
<legend>User Profile</legend>
{{ user_form|crispy }}
{{ profile_form|crispy}}
<input type="submit" value="Save" class="btn btn-primary">
</fieldset>
</form>
</div>
{% endblock %}
First, your if/else block is checking if the request is a POST. Since the else block is not a POST, you do not want to pass any POST data into your form. This will make the form think it's bound with no data.
Also, it looks like you are passing the request.user to your ProfileForm as the instance, but the model on the ProfileForm meta class is expecting a Profile object.
Can you fix those two things and see if it works or not? If it doesn't work, please post some more code (like your templates).