local variable 'user' referenced before assignment issue - python

so i currently have my likes app which deals with friend requests, and it works fine however my notification dont seem to be working. Whenever some likes someone else regardless of weather they are liked by that user or not it only sends the second of the two notify.send. I presume its an issue with the line "user = get_object_or_404(User, username=user.username)", however i dont know how to get round it. Here is my code:
def like_user(request, id):
pending_like = get_object_or_404(User, id=id)
user_like, created = UserLike.objects.get_or_create(user=request.user)
user = get_object_or_404(User, username=user.username)
liked_user, like_user_created = UserLike.objects.get_or_create(user=user)
if pending_like in user_like.liked_users.all():
user_like.liked_users.remove(pending_like)
elif request.user in liked_user.liked_users.all():
user_like.liked_users.add(pending_like)
notify.send(request.user,
#action=request.user.profile,
target=request.user.profile,
recipient=pending_like,
verb='sent you a friend request view'),
else:
user_like.liked_users.add(pending_like)
notify.send(request.user,
#action=request.user.profile,
target=request.user.profile,
recipient=pending_like,
verb='accepted your friend request view')
return redirect("profile", username=pending_like.username)
Here is an example of where the line " if request.user in liked_user.liked_users.all():" works fine i presume because the line " user = get_object_or_404(User, username=username)" has username in it.
#login_required
def profile_view(request, username):
user = get_object_or_404(User, username=username)
liked_user, like_user_created = UserLike.objects.get_or_create(user=user)
do_they_like = False
if request.user in liked_user.liked_users.all():
do_they_like = True
However in my first bit of code I'm trying to use user.username instead of username=username but i get the error "local variable 'user' referenced before assignment". What is the best way round this? am i do it completely wrong? should i try and pass in username, because when i do i get the error "like_user() takes exactly 3 arguments (2 given)". Sorry quite new to django, any help would be massively appreciated!
Here is my likes app model incase it helps:
class UserLike(models.Model):
user = models.OneToOneField(User, related_name='liker')
liked_users = models.ManyToManyField(User, related_name='liked_users', blank=True)
objects = UserLikeManager()
def __unicode__(self):
return self.user.username
def get_mutual_like(self, user_b):
i_like = False
you_like = False
if user_b in self.liked_users.all():
i_like = True
liked_user, created = UserLike.objects.get_or_create(user=user_b)
if self.user in liked_user.liked_users.all():
you_like = True
if you_like and i_like:
return True
else:
return False
really sorry for the long post, but im very stuck as most of this was written by some more advanced than me and im left with the issue of fixing it, any help would be massively appreciated!
thanks

You are correct, the issue is with the line:
user = get_object_or_404(User, username=user.username)
You're trying to get the attribute 'username' of the 'user' object, but 'user' is not defined within the scope of your function yet. In other words, at that point 'user' doesn't exist yet.
I don't have nearly enough info to start helping you, but if it was me debugging that, I'd consider the following:
You might not need that problematic line at all. It seems like request.user holds the reference to a user (The one who's liking stuff??), and pending_like seems to contain a reference to the recipient of the like. That's probably enough users to establish a 'like' relationship
Maybe do a print of the attributes of pending_like print(pending_like.__dict__) and request.user print(request.user.__dict__) to see if they contain all the info you need?

Related

How can i fetch my data from database to django template?

Whenever I run this,
Exception Value:
name 'current_user' is not defined;
error is raised.
I am not getting where i am doing the mistake as I m new in django programming. Please help me fetch the data
# To add a new product in the database
def AddNewProduct(request):
if request.method == "POST":
current_user = request.user
product_title =request.POST['product_title']
uid = request.POST['uid']
specification =request.POST['specification']
sale_price = request.POST['sale_price']
discount = request.POST['discount']
img1 = request.FILES['img1']
img2 = request.FILES['img2']
promote_method = request.POST['promote_method']
terms_conditions = request.POST['terms_conditions']
newproduct = AffProduct(user_id=current_user.id, product_title=product_title, uid=uid, specification=specification, sale_price=sale_price,
discount=discount, img1=request.FILES.get('img1'), img2=request.FILES.get('img2'),
promote_method=promote_method, terms_conditions=terms_conditions)
newproduct.save()
# Status message
messages.success(request, 'Product added successfully')
return render(request, 'blink_network.html')
else:
return render(request, 'blink_network.html')
#Here i m trying to fetch my data.
def showproduct(request):
if request.user.is_authenticated:
result = AffProduct.objects.filter(user_id=current_user.id)
else:
result = AffProduct.objects.all()
return render(request, 'blink_viewproduct.html', {'result': result})
It looks like you will be getting that problem from showproduct(request) because you don't define current_user in that method before calling it.
to call this
result = AffProduct.objects.filter(user_id=current_user.id)
you need to define current_user = request.user beforehand
Could you share the relevant models.py file as well? You probably linked the user model with the ForeignKey with the Product model. If you did this, you need to give current_user, not current_user.id, django handles the matching itself.
Also, I guess you are using django form. If you are using it, I recommend you to use it because you can increase the readability of your code by writing less code.

Django. How to restrict "profile" page to only "friends"

I currently have a "profile" page that displays specific users information they have uploaded. Currently it does so by
objects.filter(user = request.user)
Im trying to figure out how I can allow a, for lack of a better description, a "friend" to view someone else's profile. Cause right now, the user who makes the request gets their own information. I believe I know how to build the ability to "friend" another user... i just dont know how to display another users info since all ive been filtering on so far is "request.user"
You can do this using Many-to-many relationships
You object should look like this
class Profile(models.Model):
friends = models.ManyToManyField(Profile)
To check whether target profile belongs to your friend you can modify your code following way:
Profile.objects.filter(friends = request.user)
I would like to share how I implemented this in a project of mine. This may be somewhat specific for how I have implemented friend relationships, but I think the main idea should be the same.
Here is the view for view_profile
def view_profile(request, username):
if request.user.username == username:
return HttpResponseRedirect(reverse('accounts:profile'))
#get the user we are looking at
person = get_object_or_404(User, username=username)
#get the userprofile
person = person.userprofile
person_friend_object, person_created = Friend.objects.get_or_create(current_user=person)
user_friends = [friend for friend in person_friend_object.users.all()]
follower_count = len(user_friends)
friend = False
context = {
'person':person,
'friend':friend,
'follower_count':follower_count,
'user_friends':user_friends,
}
if request.user.is_authenticated():
friend_object, created = Friend.objects.get_or_create(current_user=request.user.userprofile)
friends = [friend for friend in friend_object.users.all()]
if person in friends:
friend = True
else:
friend = False
context['friend'] = friend
return render(request, 'users/user_profile_view.html', context)
Then, in the template you can control what friend can see of a given user's profile with template logic. Here's a basic example:
{% if not friend %}
<p>You are not friends with this user</p><button>Add friend</button>
{% else %}
<p>You are friends with this user. Here is information about this user...(here you can show data on the user through by accessing the `person` context variable)</p><button>Unfriend</button>
{% endif %}
So everything is controlled by the friend variable which is either True or False.
There are many ways to do what you are describing, this would be just one way I believe. Hope this helps with your project.

How to fetch property in the template Django 1.8?

I want to create functionality where it's clear whether the user liked every fetched post in template or not(so that I just check attribute post.liked which is True or False in for construction)
I suggested that method in models.py might help:
class Post(models.Model):
who_liked = models.ForeignKey('UserProfile', related_name='who_liked_QUESTION', blank=True, null=True)
def _is_it_liked(self, theuser):
if self.who_liked == theuser:
return True
else:
return False
liked_bool = property(_is_it_liked)
But I do not fully understand how should I fetch it then in template, considering that it's a function and I need to insert request.user as argument to the function and call it. Could you please explain how it works since documentation didn't help me much?

Saving data from a modelform Django

Now heads up! I am fresh noob off the NOOB-BUS from NOOBSVILLE!
So i am workin on a form to load up information and edit that form information and im in a headache. so i am using:
Django: 1.8
Pyhton: 3.5.1
backend is sqlite
I am using a form.ModelForm to load information into but when it comes to saving this is where i am stuck. the documentation is very confusing should i use all or just one clean.
this is the forms.py
class EditContact(forms.ModelForm):
class Meta:
model = Contact
#the list of all fields
exclude = ['date_modified']
def clean(self):
if self.date_of_entry is None:
print("looking to see what works")
self.date_of_entry = datetime.date.today()
return
def clean_ContactID(self):
#see this line below this comment i dunno what it does
ContactID= self.cleaned_data.get('ContactID')
print ("cleaning it")
# i also dont know what validation code suppose to look like
# i cant find any working examples of how to clean data
return ContactID
now there are mainly more def clean_methods but i think what i want to use is clean which should use all but in my view.
this is in view.py
def saveContactInfo (request):
#this part i get
if request.user.is_authenticated():
ContactID= request.POST['ContactID']
a = ListofContacts.objects.get(ContactID=ContactID)
f = EditContact(request.POST,instance=a)
print("plz work!")
if f.is_valid():
f.save()
return render (request,"Contactmanager/editContact.html", {'contactID': contactID})
else:
return HttpResponse("something isnt savin")
else:
return HttpResponse("Hello, you shouldnt ")
and this is model.py
def clean(self):
if self.ConactID is None:
raise ValidationError(_('ContactID cant be NULL!'))
if self.date_of_entry is None:
print("think it might call here first?")
self.date_of_entry = datetime.date.today()
print ( self.date_of_entry )
if self.modified_by is not None:
self.modified_by="darnellefornow"
print(self.modified_by )
if self.entered_by is not None:
self.entered_by = "darnellefornow"
print(self.entered_by )
ContactID = self.cleaned_data.get('ContactID')
return
now above the model has the fields and the types which all have blank = true and null = true except for the excluded field date_of_entry
and ive gotten to find out that when calling is_valid() in views it calls the models.clean() but it fails to save!!! and i dont know why! i dont know how to do the validation. i would like to know the process and what is required and even an example of form validation a field.
I think you're wanting info/answers on a couple of things here, looking at your code comments. Hopefully this helps:
1) You only need to use the clean_FIELDNAME functions if you need to handle something custom specifically for that field. The Django docs show this as an example:
def clean_recipients(self):
data = self.cleaned_data['recipients']
if "fred#example.com" not in data:
raise forms.ValidationError("You have forgotten about Fred!")
# Always return the cleaned data, whether you have changed it or
# not.
return data
So in that block, they are checking to see if the email list provided contains a particular email.
2) That also shows another question you asked in your comments about how to handle the validation. You'll see in that snippet above, you could raise a forms.ValidationError. This is discussed more here: https://docs.djangoproject.com/en/1.10/ref/forms/validation/
So, if an error is raised in any of those clean_ methods or in the main clean method, the form.is_valid() will be false.
Does that help?

AnonymousUser problem in Django, Feedback App

user = models.ForeignKey(User,)
I have a user foreignkey in models.py
if request.user.is_authenticated():
feedback.user = request.user
else:
feedback.user = 'something'
In views.py, If user logged in feedback.user area, write username else write something there.
How can I do this in Django.
I was trying to django-feedback and it was like just
feedback.user = request.user
Like this, it was giving the error below.
Cannot assign "<django.contrib.auth.models.AnonymousUser
object at 0x2dbcf50>": "Feedback.user" must be a "User" instance
I am working on localhost. Any idea?
Either require the user to be logged in for the view, or handle it yourself and assign None.

Categories