Avoid access to other pages via URL, if not logged on (Django) - python

Team, I have used Django Authentication models which is validating the login to the my blog, but it still permits users to access other restricted pages through url, I need to avoid this, please help on that. Please add maximum details as you can, I am struggling a lot with that
Models:
from django.db import models
from django.db.models import permalink
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
datposted = models.DateTimeField('date posted')
category = models.ForeignKey('Category')
owner = models.ForeignKey('UserProfile')
def __str__(self):
return '%s' % self.title
class Category(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', null=True)
def __unicode__(self):
return self.user.username
class Logout(User):
force_logout_date = models.DateTimeField(null=True, blank=True)
Views:
def index(request):
template = "index.html"
return render(request,template)
def menu(request):
return render(request,"menu.html")
def view_posts(request):
return render_to_response('posts.html',{'posts':Post.objects.all()})
def view_post(request, post_id=1):
return render_to_response('view_post.html',{'post':Post.objects.get(id=post_id)})
def view_by_year(request):
cur_year=timezone.now().year
posts_cur_year = Post.objects.filter(datposted__year=cur_year)
return render_to_response('view_by_year.html',{'posts_cur_year':posts_cur_year})
def view_by_month(request):
cur_month=timezone.now().month
posts_cur_month = Post.objects.filter(datposted__month=cur_month)
return render_to_response('view_by_month.html',{'posts_cur_month':posts_cur_month, 'cur_month':cur_month})
def view_by_owner(request):
user = request.user
posts_owner = Post.objects.filter(owner__user=request.user)
return render_to_response('view_by_owner.html',{'view_owner':posts_owner})
def register(request):
# Like before, get the request's context.
context = RequestContext(request)
# A boolean value for telling the template whether the registration was successful.
# Set to False initially. Code changes value to True when registration succeeds.
registered = False
if request.method == 'POST':
# Attempt to grab information from the raw form information.
# Note that we make use of both UserForm and UserProfileForm.
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
# If the two forms are valid...
if user_form.is_valid() and profile_form.is_valid():
# Save the user's form data to the database.
user = user_form.save()
# Now we hash the password with the set_password method.
# Once hashed, we can update the user object.
user.set_password(user.password)
user.save()
# Now sort out the UserProfile instance.
# Since we need to set the user attribute ourselves, we set commit=False.
# This delays saving the model until we're ready to avoid integrity problems.
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else:
user_form = UserForm()
profile_form = UserProfileForm()
# Render the template depending on the context.
return render_to_response(
'register.html',
{'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
context)
def user_login(request):
# Like before, obtain the context for the user's request.
context = RequestContext(request)
# If the request is a HTTP POST, try to pull out the relevant information.
if request.method == 'POST':
# Gather the username and password provided by the user.
# This information is obtained from the login form.
username = request.POST['username']
password = request.POST['password']
# Use Django's machinery to attempt to see if the username/password
# combination is valid - a User object is returned if it is.
user = authenticate(username=username, password=password)
# If we have a User object, the details are correct.
# If None (Python's way of representing the absence of a value), no user
# with matching credentials was found.
if user:
# Is the account active? It could have been disabled.
if user.is_active:
# If the account is valid and active, we can log the user in.
# We'll send the user back to the homepage.
login(request, user)
return HttpResponseRedirect('/menu/')
else:
# An inactive account was used - no logging in!
return HttpResponse("Sua conta nao esta ativa.")
else:
# Bad login details were provided. So we can't log the user in.
print "Credenciais Incorretas: {0}, {1}".format(username, password)
return HttpResponse("Login invalido.")
# The request is not a HTTP POST, so display the login form.
# This scenario would most likely be a HTTP GET.
else:
# No context variables to pass to the template system, hence the
# blank dictionary object...
return render_to_response('login.html', {}, context)
def create_post(request):
if request.method == 'POST':
form = CreatePostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.datposted = datetime.datetime.now()
#post.owner = request.user()
post.save()
return HttpResponseRedirect('/posts/')
else:
return HttpResponse("Favor. Verifique os campos necessarios")
else:
form = CreatePostForm()
f = {'form' : form}
return render(request,'create_post.html',f)
def logout(request):
auth.logout(request)
return render_to_response('logout.html')

You can use the #login_required decorator above each view that you want to protect:
#login_required
def index(request):
template = "index.html"
return render(request,template)
This will ensure that the user has logged in before allowing them access to each view that utilizes this decorator.
See the Documentation for more information.

Related

How Can I check if logged in user profile information is updated in django models

I am working on a project in Django where I have a Profile Model with a Foreign Key field (OneToOne Relationship with User Model) called applicant and a status field which is set to 'Update' at default. Other fields like surname and othernames are also included in the Profile Model.
class Profile(models.Model):
applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
surname = models.CharField(max_length=10, null=True)
othernames = models.CharField(max_length=30, null=True)
status = models.CharField(max_length=30, default='Update', null=True)
def save(self, *args, **kwargs):
self.profilestatus = 'Updated'
super().save(*args, **kwargs)
def __str__(self):
return f'{self.applicant.username}-Profile'
I want the system to check every logged in user if their profile information are not Updated, they should be redirected to the Profile Update page to update their profile first else they should be redirected to view their updated profile.
def index(request):
user = request.user.is_authenticated
if request.user.is_authenticated and Profile.objects.get(applicant=user, status= 'Update'):
return redirect('user-profile-update')
else:
return redirect('user-profile')
context = {
'check_profile_update':check_profile_update,
}
return render(request, 'dashboard/index.html', context)
I have ModelForm with a save method with automatically updates the satus field in Profile Model to Updated any time a user updates his or her profile information.
The issue is anytime I run the app error says 'Profile matching query does not exist.'
Someone should kindly help me on the best way of solving this issue.
In fact, how can I create an instance of the logged in user so I can check the user profile update status in model?
Thanks
The Problem:
user = request.user.is_authenticated makes the variable user = True, so when you use it in
if request.user.is_authenticated and Profile.objects.get(applicant=user, status= 'Update'):,
you are really doing the following:
if request.user.is_authenticated and Profile.objects.get(applicant=True, status= 'Update'):
So of course there will be no matches since no applicant equals True.
The Solution
Change the two lines to:
user = request.user # Now user equals the actual user
if user.is_authenticated and Profile.objects.get(applicant=user, status= 'Update'):
On another note:
I hesitate to use a get query without putting it in a try/except statement so that you can handle what should happen if a Profile is not found:
user = request.user # Now user equals the actual user
if user.is_authenticated:
try:
profile = Profile.objects.get(applicant=user, status= 'Update')
except Profile.DoesNotExist:
# Code to handle what happens if a Profile is NOT found
# Maybe redirect to a page not found
# or maybe redirect to a page to create an applicant?
EDIT
def index(request):
user = request.user
if user.is_authenticated:
try:
profile = Profile.objects.get(applicant=user)
except Profile.DoesNotExist:
print("Profile Does Not Exist")
# Redirect to a Profile creating page?
else:
if profile.status == 'Update':
return redirect('user-profile-update')
else:
return redirect('user-profile')
context = {
'check_profile_update':check_profile_update,
}
return render(request, 'dashboard/index.html', context)
Edit 2
As per your comment, the final working version is then:
def index(request):
user = request.user
if user.is_authenticated:
try:
profile = Profile.objects.get(applicant=user)
except Profile.DoesNotExist:
print("Profile Does Not Exist")
# Redirect to a Profile creating page?
else:
if profile.surname == None:
return redirect('user-profile-update')
else:
return redirect('user-profile')
context = {
'check_profile_update':check_profile_update,
}
return render(request, 'dashboard/index.html', context)

How can I connect the user to a post he created in Django

I am starting with Django, and I have a question about the connection between a post and the user who created it. For now, I managed to create the link, however, whenever I create a new post, the user id is always the default one, thus one. I want to make it in a way that the user id is the id of the person creating the post, and for some reason, it never works. The other option I tried is to put "user" into the form but the problem is that then the user can choose which user he is, which is risky. So is there any way to make it automatic? That when the post is created, the right user id is directly connected to it? Thank you for any help!!
model.py
"""
class Post(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE, default=1)
image = models.ImageField(default="man.jpg")
titre = models.CharField(max_length=50)
slug = models.SlugField(max_length=100)
date_publication = models.DateTimeField(auto_now_add=True)
"""
view.py
"""
#login_required
def post_create(request):
if request.method == "POST":
post_form = PostForm(request.POST)
if post_form.is_valid():
post_form.save()
messages.success(request, 'Your post was successfully created!')
return redirect('seed:view_seed')
else:
messages.error(request, 'Please correct the error below.')
else:
post_form = PostForm(request.POST)
return render(request, "post/create.html", context={"post_form": post_form})
"""
forms.py
"""
class PostForm(ModelForm):
class Meta:
model = Post
fields = ["user", "image", "titre", "slug"]
"""
You remove the user field from the fields in the form:
class PostForm(ModelForm):
class Meta:
model = Post
# no user ↓
fields = ['image', 'titre', 'slug']
and in the view you add the logged in user to the instance wrapped in the form:
#login_required
def post_create(request):
if request.method == 'POST':
post_form = PostForm(request.POST)
if post_form.is_valid():
# add user to the instance ↓
post_form.instance.user = request.user
post_form.save()
messages.success(request, 'Your post was successfully created!')
return redirect('seed:view_seed')
else:
messages.error(request, 'Please correct the error below.')
else:
post_form = PostForm()
return render(request, "post/create.html", context={"post_form": post_form})
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

RelatedObjectDoesNotExist for a model with foreginkey with standard user model

I have this issue :RelatedObjectDoesNotExist
I add a UserProfile to my models (for now there is only avatar to be added to User Model.
It is not mandatory to add a picture. So some userProfile are null. The proble is when I edit Userform and ProfileUserform. I had an error :
RelatedObjectDoesNotExist at /accounts/user_edit/
User has no profile.
I try to add a try: except in views but seems not working
Models.Py:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') # il s'agit d'ajouter des infos au modele User
# add any additional attributes needed
avatar = models.ImageField(upload_to='profile_pics', blank=True) # avatar of the user in director profile_pics
def __str__(self):
return self.user.email
Views.py:
#login_required(login_url='account/sign_up.html')
def user_edit(request):
# Get info from "both" forms
# It appears as one form to the user on the .html page
user_form = UserFormEdit(instance=request.user)
profile_form = UserProfileForm(instance=request.user.profile)
# Check to see both forms are valid
if user_form.is_valid() and profile_form.is_valid():
# Prepare Save User Form to Database
user = user_form.save()
profile = profile_form.save(commit=False)
# Check if they provided a profile picture
if 'profile_pic' in request.FILES:
print('found it')
# If yes, then grab it from the POST form reply
profile.profile_pic = request.FILES['profile_pic']
profile.save()
messages.success(request, 'User updated')
return render(request, 'account/user_edit.html',
{'user_form': user_form,
'profile_form': profile_form}
)
Error is on profile_form = UserProfileForm(instance=request.user.profile)
because request is null....
I would like to have possibility to add or edit UserProfile info after creation of User. So it should render a empty UserProfileForm if it does not already exists or instance user.profile data if exists
thanks for helping
You can check out the profile exists, and if not use a new instance.
try:
profile = request.user.profile
except UserProfile.DoesNotExist:
profile = UserProfile(user=request.user)
profile_form = UserProfileForm(instance=profile)
The fact that you have a RelatedObjectDoesNotExist error originates from the fact that a user does not per se has a related Profile. So request.user.profile can fail.
You can fetch the Profile if it exists with .filter(..).first():
#login_required(login_url='account/sign_up.html')
def user_edit(request):
user = request.user
profile = Profile.objects.filter(user=user).first()
if request.method == 'POST':
user_form = UserFormEdit(request.POST, request.FILES, instance=request.user)
profile_form = UserProfileForm(request.POST, request.FILES, instance=profile)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.instance.user = user
profile = profile_form.save()
messages.success(request, 'User updated')
return redirect('some_view')
else:
user_form = UserFormEdit(instance=user)
profile_form = UserProfileForm(instance=profile)
return render(
request,
'account/user_edit.html',
{'user_form': user_form, 'profile_form': profile_form}
)
Furthermore a form can handle files as well, and I advice you to let the form handle the work, since it will usually be less error-prone, perform proper validations, and remove a lot of boilerplate code.
While it is completely fine to have two related models with an object existing only in one, in this case, it might be better to always have a profile even if it is empty. I would suggest creating a user profile on user create.
Anyways if you want to continue with the existing code, a simple way to handle creating a UserProfile on edit would be to do something like the below, in your view
try:
profile = request.user.profile
except RelatedObjectDoesNotExist: # I feel it should actually throw AttributeError here
profile = UserProfile(user=request.user) # this is a dummy profile and won't be save until the form is saved
profile_form = UserProfileForm(instance=profile)
If you do want to create a profile on creation of users, you can add it to the save of the form or model.
# in form
def save(self, *args, **kwargs):
is_create = self.instance.pk is None
return_value = super().save(*args, **kwargs)
if is_create:
UserProfile.objects.create(user=self.instance)
return return_value
# or in user model
def save(self, *args, **kwargs):
is_create = self.pk is None
super().save(*args, **kwargs)
if is_create:
UserProfile.objects.create(user=self)
return self
# or in the view
def create(request):
...
if form.is_valid():
user = form.save()
UserProfile.objects.create(user=self)
...

Django request.user becomes anonymous after changing page. Using custom user model

I'm using a custom user model that extends AbstractBaseUser. This is the user model:
class cUser(AbstractBaseUser):
def save(self, *args, **kwargs):
pass
role_id = models.IntegerField()
user_id = models.IntegerField()
email = models.CharField(max_length=40)
password = models.CharField(max_length=40)
f_name = models.CharField(max_length=40)
l_name = models.CharField(max_length=40)
address_id = models.IntegerField()
phone_num = models.IntegerField()
loan_item_count = models.IntegerField()
id = models.IntegerField(unique = True, primary_key = True)
def __init__(self, dictionary, *args, **kwargs):
self.role_id = int(dictionary['role_id'])
self.user_id = dictionary['user_id']
self.email = dictionary['email']
self.password = dictionary['password']
self.f_name = dictionary['f_name']
self.l_name = dictionary['l_name']
self.address_id = dictionary['address_id']
self.phone_num = dictionary['phone_num']
self.loan_item_count = dictionary['loan_item_count']
self.id = self.user_id
USERNAME_FIELD = 'user_id'
class Meta:
managed = False
I don't want the model to affect the DB in any way. I'm loading it by a simple raw SQL query from a gateway method.
This is how I'm handling login:
def login_request(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
user = userGateway(username,password)
if user is not None:
print("=========USER==========")
print(user.email)
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request,user)
print(request.user.is_authenticated)
if user.role_id==1:
return render(request, 'biblioteca/admin/landing.html')
# return HttpResponseRedirect('/')
else:
return render(request, 'biblioteca/landing.html')
else:
print("=========NOT USER==========")
else:
if(request.user is not None and not request.user.is_anonymous):
return render(request, 'biblioteca/admin/landing.html')
form = LoginForm()
return render(request, 'biblioteca/login.html', {'form': form})
As you can see, I'm setting the back-end before login to authenticate without having to pass through a password - the password check is being done when the user object is created by comparing the password passed in with the password retrieved from the DB.
If I return a render, as seen here, the next page contains the proper request.user object. If I return a redirect, it does not. Additionally, if I leave that page at all, the user becomes unauthenticated and anonymous again, losing the session.
Any help as to why this happens would be much appreciated.
When you redirect, the request is completed and a redirect code is sent to the client, who then makes a new request to the new page without the POST data for the login form. The user may not be getting their token. In that case, render a page to log them in that delays for a few seconds, then redirects them to the right spot.
So, this was solved by turning userGateway() into a proper auth backend and implementing it like that.
Explanation as to why:
The sessionID in django stores a hash of the user's PK as well as the auth backend used to log in. Whenever a new request is sent, data needed is lazy-loaded from the DB using this hash.
This is why login() was properly authenticating the user on the login page, because it was pretty much forced to. As soon as another request happened, though, it would be unable to load the user's data from the DB, and would flush the sessionid.

Tango With Django: User Authentication - User being saved but not receiving confirmation

I am on chapter 9 of Tango With Django:
http://www.tangowithdjango.com/book17/chapters/login.html#demo
Whenever I create a user, I get an error page on my browser as shown below:
IntegrityError at /rango/register/
rango_userprofile.user_id may not be NULL
Request Method: POST
Request URL: http://127.0.0.1:8000/rango/register/
Django Version: 1.7.1
Exception Type: IntegrityError
Exception Value:
rango_userprofile.user_id may not be NULL
Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 485
Python Executable: C:\Python27\python.exe
Python Version: 2.7.8
Python Path:
['C:\\Users\\Paul.Zovighian\\desktop\\tango\\tango_with_django_project',
'C:\\Python27\\lib\\site-packages\\pandas-0.14.1-py2.7-win32.egg',
'C:\\Python27\\lib\\site-packages\\pytz-2014.7-py2.7.egg',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\win32',
'C:\\Python27\\lib\\site-packages\\win32\\lib',
'C:\\Python27\\lib\\site-packages\\Pythonwin']
Server time: Fri, 12 Dec 2014 16:50:14 +0000
I can see that there is an integrity error, but I am not sure why this is the message I get. If I try registering that user again, it won't let me because it says that that username already exists. So it's like, working for registering new users, but it just doesn't acknowledge the successful registration.
Here is my code:
models.py
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
views.py
from django.http import HttpResponse
from django.shortcuts import render
from rango.models import Category
from rango.models import Page
from rango.forms import CategoryForm
from rango.forms import PageForm
from rango.forms import UserForm, UserProfileForm
def index(request):
# Query the database for a list of ALL categories currently stored.
# Order the categories by no. likes in descending order.
# Retrieve the top 5 only - or all if less than 5.
# Place the list in our context_dict and dictionary which will be passed to the template engine.
category_list = Category.objects.order_by('-likes')[:5]
page_list = Page.objects.order_by('-views')[:5]
context_dict = {'categories': category_list, 'pages': page_list}
# Render the response and send it back!
return render(request, 'rango/index.html', context_dict)
def about(request):
context_dict = {'italicmessage': "I am italicised font from the context"}
return render(request, 'rango/about.html', context_dict)
def category(request, category_name_slug):
# Create a context dictionary which we can pass to the template rendering engine
context_dict = {}
try:
# Can we find a category name slug with the given name?
# If we can't, the .get() method raises a DoesNotExist exception.
# So the .get() method returns one model instance or raises an exception.
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
# Retrieve all the associated pages.
# Note that filter returns >= 1 model instance.
pages = Page.objects.filter(category=category)
# Adds our results list to the template context under name pages.
context_dict['pages'] = pages
# We also add the category object from the database to the context dictionary.
# We'll use this in the template to verify that the category exists.
context_dict['category'] = category
context_dict['category_name_slug'] = category_name_slug
except Category.DoesNotExist:
# We get here if we didn't find the specified category.
# Don't do anything - the template displayes the "no category message for us."
pass
# Go render the response and return it to the client.
return render(request, 'rango/category.html', context_dict)
def add_category(request):
# A HTTP POST?
if request.method == 'POST':
form = CategoryForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# save the new category to the database.
form.save(commit=True)
# Now call the index() view.
# The user will be shown the homepage.
return index(request)
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = CategoryForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'rango/add_category.html', {'form': form})
def add_page(request, category_name_slug):
try:
cat = Category.objects.get(slug=category_name_slug)
except Category.DoesNotExist:
cat = None
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
if cat:
page = form.save(commit=False)
page.category = cat
page.views = 0
page.save()
return category(request, category_name_slug)
else:
form = PageForm()
context_dict = {'form': form, 'category': cat, 'category_name_slug': category_name_slug}
return render(request, 'rango/add_page.html', context_dict)
def register(request):
# A boolean value for telling the template whether the registration was successful.
# Set to False initially. Code changes value to True when registration succeeds.
registered = False
# If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST':
# Attempt to grab information from the raw form information
# Note that we make use of both UserForm and UserProfileForm.
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
# If the two forms are valid...
if user_form.is_valid() and profile_form.is_valid():
# Save the user's form data to the database.
user = user_form.save()
# Now we hash the password with the set_password method.
# Once hashed, we can update the user object.
user.set_password(user.password)
user.save()
# Now we sort out the UserProfile instance.
# Since we need to set the user attribute ourselves, we set commit=False
# This delays saving the model until we're ready to avoid integrity problems.
profile = profile_form.save()
profile.user = user
# Did the user provide a profile picture?
# If so, we need to get it from the input form and put it in the UserProfile model.
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
# Now we save the UserProfile model instance.
profile.save()
# Update our variables to tell the template registration was successful.
registered = True
# Invalid form or forms - mistakes or something else?
# Print problems to the terminal.
# They'll also be shown to the user.
else:
print user_form.errors, profile_form.errors
# Not a HTTP POST, so we render our form using two ModuleForm instances.
# These forms will be blank, ready for user input.
else:
user_form = UserForm()
profile_form = UserProfileForm()
# Render the template depending on the context.
return render(request,'rango/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
forms.py
from django import forms
from django.contrib.auth.models import User
from rango.models import Page, Category, UserProfile
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter the category name.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
# An inline class to provide additional information on the form.
class Meta:
# Provide an association between the ModelForm and a model
model = Category
fields = ('name',)
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
model = Page
exclude = ('category',)
# or specify the fields to include (.i.e. not include the category field)
#fields = ('title', 'url', 'views')
def clean(self):
cleaned_data = self.cleaned_data
url = cleaned_data.get('url')
# If url is not empty and doesn't start with 'http://', prepend 'http://'.
if url and not url.startswith('http://'):
url = 'http://' + url
cleaned_data['url'] = url
return cleaned_data
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username','email','password')
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('website', 'picture')
I think I have all relevant files included here, but let me know if I could provide any other info to clear things up!
Thanks in advance
Your comment says "Since we need to set the user attribute ourselves, we set commit=False", but you don't actually do that. It should be:
profile = profile_form.save(commit=False)
In future, please cut your code down to the minimum that exhibits your problem: the error was occurring on register, you didn't need to show all the code relating to categories.

Categories