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.
heres my code:
View.py
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=request.user)
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)
models.py
class UserLikeManager(models.Manager):
def get_all_mutual_likes(self, user, number):
try:
qs = user.liker.liked_users.all().order_by("?")
except:
return []
mutual_users = [][:number]
for other_user in qs:
try:
if other_user.liker.get_mutual_like(user):
mutual_users.append(other_user)
except:
pass
return mutual_users
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
as you can see in my views.py i have an if statement with one elif, however it never seems to pick up on that elif and goes direct to the else, so in my notifications i always get the 'accepted your friend request view' message. I cant seem to fix this issue if anyone can see an faults please let me know.
When i use it in my profile app to display a button showing, confirm friend request it seems to work. here is my code for the profile:
view.py
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
context = {
"do_they_like": do_they_like
}
return render(request, "profiles/profile_view.html", context)
Thanks
Problem in your below line
user = get_object_or_404(User, username=request.user)
Update above with below line
user = get_object_or_404(User, pk=request.user.pk)
Related
I am creating a web application that allows a user to create a todolist where they can add, delete, and edit todo list items (todos). I am using the django framework to do so and I have gotten it to work for the most part. So far, I have implemented adding, editing, and deleting todos from a todolist, I have created a superuser, and I am able to log in to the site using my superuser.
However, I want to let each user have their own unique todolist. I don't want users to see each other's todolists. I am new to python and django and I am not sure how to go about doing this. I have created a test user using the admin site and when I log in using this test user, I am taken to the page with the same (and only) todo list. I have not yet implemented a registration page for new users and I want to be able to link users to their own todolists before I do that. This is what I have so far:
// models.py
class Todo(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
text = models.TextField()
created_at = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
#receiver(post_save, sender=User)
def create_user_todos(sender, instance, created, **kwargs):
if created:
Todo.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_todos(sender, instance, **kwargs):
instance.todo.save()
// views.py
def index(request, user_id):
user = User.objects.get(pk=user_id)
todos = user.todo.objects.all()[:10]
context = {
'todos': todos # to pass them to index.html
}
return render(request, 'index.html', context)
def details(request, id, user_id):
user = User.objects.get(pk=user_id)
todo = user.todo.objects.get(id=id)
context = {
'todo': todo
}
return render(request, 'details.html', context)
def add(request, user_id):
user = User.objects.get(pk=user_id)
if(request.method == 'POST'):
title = request.POST['title']
text = request.POST['text']
todo = user.todo(title=title, text=text)
todo.save()
return redirect('/todos')
else:
return render(request, 'add.html')
def edit(request, id, user_id):
user = User.objects.get(pk=user_id)
todo = user.todo.objects.get(id=id)
context = {
'todo': todo
}
if(request.method == 'POST'):
title = request.POST['title']
text = request.POST['text']
if len(str(title)) != 0:
todo.title = title
if len(str(text)) != 0:
todo.text = text
todo.save()
return redirect('/todos')
else:
return render(request, 'edit.html', context)
def delete(request, id, user_id):
user = User.objects.get(pk=user_id)
todo = user.todo.objects.get(id=id)
context = {
'todo': todo
}
if(request.method == 'POST'):
Todo.delete(todo)
return redirect('/todos')
else:
return render(request, 'delete.html', context)
I was following a tutorial beforehand where I added the extra parameter user_id to all my functions in views.py. It is giving me an error now but if I don't include the paramter and change my implementation of the functions to be
todo = Todo.objects.get(id=id)
then everything works.
I realize my question is vague and I have tried searching for solutions but everything I have read assumes I have some previous in depth knowledge of django (which I don't). Please lead me in the right direction :)
I am trying to check if user is logged in from my views.py file. As depending if user is logged in it should return me different forms. But request.user.is_authenticated() or request.user.is_authenticated is not working, i always get True value.
My view:
def ContactsView(request):
form_class = ContactForm_logged(request=request)
form_class_nonlogged = ContactForm_nonlogged(request=request)
# new logic!
if request.method == 'POST':
if request.user.is_authenticated():
form = ContactForm_logged(data=request.POST, request = request)
else:
form = ContactForm_nonlogged(data=request.POST)
if form.is_valid():
contact_name = request.POST.get(
'contact_name'
, '')
contact_email = request.POST.get(
'contact_email'
, '')
form_content = request.POST.get('content', '')
subjects = form.cleaned_data['subjects']
subjects = dict(form.fields['subjects'].choices)[subjects]
# Email the profile with the
# contact information
template = get_template('threeD/email/contact_template.txt')
context = Context({
'contact_name': contact_name,
'subjects': subjects,
'contact_email': contact_email,
'form_content': form_content,
})
content = template.render(context)
email = EmailMessage(
"New message from " + contact_name,
content,
"Message - " + subjects + ' ',
['smart.3d.printing.facility#gmail.com'],
headers={'Reply-To': contact_email}
)
email.send()
messages.success(request, "Thank you for your message.")
return redirect('/index/contacts/')
else:
if request.user.is_authenticated():
form = ContactForm_logged(request=request)
else:
form = ContactForm_nonlogged()
if request.user.is_authenticated():
return render(request, 'threeD/contacts.html', {
'form': form_class,
})
else:
return render(request, 'threeD/contacts.html', {
'form': form_class_nonlogged,
})
And two of my forms:
class ContactForm_logged(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
subjects = forms.ChoiceField(choices=emailsubjects)
content = forms.CharField(
required=True,
widget=forms.Textarea
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(ContactForm_logged, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Your name:"
if (self.request.user.first_name == '' or self.request.user.last_name ==''):
self.fields['contact_name'].initial = 'Type your name here'
self.fields['contact_name'].widget.attrs['readonly'] = False
else:
self.fields['contact_name'].initial = self.request.user.first_name
self.fields['contact_name'].widget.attrs['readonly'] = True
self.fields['contact_email'].label = "Your email:"
if (self.request.user.profile.sdu_email == ''):
if (self.request.user.email == ''):
self.fields['contact_email'].initial = 'Type your email here'
self.fields['contact_email'].widget.attrs['readonly'] = False
else:
self.fields['contact_email'].initial = self.request.user.email
self.fields['contact_email'].widget.attrs['readonly'] = True
else:
self.fields['contact_email'].initial = self.request.user.profile.sdu_email
self.fields['contact_email'].widget.attrs['readonly'] = True
self.fields['content'].label = "What do you want to say?"
self.fields['content'].initial = "Dear, Smart 3D printing facility team, I like this WEB server very much, but ..."
self.fields['subjects'].label = "Please, select the subject of your message"
class ContactForm_nonlogged(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
subjects = forms.ChoiceField(choices=emailsubjects)
content = forms.CharField(
required=True,
widget=forms.Textarea
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(ContactForm_nonlogged, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Your name:"
self.fields['contact_name'].initial = 'Type your name here'
self.fields['contact_email'].label = "Your email:"
self.fields['contact_email'].initial = 'Type your email here'
self.fields['content'].label = "What do you want to say?"
self.fields['content'].initial = "Dear, Smart 3D printing facility team, I like this WEB server very much, but ..."
self.fields['subjects'].label = "Please, select the subject of your message"
The problem is that, whether i am logged in or am not i always get ContactForm_logged form back. And if i m not logged in than, getting ContactForm_logged form back i get an error, that "'AnonymousUser' object has no attribute 'first_name'".
I read on forums that that could have happened if i call request.user.is_authenticated() wrong, but i have tried both request.user.is_authenticated() and request.user.is_authenticated, both give me the same error :/
Any help would be greatly appreciated!
If you are using Django 1.10+, then you should use the property request.user.is_authenticated.
If you are using Django 1.9 or earlier, then you must use request.user.is_authenticated(). Using request.user.is_authenticated in Django 1.9 or earlier is a mistake which can cause sensitive data to be leaked, because it will always be evaluated as True.
If you are using the correct version and it is returning True, then that suggests you really are logged in.
The problem is in the first line of your view method definition:
def ContactsView(request):
form_class = ContactForm_logged(request=request)
Here you are creating an instance of ContactForm_logged class. This line will be executed every time the view method is called. So an instance of ContactForm_logged class will be created everytime, whether user is logged-in or not. Further, in the __init__ method of ContactForm_logged class you are accessing self.request.user.first_name. So when the ContactForm_logged instance is being initialized for unauthenticated requests it is raising the error: "'AnonymousUser' object has no attribute 'first_name'"
hi i a working on a project for that i have made login and registration of a user. now i want to show full profile of user.since get_profile is not working anymore so how can i get full profile of a user
my models.py
class Consultants(models.Model):
consul_id=models.IntegerField(default=0,primary_key=True)
first_name=models.CharField(max_length=255,blank=True,null=True)
last_name=models.CharField(max_length=255,blank=True,null=True)
email=models.EmailField(max_length=255,blank=True,null=True)
username=models.CharField(max_length=255,blank=True,null=True)
password=models.CharField(max_length=50,blank=True,null=True)
last_login=models.DateTimeField(default=datetime.now,blank=True,null=True)
is_active=models.BooleanField(default=False)
def __str__(self):
return self.first_name
views.py for login and registration
def register(request):
context = RequestContext(request)
registered = False
if request.method == 'POST':
# user_form = UserForm(data=request.POST)
consultant_form = ConsultantsForm(data=request.POST)
if consultant_form.is_valid():
consultant = consultant_form.save(commit=False)
consultant.save()
registered = True
else:
print consultant_form.errors
else:
consultant_form = ConsultantsForm()
return render_to_response(
'register.html',
{'consultant_form': consultant_form, 'registered': registered},
context_instance=RequestContext(request))
def login_user(request):
context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
print type(username)
print "username",username
try:
user = Consultants.objects.get(Q(username= username) & Q(password= password))
print 'chala'
if user.is_active:
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
return HttpResponse("welcome......you are succesfuly log in")
else:
return HttpResponse("Your UkKonnect account is disabled.")
except ObjectDoesNotExist:
return HttpResponse("INvalid User")
else:
return render_to_response('login.html', {}, context)
i want to make def full_profile and def edit_profile.
How can i get logged in user consul_id??
please help me
Not sure that I understand you problem well.. Take a look at recommended way of extending User model:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
from django.contrib.auth.models import User
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
Then you can do:
u = User.objects.get(username='fsmith')
freds_department = u.employee.department
In your case it would be:
class Consultant(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
*your fields here*
Now you can use standard authentication forms and methods
You always can obtain consultant data as:
request.user.consultant
I am having trouble having my form validate in Django and I really dont know what the problem is. It is a messaging application and I am trying to have the user sending the message be automatically populated with the user that is logged in. I have tried a lot of things but none of them have worked. Any help would be appreciated. Here is my models.py: (anything commented out is previous attempts at a solution)
class Message(models.Model):
#readonly_fields = 'sender'
sender = models.ForeignKey(User, related_name="send", default=User)
recipient = models.ForeignKey(User, related_name="receive", default=None)
message_subject = models.CharField("Subject", max_length=25)
message_text = models.TextField("Message")
message_time_created = models.DateTimeField(auto_now_add=True)
urgent = models.CharField(max_length=3, choices=URGENCY)
#field to make message urgent or not
def __str__(self):
return self.message_subject
here is the views.py for creating a new message: (anything commented out is previous attempts at a solution)(also includes#login_required tag that wouldnt show up when pasting)
def newMessage(request, user):
user = get_object_or_404(User, pk=user)
#form = MessageForm(request.POST or None, initial={'sender':request.POST.get('username')})
if request.method == 'POST':
#instance = Message(sender=request.user)
#form = MessageForm(instance=instance)
#form = MessageForm(initial={'sender':request.user})
form = MessageForm(request.POST)
if form.is_valid():
new_instance = form.save()
temp = Event(activity='\n' + new_instance.sender.get_full_name() + " sent a message to " + new_instance.recipient.get_full_name())
temp.save()
try:
target = Patient.objects.get(user=user)
return HttpResponseRedirect('/patients/%s/' % target.id)
except Exception as e:
try:
target = Nurse.objects.get(user=user)
return HttpResponseRedirect('/nurses/%s/' % target.id)
except Exception as e:
try:
target = Doctor.objects.get(user=user)
return HttpResponseRedirect('/doctors/%s/' % target.id)
except Exception as e:
try:
target = HospitalAdmin.objects.get(user=user)
return HttpResponseRedirect('/hospitalAdmins/%s/' % target.id)
except Exception as e:
return render(request, "main_site/newMessagePrompt.html",
{ "form" : form, })
elif request.method == 'GET':
form = MessageForm()
return render(request, "main_site/newMessagePrompt.html",
{ "form" : form, })
Here is the form:(anything commented out is previous attempts at a solution)
class MessageForm(ModelForm):
#readonly_fields = 'sender'
urgent = forms.ChoiceField(choices=URGENCY, required=True)
class Meta:
model = Message
#widgets = {'sender': forms.HiddenInput()}
exclude =['message_time_created']
Currently, with giving the sender a default=User in the model, which does auto-populate with the user who is logged in, and if you try to send the message it will work. However the field can still be edited, which is not intentional. If i try to make the field editable=False in the model.py, and then try to send the message, it will give an error. If i try other ways to hide this, such as HiddenInput in the form, the form will not validate. Similar results have occurred when trying to use an instance variable. I have also tried to make the sender field be a read only field but have not succesffully been able to implement it to see if it would work. I really cannot figure out how to fix this problem. Can anyone help me out with this?
I'm trying to learn the Peewee ORM in combination with Flask by following the Flask Mega Tutorial. In part 5 of the tutorial I create a login using OpenID. After overcoming a bunch of hurdles already I now get an AttributeError in the function pasted below on the following line: login_user(user, remember = remember_me).
#oid.after_login
def after_login(resp):
if resp.email is None or resp.email == "":
flash('Invalid login. Please try again.')
return redirect(url_for('login'))
user = User.select().where(User.email == resp.email)
if user.wrapped_count() == 0:
nickname = resp.nickname
if nickname is None or nickname == "":
nickname = resp.email.split('#')[0]
user = User(nickname = nickname, email = resp.email, role = models.ROLE_USER)
user.save()
remember_me = False
if 'remember_me' in session:
remember_me = session['remember_me']
session.pop('remember_me', None)
login_user(user, remember = remember_me)
return redirect(request.args.get('next') or url_for('index'))
is_active is found in my User model as follows:
class User(db.Model):
nickname = TextField()
email = TextField()
role = IntegerField(default = ROLE_USER)
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return self.id
def __repr__(self):
return '<User %r>' % (self.nickname)
I have no clue what I'm doing wrong here though. Could anybody give me a helping hand in what I'm doing wrong here?
All tips are welcome!
As the error suggests, user = User.select().where(User.email == resp.email) gives you back a SelectQuery, not an instance of User. You'll want to include an additional method call to actually fetch the record, something like .first(). first will return either an instance of User or None.
This would allow you to slightly adjust your code:
user = User.select().where(User.email == resp.email).first()
if not user: # or if user is None:
nickname = resp.nickname
...