how to fix the 'AnonymousUser' object has no attribute 'profile' error? - python

I'm writing a chat app for a hypothetical social network but when I try to open the chat page I give the following error 'AnonymousUser' object has no attribute 'profile' error .
I think there may be problem in the models file but I can't really figure out how to fix it and I'm really confused now!? can anyone give any suggestions??
parts of the chat views.py
def index(request):
if request.method == 'POST':
print request.POST
request.user.profile.is_chat_user=True
logged_users = []
if request.user.username and request.user.profile.is_chat_user:
context = {'logged_users':logged_users}
cu = request.user.profile
cu.is_chat_user = True
cu.last_accessed = utcnow()
cu.save()
return render(request, 'djangoChat/index.html', context)
try:
eml = request.COOKIES[ 'email' ]
pwd = request.COOKIES[ 'password' ]
except KeyError:
d = {'server_message':"You are not logged in."}
query_str = urlencode(d)
return HttpResponseRedirect('/login/?'+query_str)
try:
client = Vertex.objects.get(email = eml)
context = {'logged_users':logged_users}
cu = request.user.profile
cu.is_chat_user = True
cu.last_accessed = utcnow()
cu.save()
if client.password != pwd:
raise LookupError()
except Vertex.DoesNotExist:
sleep(3)
d = {'server_message':"Wrong username or password."}
query_str = urlencode(d)
return HttpResponseRedirect('/login/?'+query_str)
return render_to_response('djangoChat/index.html',
{"USER_EMAIL":eml,request.user.profile.is_chat_user:True},
context_instance=RequestContext(request))
#csrf_exempt
def chat_api(request):
if request.method == 'POST':
d = json.loads(request.body)
msg = d.get('msg')
user = request.user.username
gravatar = request.user.profile.gravatar_url
m = Message(user=user,message=msg,gravatar=gravatar)
m.save()
res = {'id':m.id,'msg':m.message,'user':m.user,'time':m.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':m.gravatar}
data = json.dumps(res)
return HttpResponse(data,content_type="application/json")
# get request
r = Message.objects.order_by('-time')[:70]
res = []
for msgs in reversed(r) :
res.append({'id':msgs.id,'user':msgs.user,'msg':msgs.message,'time':msgs.time.strftime('%I:%M:%S %p').lstrip('0'),'gravatar':msgs.gravatar})
data = json.dumps(res)
return HttpResponse(data,content_type="application/json")
def logged_chat_users(request):
u = Vertex.objects.filter(is_chat_user=True)
for j in u:
elapsed = utcnow() - j.last_accessed
if elapsed > datetime.timedelta(seconds=35):
j.is_chat_user = False
j.save()
uu = Vertex.objects.filter(is_chat_user=True)
d = []
for i in uu:
d.append({'username': i.username,'gravatar':i.gravatar_url,'id':i.userID})
data = json.dumps(d)
return HttpResponse(data,content_type="application/json")
and parts of my chat models:
class Message(models.Model):
user = models.CharField(max_length=200)
message = models.TextField(max_length=200)
time = models.DateTimeField(auto_now_add=True)
gravatar = models.CharField(max_length=300)
def __unicode__(self):
return self.user
def save(self):
if self.time == None:
self.time = datetime.now()
super(Message, self).save()
def generate_avatar(email):
a = "http://www.gravatar.com/avatar/"
a+=hashlib.md5(email.lower()).hexdigest()
a+='?d=identicon'
return a
def hash_username(username):
a = binascii.crc32(username)
return a
# the problem seems to be here ??!
User.profile = property(lambda u: Vertex.objects.get_or_create(user=u,defaults={'gravatar_url':generate_avatar(u.email),'username':u.username,'userID':hash_username(u.username)})[0])
and finally parts of the another app(ChatUsers):
class Vertex(models.Model,object):
user = models.OneToOneField(User)
password = models.CharField(max_length=50)
#user_id = models.CharField(max_length=100)
username = models.CharField(max_length=300)
userID =models.IntegerField()
Message = models.CharField(max_length=500)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
email = models.EmailField(max_length=75)
is_chat_user = models.BooleanField(default=False)
gravatar_url = models.CharField(max_length=300,null=True, blank=True)
last_accessed = models.DateTimeField(auto_now_add=True)

Because that user has not logged in yet. Django treat them as AnonymousUser and AnonymousUser does not have the profile property.
If the view is only for logged in user, you can add the login_required decorator to the view function to force the login process. Otherwise, you need to judge whether a user is anonymous with the is_authenticated function.
Reference: Using the Django authentication system

Related

AttributeError at /sample/ : 'QuerySet' object has no attribute 'no_of_ques'

I am making a quiz application, for result calculation I have written logic ..If the value of answer stored in question model is equal to the answer chosen by user then , when user submits each question , score is incrementing by one, but I've failed to build this logic as am a new user to django please help.
Models.py : question along with its 4 options and the correct answer is in question model(These fields are entered by the user who creates a quiz by filling a form). Answer submitted by user is in answer model(This field is entered by user who takes quiz). score is stored in result model.
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
class quiztitle(models.Model):
Quiz_id = models.AutoField(primary_key=True)
Quiz_title = models.CharField(max_length=600)
User = settings.AUTH_USER_MODEL
User_id= models.ForeignKey(User, on_delete=models.CASCADE)
no_of_ques = models.IntegerField(default=10)
class question(models.Model):
Qid = models.AutoField(primary_key=True)
User = settings.AUTH_USER_MODEL
User_id = models.ForeignKey(User,on_delete=models.CASCADE)
Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE)
Qques = models.TextField()
Qoption1 = models.TextField()
Qoption2 = models.TextField()
Qoption3 = models.TextField()
Qoption4 = models.TextField()
QAnswer = models.TextField()
class answer(models.Model):
Ansid = models.AutoField(primary_key=True)
Qid = models.ForeignKey(question,on_delete=models.CASCADE)
Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE)
User = settings.AUTH_USER_MODEL
User_id = models.ForeignKey(User, on_delete=models.CASCADE)
Answer = models.TextField()
class result(models.Model):
result = models.AutoField(primary_key=True)
Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE)
User_id = models.ForeignKey(User, on_delete=models.CASCADE)
score = models.FloatField()
def __str__(self):
return str(self.pk)
here's views.py file
from django.shortcuts import render,redirect,HttpResponseRedirect
from .models import question ,quiztitle ,answer ,result
from django.contrib.auth.models import User
from .forms import CreateUserForm
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from .decorators import unauthenticated_user,allowed_users
from django.contrib.auth.models import Group
def home_page(request):
return render(request,'Home.html')
def forbidden(request):
return render(request,'error403.html')
#unauthenticated_user
def registerPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
group = Group.objects.get(name='Student')
user.groups.add(group)
messages.success(request, 'account has been created successfully for username' + username)
return redirect('login')
context = {'form':form}
return render(request,'register.html',context)
#unauthenticated_user
def handle_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request,user)
if request.user.groups.filter(name="Teacher"):
return redirect('quizmaker')
else:
return redirect('student')
else:
messages.info(request, 'Incorrect Username or Password')
context = {}
return render(request, 'login.html', context)
def logoutUser(request):
logout(request)
return redirect('home')#redirect to login page
#login_required(login_url='home')
#allowed_users(allowed_roles=['Teacher','Head'])
def handle_quiz(request):
if request.method=="POST":
# get post parameters
Quiz_title = request.POST.get('Quiz_title')
Quiz_id = request.POST.get('Quiz_id')
no_of_ques = request.POST.get('no_of_ques')
Qid = request.POST.get('Qid')
Qques = request.POST.get('Qques')
Qoption1 = request.POST.get('Qoption1')
Qoption2 = request.POST.get('Qoption2')
Qoption3 = request.POST.get('Qoption3')
Qoption4 = request.POST.get('Qoption4')
QAnswer = request.POST.get('QAnswer')
title = quiztitle(Quiz_title=Quiz_title,Quiz_id=Quiz_id,no_of_ques=no_of_ques)
title.User_id=request.user
title.save()
detail = question(Qid=Qid,Qques=Qques,Qoption1=Qoption1,Qoption2=Qoption2,Qoption3=Qoption3,Qoption4=Qoption4,QAnswer=QAnswer)
detail.User_id=request.user
detail.Quiz_id = title
detail.save()
messages.success(request,'Your question has been added succesfully')
return HttpResponseRedirect('/quizmaker')
return render(request,"createquiz.html")
#login_required(login_url='login')
#allowed_users(allowed_roles=['Student'])
def handle_response(request):
if request.user.is_authenticated:
myuser = User.objects.all()
title = quiztitle.objects.all()
data = question.objects.all()
if request.method == 'POST':
Answer=request.POST.get('Answer')
response = answer(Answer=Answer)
response.User_id = request.user
response.Quiz_id = request.quiztitle
response.Qid = request.question
Answer.save()
return HttpResponseRedirect('/student')
return render(request,"student.html",context={"messages": data ,"topic": title ,"user1": myuser})
def handle_result(request):
if request.user.is_authenticated:
quiz = quiztitle.objects.all()
ques = question.objects.all()
ans = answer.objects.all()
score = 0
if request.method == 'POST':
while(score<=quiz.no_of_ques):
if (ques.objects.QAnswer == ans.objects.Answer):
score += 1
print(score)
sc = request.POST('score')
res = result(sc=score)
res.User_id = request.user
res.Quiz_id = request.quiztitle
result.save()
return HttpResponseRedirect('/sample')
return render(request, "sample.html", context = {"ques":ques , "ans":ans})
In your handle_result function, you have:
quiz = quiztitle.objects.all()
# ...
while(score<=quiz.no_of_ques):
The issue here is that:
The quiz variable is not ONE quiz, it's ALL of them. So it's not an instance, it's a list of instances (technically, a QuerySet of instances)
Therefore, you cannot call quiz.no_of_ques, because quiz is not an instance
That's why you're getting the 'QuerySet' object has no attribute 'no_of_ques' error. Either query one specific instance, or query them all and loop over them.
In views.py handle_result function,
replacing
quiz = quiztitle.objects.all()
with
quizno = quiztitle.objects.values_list('no_of_ques', flat=True)
#....
while(score<=quizno):
it resolves the error 'QuerySet' object has no attribute 'no_of_ques' as it queries one instance i.e no_of_ques

Cannot assign "'7'": "Appointment.your_service" must be a "Service" instance

I'm working on a project "Beauty Parlour Management System" and I got this error (Cannot assign "'7'": "Appointment.your_service" must be a "Service" instance.) anyone here can help me, please.
When I am filling a book appointment form then I got this error.
models.py
class Service(models.Model):
name = models.CharField(max_length=50)
price = models.IntegerField(default=0)
image = models.ImageField(upload_to='uploads/productImg')
class Appointment(models.Model):
your_name = models.CharField(max_length=100)
your_phone = models.CharField(max_length=10)
your_email = models.EmailField(max_length=200)
your_service = models.ForeignKey('Service', on_delete=models.CASCADE, default=1)
your_date = models.DateField()
views.py
def appointments(request):
if request.method == 'GET':
return render(request, 'core/bookappointment.html')
else:
your_name = request.POST.get('your-name')
your_phone = request.POST.get('your-phone')
your_email = request.POST.get('your-email')
your_service = request.POST.get('your-service')
your_date = request.POST.get('your-date')
details = Appointment(
your_name = your_name,
your_phone = your_phone,
your_email = your_email,
your_service = your_service,
your_date = your_date)
details.save()
return render(request, 'core/appointments.html')
You create this by assigining the method to your_service_id field, if you work with your_service, it should be a Service object:
details = Appointment.objects.create(
your_name=your_name,
your_phone=your_phone,
your_email=your_email,
your_service_id=your_service,
your_date=your_date
)
That being said, it is usually better to validate, clean, and save the data with a ModelForm, not manually.
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
def appointments(request,pk):
record = get_object_or_404(Service,pk=pk)
if request.method == 'POST':
form = appointmentsForm(request.POST,request.FILES)
if form.is_valid():
appointment= form.save(commit=False)
appointment.your_service = record
appointment.save()
return render(request, 'core/bookappointment.html')
else:
return render(request, 'core/appointments.html')

Function notifies commentor when the poster should get notified

If I comment on the post named "a", then I get a notification saying that I made the comment on "a" but the notification system should notify the user who created post "a".
I have a clue what to do, because I have done something similar (notifying the user who commented when there's a reply to that comment) thanks to some tutorial.
In models.py for notification, I have to send the right notification and connect to it. I'll post my full code, you can see the bottom function for the connecting, and this is the one I'm having problem with.
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db import models
from django.contrib.auth.models import User
from main.models import Post
from accounts.models import MyProfile
from .signals import notify
# Create your models here.
class NotificationQuerySet(models.query.QuerySet):
def get_user(self, recipient):
return self.filter(recipient=recipient)
def mark_targetless(self, recipient):
qs = self.unread().get_user(recipient)
qs_no_target = qs.filter(target_object_id=None)
if qs_no_target:
qs_no_target.update(read=True)
def mark_all_read(self, recipient):
qs = self.unread().get_user(recipient)
qs.update(read=True)
def mark_all_unread(self, recipient):
qs = self.read().get_user(recipient)
qs.update(read=False)
def unread(self):
return self.filter(read=False)
def read(self):
return self.filter(read=True)
def recent(self):
return self.unread()[:5]
class NotificationManager(models.Manager):
def get_queryset(self):
return NotificationQuerySet(self.model, using=self._db)
def all_unread(self, user):
return self.get_queryset().get_user(user).unread()
def all_read(self, user):
return self.get_queryset().get_user(user).read()
def all_for_user(self, user):
self.get_queryset().mark_targetless(user)
return self.get_queryset().get_user(user)
class Notification(models.Model):
sender_content_type = models.ForeignKey(ContentType, related_name='nofity_sender')
sender_object_id = models.PositiveIntegerField()
sender_object = GenericForeignKey("sender_content_type", "sender_object_id")
verb = models.CharField(max_length=255)
action_content_type = models.ForeignKey(ContentType, related_name='notify_action',
null=True, blank=True)
action_object_id = models.PositiveIntegerField(null=True, blank=True)
action_object = GenericForeignKey("action_content_type", "action_object_id")
target_content_type = models.ForeignKey(ContentType, related_name='notify_target',
null=True, blank=True)
target_object_id = models.PositiveIntegerField(null=True, blank=True)
target_object = GenericForeignKey("target_content_type", "target_object_id")
recipient = models.ForeignKey(settings.AUTH_PROFILE_MODULE, related_name='notifications')
read = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
objects = NotificationManager()
def __unicode__(self):
try:
target_url = self.target_object.get_absolute_url()
except:
target_url = None
context = {
"sender": self.sender_object,
"verb": self.verb,
"action": self.action_object,
"target": self.target_object,
"verify_read": reverse("notifications_read", kwargs={"id": self.id}),
"target_url": target_url,
}
if self.target_object:
if self.action_object and target_url:
return "%(sender)s %(verb)s <a href='%(verify_read)s?next=%(target_url)s'>%(target)s</a> with %(action)s" %context
if self.action_object and not target_url:
return "%(sender)s %(verb)s %(target)s with %(action)s" %context
return "%(sender)s %(verb)s %(target)s" %context
return "%(sender)s %(verb)s" %context
#property
def get_link(self):
try:
target_url = self.target_object.get_absolute_url()
except:
target_url = reverse("notifications_all")
context = {
"sender": self.sender_object,
"verb": self.verb,
"action": self.action_object,
"target": self.target_object,
"verify_read": reverse("notifications_read", kwargs={"id": self.id}),
"target_url": target_url,
}
if self.target_object:
return "<a href='%(verify_read)s?next=%(target_url)s'>%(sender)s %(verb)s %(target)s with %(action)s</a>" %context
else:
return "<a href='%(verify_read)s?next=%(target_url)s'>%(sender)s %(verb)s</a>" %context
def new_notification(sender, **kwargs):
kwargs.pop('signal', None)
recipient = kwargs.pop("recipient")
verb = kwargs.pop("verb")
affected_users = kwargs.pop('affected_users')
#super_user_qs = MyProfile.objects.get(user=Post.moderator),
''' this is wrong, It;s what I tried but failed
if super_user_qs:
super_user_instance = super_user_qs
new_note = Notification(
recipient=super_user_instance,
verb = verb, # smart_text
sender_content_type = ContentType.objects.get_for_model(sender),
sender_object_id = sender.id,
)
for option in ("target", "action"):
obj = kwargs.pop(option, None)
if obj is not None:
setattr(new_note, "%s_content_type" %option, ContentType.objects.get_for_model(obj))
setattr(new_note, "%s_object_id" %option, obj.id)
new_note.save()
the below works for notifying commentor who gets reply
'''
if affected_users is not None:
for u in affected_users:
if u == sender:
pass
else:
new_note = Notification(
recipient=recipient,
verb = verb, # smart_text
sender_content_type = ContentType.objects.get_for_model(sender),
sender_object_id = sender.id,
)
for option in ("target", "action"):
try:
obj = kwargs[option]
if obj is not None:
setattr(new_note, "%s_content_type" %option, ContentType.objects.get_for_model(obj))
setattr(new_note, "%s_object_id" %option, obj.id)
except:
pass
new_note.save()
else:
new_note = Notification(
recipient=recipient,
verb = verb, # smart_text
sender_content_type = ContentType.objects.get_for_model(sender),
sender_object_id = sender.id,
)
for option in ("target", "action"):
obj = kwargs.pop(option, None)
if obj is not None:
setattr(new_note, "%s_content_type" %option, ContentType.objects.get_for_model(obj))
setattr(new_note, "%s_object_id" %option, obj.id)
new_note.save()
notify.connect(new_notification)
And then in models.py I have comment and post models. the get_affected_user is the function that's used in comment views.py to notify affected_user I believe. (I followed a tutorial.)
class Comment(models.Model):
user = models.ForeignKey(MyProfile)
parent = models.ForeignKey("self", null=True, blank=True)
post = models.ForeignKey(Post, null=True, blank=True, related_name="commented_post")
#property
def get_origin(self):
return self.path
#property
def get_comment(self):
return self.text
#property
def is_child(self):
if self.parent is not None:
return True
else:
return False
def get_children(self):
if self.is_child:
return None
else:
return Comment.objects.filter(parent=self)
def get_affected_users(self):
"""
it needs to be a parent and have children,
the children, in effect, are the affected users.
"""
comment_children = self.get_children()
if comment_children is not None:
users = []
for comment in comment_children:
if comment.user in users:
pass
else:
users.append(comment.user)
return users
return None
class Post(models.Model):
title = models.CharField(max_length = 50)
moderator = models.ForeignKey(User)
views = models.IntegerField(default=0)
In views.py for comment, the above get_affected_user is used for notifying commentor who gets reply. I thought about using the same function to achieve what I want, but couldn't. So for that I just set get_affected_user to none for now.
def comment_create_view(request):
if request.method == "POST" and request.user.is_authenticated():
parent_id = request.POST.get('parent_id')
post_id = request.POST.get("post_id")
origin_path = request.POST.get("origin_path")
try:
post = Post.objects.get(id=post_id)
except:
post = None
parent_comment = None
if parent_id is not None:
try:
parent_comment = Comment.objects.get(id=parent_id)
except:
parent_comment = None
if parent_comment is not None and parent_comment.post is not None:
post = parent_comment.post
form = CommentForm(request.POST)
if form.is_valid():
comment_text = form.cleaned_data['comment']
if parent_comment is not None:
# parent comments exists
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=parent_comment.get_origin,
text=comment_text,
post = post,
parent=parent_comment
)
#affected_users = parent_comment.get_affected_users()
#print "this is"
affected_users = parent_comment.get_affected_users()
notify.send(
MyProfile.objects.get(user=request.user),
action=new_comment,
target=parent_comment,
recipient=parent_comment.user,
affected_users = affected_users,
verb='replied to')
messages.success(request, "Thank you for your response.", extra_tags='safe')
return HttpResponseRedirect(parent_comment.get_absolute_url())
else:
new_comment = Comment.objects.create_comment(
user=MyProfile.objects.get(user=request.user),
path=origin_path,
text=comment_text,
post = post
)
notify.send(
MyProfile.objects.get(user=request.user),
recipient = MyProfile.objects.get(user=request.user),
action=new_comment,
affected_users = None,
target = new_comment.post,
verb='commented on')
messages.success(request, "Thank you for the comment.")
return HttpResponseRedirect(new_comment.get_absolute_url())
else:
messages.error(request, "There was an error with your comment.")
return HttpResponseRedirect(origin_path)
else:
raise Http404
Edit:I'm having this problem for almost a week now.....I asked for some help from the instructor of the tutorial I purchased, and he only answers in short sentences(I can tell he doesn't absolutely care). Here are some hints he dropped. If I were to notify superuser
I should add the following to the models.py for notification,
super_user_qs = User.objects.filter(is_admin=True)
if super_user_qs.exists():
super_user_instance = super_user_qs.first()
new_note = Notification(
recipient=super_user_instance,
verb = verb, # smart_text
sender_content_type = ContentType.objects.get_for_model(sender),
sender_object_id = sender.id,
)
for option in ("target", "action"):
obj = kwargs.pop(option, None)
if obj is not None:
setattr(new_note, "%s_content_type" %option, ContentType.objects.get_for_model(obj))
setattr(new_note, "%s_object_id" %option, obj.id)
new_note.save()
but then I told him, I'm trying to notify post creator/moderator because any one can make post.(I told him this couple times/before he answered with the superuser one) I should use model post_save signal to create a new Notification within the model I'm working on. and I do not have to use the custom notify signal in this case.
Meanwhile, I was watching the tutorials over and over. I thought maybe I just need to change recipient = MyProfile.objects.get(user=post.moderator),
to the post.moderator but then I get Cannot assign "": "Notification.recipient" must be a "MyProfile" instance. so I did recipient = MyProfile.objects.get(user=post.moderator), but this notify to me about the comments I make...
I really await any advise
thank you
For you to notify the POST owner, it should be sent this way:
recipient = new_comment.post.moderator
instead of
recipient = MyProfile.objects.get(user=request.user)
This would send the notification to the moderator of the Post.
The way I see it is:
if parent_comment is not None: This line evaluates to false, so the recipient of the message is request.user.
You should make sure that this line parent_id = request.POST.get('parent_id') has a meaningful value
This line parent_comment = Comment.objects.get(id=parent_id) might be the culprit. Insert a print('!!!!!parent_id = ', parent_id) after this line, and see if you get in the console the id of an actual comment.
But that's what I suspect anyway, that the templates you created don't include this field in the form.
If you paste the template code, I might be able to help you debug.

Checking session in Django custom user model

I am creating a custom user model, here's the code in models.py:
class Users(models.Model):
username = models.CharField(max_length=30)
password = models.CharField(max_length=30)
contactnos = models.IntegerField()
address = models.CharField(max_length=50)
fname = models.CharField(max_length=30)
mname = models.CharField(max_length=30)
lname = models.CharField(max_length=30)
def __unicode__(self):
return self.username
I have this line of code in views.py
def auth_view(request):
try:
m = Users.objects.get(username=request.POST['username'])
if m.password == request.POST['password']:
request.session["id"] = m.id
myid = request.session["id"]
if myid == m.id:
return render(request, "profile.html", {
'username': m,
'myid': myid
})
else:
HttpResponse("Session has expired. Log in again.")
except Users.DoesNotExist:
return HttpResponseRedirect('/account/invalid')
The code above can check if the user is in the database and able to redirect to profile page. What I want to achieve is if the user log out, the session key should expire or redirect to another page and not on the profile page.
And I want to ask, if it is really possible? Thanks.
Just create another view for log out.
def logout_view(request):
try:
del request.session['id']
except KeyError:
pass
return HttpResponseRedirect('/home')

UnboundLocalError local variable <variablename> referenced before assignment

I faced the error when I tried to capture the POST data from a form. Weird, because the same algorithm works with another django app model.
The models:
class Item(models.Model):
code = models.CharField(max_length=200, unique=True)
barcode = models.CharField(max_length=300)
desc = models.CharField('Description',max_length=500)
reg_date = models.DateField('registered date')
registrar = models.CharField(max_length=100)
def __unicode__(self):
return self.code + ' : ' + self.desc
class ItemInfo(models.Model):
model = models.ForeignKey(Item)
supplier = models.ForeignKey(Supplier)
stock_on_hand = models.IntegerField()
stock_on_order = models.IntegerField()
cost = models.IntegerField()
price = models.IntegerField()
unit = models.CharField(max_length=100)
lead_time = models.IntegerField()
def __unicode__(self):
return Item.code + ' : ' + supplier
class ItemForm(ModelForm):
class Meta:
model = Item
class ItemInfoForm(ModelForm):
class Meta:
model = ItemInfo
exclude = ('model')
And the views.py function for non-working (Item) is like this:
def register(request):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
if request.POST:
item = Item()
item_info = ItemInfo()
header_form == ItemForm(data=request.POST,instance=item)
details_form == ItemInfoForm(data=request.POST, instance=item_info)
if header_form.is_valid():
header = header_form.save()
if details_form.is_valid():
details = details_form.save(commit=False)
details.supplier = header
details.save()
return HttpResponseRedirect('/item/')
else:
return render_to_response('error/denied_data_entry.html')
else:
header_form = ItemForm()
details_form = ItemInfoForm()
return render_to_response('item/register.html',{'header_form' : header_form, 'details_form' : details_form}, csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
The working views.py function for another working (Supplier) model is here:
def register(request):
csrf_context = RequestContext(request)
current_user = User
if request.user.is_authenticated():
if request.POST:
supplier = Supplier()
supplier_info = SupplierInfo()
header_form = SupplierForm(data=request.POST, instance=supplier)
details_form = SupplierInfoForm(data=request.POST, instance=supplier_info)
if header_form.is_valid():
header = header_form.save()
if details_form.is_valid():
details = details_form.save(commit=False)
details.model = header
details.save()
return HttpResponseRedirect('/supplier/')
else:
return render_to_response('error/denied_data_entry.html')
else:
return render_to_response('error/denied_data_entry.html')
else:
header_form = SupplierForm()
details_form = SupplierInfoForm()
return render_to_response('supplier/register.html', {'header_form' : header_form, 'details_form' : details_form}, csrf_context)
else:
return render_to_response('error/requires_login.html', csrf_context)
The traceback page shows that the POST did pass some variable. Help me please, I cant figure it out why it works on Supplier, but not Item.
P/S: Sorry for the indentation.
The problem is here:
# ...
header_form == ItemForm(data=request.POST,instance=item)
details_form == ItemInfoForm(data=request.POST, instance=item_info)
You're not assigning, you're comparing.

Categories