Display user data in template - python

I'm new in Django. I want to display in templates
user's information where he connect, but when I change page, data disappears!
views.py:
def login(request):
if request.method == "POST":
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = authenticate(username=username, password=password)
data = {}
data['user'] = user
if user is not None:
if user.is_authenticated:
return redirect(accueil)
else:
messages.error(request, 'Compte inactif.')
else:
messages.error(request, 'Identifiant et/ou mot de passe invalide.')
return render(request, 'login.html')
Models.py:
class AbstractCustomerUser(AbstractBaseUser):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
Username, password and email are required. Other fields are optional.
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, digits and '
'#/./+/-/_ only.'),
validators=[
validators.RegexValidator(r'^[\w.#+-]+$', _('Enter a valid username.'), 'invalid')
])
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('email address'), blank=True, unique=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
company = models.ForeignKey(Customer)
referent_for_customers = models.ManyToManyField('Customer',
related_name='referents',
verbose_name="est référent pour")
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['id', 'company']
class Meta:
# For an unknown reason, fails to save a modified object with this
# constaint. Comment it for now:
#unique_together = ('username', 'company')
verbose_name = _('utilisateur')
abstract = True
class CustomerUser(AbstractCustomerUser):
class Meta(AbstractCustomerUser.Meta):
db_table = 'customers_customeruser'
swappable = 'AUTH_USER_MODEL'
verbose_name = 'utilisateur portail'
templates:
<div id="header">
<h2>Portail Client</h2>
Bienvenue {{ user.username }}
CustomerUser table info: {{ user.company_id }}, {{ user.last_login }}
Customer table info: {{ user.company.name }}
Modifier mot de passe
Déconnexion
</div>

user is automatically provided to the template via the context processor. But these only run if you are using a RequestContext when rendering your template: either by specifically passing it in (eg with the context_instance parameter to render_to_response), or by using the newer render shortcut.
So in all your other views, you need to be sure you are doing:
return render(request, 'your_template.html', params)

in your views.py you should use RequestContext
from django.template import RequestContext
from django.shortcuts import render_to_response
def login(request):
args={}
...
return render_to_response('login.html', args, context_instance=RequestContext(request))

Looks like the user object is not available inside your template. If the user object is not available in the template, nothing will be displayed when the template evaluates {{ user.username }}
From the docs -
If you use a variable that doesn’t exist, the template system will
insert the value of the TEMPLATE_STRING_IF_INVALID setting, which is
set to '' (the empty string) by default.
You can pass the user object to the template by modifying the appropriate view which returns the welcome template, using either render() which forces the use of a RequestContext implicitly or render_to_response() where you have to explicitly pass a RequestContext instance

Related

Keeping user logged in after changing password (Django) custom user model

I have a customized Django model. My problem is whenever I update any of the user profile information, it logged out. I know that Django logged out the user after changing their password and I have to use update_session_auth_hash() function. However, in my case it didn't work and I don't want to use Django changePasswordForm because I want the user to be able to change all his information in one form. Any help will be appreciated.
This is my custom user model:
class MyUser(AbstractBaseUser):
firstName = models.CharField(max_length=100, validators =[firstnameCheck] )
lastName = models.CharField(max_length=100, validators =[lastnameCheck] )
#nationalID = models.IntegerField(unique=True)
nationalID = models.CharField(max_length=10, validators=[RegexValidator(r'^[0-9]{10}$')], unique=True)
GENDER_CHOICES = [('male', 'Male'), ('female', 'Female')]
gender = models.CharField(choices=GENDER_CHOICES, max_length=10)
dateofbirth = models.DateField(auto_now=False, auto_now_add=False)
email = models.EmailField(max_length=100, unique=True)
password = models.CharField(max_length=100)
password_confirm = models.CharField(max_length=100, default='')
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email' #enable authentication by using email instead of default 'username'
REQUIRED_FIELDS = ['firstName', 'lastName', 'nationalID','gender','dateofbirth','password','password_confirm']
objects = MyUserManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self,app_label):
return True
This is my view
def update_admin(request,id):
context = {}
if request.method == "POST":
pi = MyUser.objects.get(pk=id)
fm = UserRegisterationForm(request.POST,instance=pi)
if fm.is_valid():
request.user.set_password(fm.cleaned_data['password1'])
fm.save()
update_session_auth_hash(request, request.user)
messages.add_message(request, messages.INFO, 'The profile updated successfully.')
context['form'] = fm
else:
pi = MyUser.objects.get(pk=id)
fm = UserRegisterationForm(instance=pi)
context['form'] = fm
return render(request,'project/update_admin.html', context)
The problem is that the change of the password will make the session invalid.
See doc
You could also heredity the django change password form for your own form.
You could do something like this.
Template:
<form method="POST" class="contact-form" action="{% url 'change-password' %}"> ##make sure the action links to the `changepassword` view
{% csrf_token %}
<input type="password" name="password" required id="password" pattern="^[a-zA-Z0-9]{6,}$">
</div>
<button type="submit">Submit</button>
</form>
Views.py:
def changepassword(request):
user = request.user
if 'password' in request.POST:
user.set_password(request.POST['password'])
return render(request, 'project/changepassword.html')
This will keep your user logged in after the password change, but you will need to add validation handling & error handling to this to make it a viable solution.

Django-allauth - Custom Sign Up with OneToOneField

I created a sign up form using two grouped forms and it has been working perfectly, but I would like to use django-allauth because of the features (login only with e-mail, sending confirmation e-mail ...).
However even reading some topics I still couldn't.
forms.py
class ExtendedUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True, label="E-mail")
first_name = forms.CharField(max_length=30, label="Nome")
last_name = forms.CharField(max_length=30, label="Sobrenome")
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('sexo', 'data_nascimento', 'foto', 'sobre_mim', 'telefone', 'paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram')
CIDADES = []
for i in cidadesReader:
if i[1] not in CIDADES:
CIDADES.append(i[1])
widgets = {
'cidade': floppyforms.widgets.Input(datalist=CIDADES, attrs={'autocomplete': 'off'}),
}
views.py
def signup(request):
if request.method == 'POST':
form = ExtendedUserCreationForm(request.POST)
profile_form = UserProfileForm(request.POST, request.FILES)
if form.is_valid() and profile_form.is_valid():
user = form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
#login(request, user)
return redirect('home')
else:
form = ExtendedUserCreationForm()
profile_form = UserProfileForm()
context = {'form': form, 'profile_form' : profile_form}
return render(request, 'registration/signup.html', context)
signup.html
{% extends '_base.html' %}
{% load crispy_forms_tags %}
{% block title %}Cadastrar{% endblock title %}
{% block content %}
<h2>Criar Perfil</h2>
<form novalidate method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
{{ profile_form|crispy }}
<button class="btn btn-success" type="submit">Cadastrar</button>
</form>
{% endblock content %}
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
SEXOS = (
('M', 'Masculino'),
('F', 'Feminino'),
)
sexo = models.CharField(max_length=1, choices=SEXOS)
data_nascimento = models.DateField(validators=[idade_minima])
...
I've tried using the ACCOUNT_SIGNUP_FORM_CLASS and ACCOUNT_FORMS options in settings.py, but it didn't work.
I tried to make some adjustments, as in this topic similar to my question:
Django allauth saving custom user profile fields with signup form
For example, I changed it in models.py and I did migrate:
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name ='profile')
After several attempts, the most common error is:
RelatedObjectDoesNotExist at /accounts/signup/
User has no profile.
Edit:
I changed my slug in UserProfile, because it depends from user (first name). The error changed:
IntegrityError at /accounts/signup/
NOT NULL constraint failed: profiles_userprofile.user_id
But UserProfile has no user continues in the final.
(Using in settings.py: ACCOUNT_SIGNUP_FORM_CLASS = 'profiles.forms.UserProfileForm'. Details from traceback:
...lib/python3.6/site-packages/allauth/account/views.py in dispatch
215 return super(SignupView, self).dispatch(request, *args, **kwargs)
.../lib/python3.6/site-packages/allauth/account/views.py in post
104 response = self.form_valid(form)
...lib/python3.6/site-packages/allauth/account/views.py in form_valid
231 self.user = form.save(self.request)
...lib/python3.6/site-packages/allauth/account/forms.py in save
405 self.custom_signup(request, user)
...lib/python3.6/site-packages/allauth/account/forms.py in custom_signup
359 custom_form.save(user)
...profiles/models.py in save
super(UserProfile, self).save(*args, **kwargs)
▼ Local vars
Variable Value
__class__
<class 'profiles.models.UserProfile'>
args ()
kwargs {}
self Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user.
slug_name 'nome-sp-260221205510'
Signals
Using signals the error changed. I added it in models.py:
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
Error:
ValueError at /accounts/signup/
The 'foto' attribute has no file associated with it.
Then I tried remove foto field, but the other error happens in another field:
IntegrityError at /accounts/signup/
NOT NULL constraint failed: profiles_userprofile.data_nascimento
Thanks in advance for any help.
The error UserProfile has no user is triggered in UserProfile.save(). You are calling this the first time in your view with commit=False and only afterwards are you setting the user:
# your code from the question
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
I'm guessing that UserProfile.save reads the the user field to create the slug. You could either skip it if commit=False, or maybe it will already work if you change it like this:
profile_form.instance.user = user
profile.save()
Another common solution is, to provide the user when initializing the form, but then you would have to change your current view code quit a bit.
I achieved! No need to use signals. Here are the changes:
forms.py
I needed to use a single class:
class SignupForm(forms.ModelForm):
first_name = forms.CharField(max_length=30, label="Nome")
last_name = forms.CharField(max_length=30, label="Sobrenome")
class Meta:
model = UserProfile
fields = ('sexo', 'data_nascimento', 'foto', 'sobre_mim','telefone','paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram')
CIDADES = []
for i in cidadesReader:
if i[1] not in CIDADES:
CIDADES.append(i[1])
widgets = {
'cidade': floppyforms.widgets.Input(datalist=CIDADES, attrs={'autocomplete': 'off'}),
}
field_order = ['first_name', 'last_name', 'email', 'password1', 'password2',
'sexo', 'data_nascimento', 'foto', 'sobre_mim','telefone','paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram']
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
profile, created = models.UserProfile.objects.get_or_create(user=user)
profile.sexo = self.cleaned_data['sexo']
profile.data_nascimento = self.cleaned_data['data_nascimento']
def compressImage(foto):
...
return foto
profile.foto = compressImage (self.cleaned_data['foto'])
profile.sobre_mim = self.cleaned_data['sobre_mim']
profile.telefone = self.cleaned_data['telefone']
profile.paroquia = self.cleaned_data['paroquia']
profile.cidade = self.cleaned_data['cidade']
profile.estado = self.cleaned_data['estado']
profile.cep = self.cleaned_data['cep']
profile.possui_filhos = self.cleaned_data['possui_filhos']
profile.facebook = self.cleaned_data['facebook']
profile.instagram = self.cleaned_data['instagram']
user.save()
profile.save()
Note:
I was using a function to compress images, in models.py.
To correct the error
ValueError at /accounts/signup/
The 'foto' attribute has no file associated with it
I had to bring it to forms.py
settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'profiles.forms.SignupForm'
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name ='profile')
SEXOS = (
('M', 'Masculino'),
('F', 'Feminino'),
)
sexo = models.CharField(max_length=1, choices=SEXOS)
...
Note:
It was necessary to test field by field.
Sometimes there were some errors like NOT NULL constraint failed ou no such table.
The solutions to these problems:
Add null=True in the field (temporarily)
makemigrations and migrate
Delete migrations
signup.html
Only {{ form|crispy }} is necessary (I could delete {{ profile_form|crispy }})
<form novalidate method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-success" type="submit">Cadastrar</button>
</form>
Thank you for your help, #Risadinha.

Django Profile model not showing first_name and last_name fields in sign up form

I created a Profile model with Django. The profile inherits from a CustomUser class which I wrote by inheriting AbstractBaseUser. However, when I go to the sign up page, even though first_name and last_name are required in the Custom User class, it doesn't show. It only shows the fields of the profile model, and email and password. I am using Django all auth.
How do I make the required fields of the custom user (and other fields I want e.g middle_name) and the fields of the profile all show up in the same form, and still save both the custom user model, and the profile model in the database all at the same time?
models.py
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
USER_TYPE_CHOICES = (
(1, 'student'),
(2, 'department'),
(3, 'admin'),
)
first_name = models.CharField(max_length=70, blank=False, default="")
middle_name = models.CharField(max_length=70, blank=False, default="")
last_name = models.CharField(max_length=70, blank=False, default="")
is_active = models.BooleanField(default=True)
user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
is_staff = models.BooleanField(default=False) # a admin user; non super-user
is_superuser = models.BooleanField(default=False) # a superuser
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name'] # Email & Password are required by default.
objects = UserManager()
# I left out some unimportant code
class StudentUser(models.Model):
# This is the model class for students
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
matric_number = models.CharField(max_length=11, blank=False)
department = models.CharField(max_length=40, blank=False)
views.py:
from users.forms import StudentUserSignupForm
from allauth.account.views import SignupView
class StudentUserSignupView(SignupView):
# The referenced HTML content can be copied from the signup.html
# in the django-allauth template folder
template_name = 'account/signup.html'
# the previously created form class
form_class = StudentUserSignupForm
forms.py:
class UserCreationForm(forms.ModelForm):
"""
A form for creating new users. Includes all the required
fields, plus a repeated password.
"""
class Meta:
model = User
fields = ('email', 'first_name', 'last_name')
def save(self, commit=True):
user = super(UserChangeForm, self).save(commit=False)
# Save the provided password in hashed format
if self.cleaned_data.get("password1"):
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
# I removed some unimportant code
class StudentUserSignupForm(SignupForm):
first_name = forms.CharField(max_length=70)
middle_name = forms.CharField(max_length=70, required=False)
last_name = forms.CharField(max_length=70)
matric_no = forms.CharField(min_length=10, max_length=11)
department = forms.CharField(max_length=40)
def save(self, request):
# Save the User instance and get a reference to it
user_form = super(StudentUserSignupForm, self).save(request)
# user_form.user_type = 1 To correct
student_user = StudentUser(
user=user_form,
matric_no=self.cleaned_data.get('matric_number'),
department=self.cleaned_data.get('department')
)
student_user.save()
return student_user.user
html template
<div class="row justify-content-center align-items-center">
<div class="col-auto m-auto">
<div class="jumbotron mt-4">
<h3>Sign Up</h3>
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field|add_class:"form-control-sm"|as_crispy_field }}
{% endfor %}
<button class="btn btn-sm btn-primary" type="submit">Sign Up</button>
</form>
</div>
</div>
You see that in the image above, it shows email, password, and department, but it does not show first_name, last_name, middle_name etc. How do I make the required and non required fields of the User model show up in the form and still save both models? Does the issue have anything to do with django-allauth?

Django - Form not showing up on template only the button

I've been trying everything, but I can't figure out why it's not showing-up. I searched everywhere on this site with no luck. The button shows up but when I click than it give me a TypeError at get_profile, saying:
Exception Value:
get_profile() got an unexpected keyword argument 'username'
Here's my code:
models.py
class CustomUser(AbstractBaseUser):
email = models.EmailField('email address', unique=True, db_index=True)
username = models.CharField('username', max_length=50, unique=True, db_index=True)
first_name = models.CharField(max_length=50, blank=False)
last_name = models.CharField(max_length=50, blank=False)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __unicode__(self):
return self.username
forms.py
from django import forms
from apps.accounts.models import CustomUser
class RegistrationForm(forms.ModelForm):
email = forms.EmailField(widget=forms.TextInput, label='email')
username = forms.CharField(widget=forms.TextInput, label='username')
password1 = forms.CharField(widget=forms.PasswordInput, label='Enter your password')
password2 = forms.CharField(widget=forms.PasswordInput, label='Re-type your password')
first_name = forms.CharField(widget=forms.TextInput, label='First Name')
last_name = forms.CharField(widget=forms.TextInput, label='Last Name')
class Meta:
model = CustomUser
fields = ['email', 'username', 'password1', 'password2', 'first_name', 'last_name']
def clean(self, password1, password2):
cleaned_data = super(RegistrationForm, self).clean()
if password1 in self.cleaned_data and password2 in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("Passwords don't match. Please enter both fields again")
return self.cleaned_data
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
views.py
def register(request):
"""
User Registration View
"""
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
CustomUser = form.save()
CustomUser.save()
return redirect('home.html')
else:
form = RegistrationForm()
return render_to_response('register.html', {
'form': form,
}, context_instance=RequestContext(request))
def get_profile(request):
username = CustomUser.username
return render_to_response(request, 'profile.html', {'username': username})
urls.py
urlpatterns = patterns ('',
url(r'register$', 'apps.accounts.views.register', name='register'),)
register.html
{% load staticfiles %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<body>
{% block body %}
<form method='POST' action="register" enctype= 'multipart/form-data'>{% csrf_token %}
<table>{{ form.ast_table}}</table>
<input type='submit' class="btn btn-default" value="Register" />
</form>
{% endblock %}
</body>
</html>
It seems that you don't have the right signature for the get_profile view function.
You should check your urls, you probably have something like
url(r'^profile/(?P<username>\w+/$', get_profile),
If so, your view should be
def get_profile(request, username):
#you can get the user
user = CustomUser.objects.get(username=username)
return render_to_response(request, 'profile.html', {'username': username, 'user': user})
CustomUser is the class. You need to fetch an instance before you can actually fetch its username.
Eg:
CustomUser.objects.get(pk=1).username
Gives you the username of the first user.
Also, its supposed to be {{form.as_table}} not ast_table

NOT NULL constraint failed error

I keep getting this error: "NOT NULL constraint failed: users_userprofile.user_id" when I try to submit a form
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
#Esta linea es requerira. Linkea UserProfile a un User model
user = models.OneToOneField(User)
#atributos adicionales
about_me = models.TextField(max_length=100,default='',blank=True)
experience = models.TextField(max_length=250,default='',blank=True)
offers = models.TextField(max_length=110,default='',blank=True)
This is the forms.py:
from django import forms
from users.models import UserProfile
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
password = forms.CharField(min_length=6,label='', widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':'true','class':"form-control"}))
username = forms.CharField(label='', min_length=6,
widget=forms.TextInput(attrs={'placeholder': 'Username','required':'true','class':"form-control",'autofocus':'true'}))
email = forms.CharField(label='',
widget=forms.TextInput(attrs={'placeholder': 'Email','required':'true','class':"form-control"}))
class Meta:
model = User
fields = ('username', 'email', 'password')
class UserProfileForm(forms.ModelForm):
about_me = forms.CharField(label='',
widget=forms.Textarea(attrs={'placeholder': 'Sobre mi','required':'true','class':"form-control"}))
first_name = forms.CharField(label='',
widget=forms.TextInput(attrs={'placeholder': 'Nombre','required':'true','class':"form-control"}))
last_name = forms.CharField(label='',
widget=forms.TextInput(attrs={'placeholder': 'Apellidos','required':'true','class':"form-control"}))
experience = forms.CharField(label='',
widget=forms.TextInput(attrs={'placeholder': 'Experiencia','required':'true','class':"form-control"}))
offers = forms.CharField(label='',
widget=forms.Textarea(attrs={'placeholder': 'Mensaje','required':'true','class':"form-control"}))
class Meta:
model = UserProfile
fields =('first_name','last_name','about_me','experience','offers')
This is the template:
{%extends 'base.html'%}
{%block content%}
{% if user.is_authenticated %}
<h1>Edita tu perfil</h1>
<form id='profile' method='post' action='/edit_profile/'>
{% csrf_token %}
{{profile.as_p}}
<button type='submit'>Editar</button>
</form>
{%endif%}
{%endblock%}
Thanks before hand
EDIT:
The error was in the views.py I needed to add an instance to the form, like this:
form = UserProfileForm(data=request.POST, instance=profile)
This is my complete views.py:
def edit_profile(request):
try:
profile = request.user.userprofile
except UserProfile.DoesNotExist:
profile = UserProfile(user=request.user)
if request.method == 'POST':
form = UserProfileForm(data=request.POST, instance=profile)
if form.is_valid():
form.save()
return HttpResponse("Exito!")
else:
form = UserProfileForm(instance=profile)
else:
form = UserProfileForm()
return render(request,
'editprof.html',
{ 'form': form})
Problem is that user in UserProfile is required, but you are not setting user field in UserProfileForm. The database didn't get user_id, so it tried to set null on this field, but the field had not a null constraint. You can set null=True on field definition in UserProfile model, or overwrite save (or probably is_valid) form method to set user automatically or add user field to UserProfileForm, or whatever you want.
In your model give a null
user = models.OneToOneField(User, null=True)
about_me = models.TextField(max_length=100,default='',blank=True, null=True)
experience = models.TextField(max_length=250,default='',blank=True, null=True)
offers = models.TextField(max_length=110,default='',blank=True, null=True)

Categories