Reputation: 269
i having a problem in appending some string into a list in database please help me
here is my models.py
class friendList(models.TextField):
myFriend = []
class friend(models.Model):
username = models.CharField(max_length="30")
friends = friendList().myFriend
and this is view.py
def addfriend(request):
try:
user = request.session['user']
if request.method == 'POST':
friend.objects.filter(username = user.username)[0].friends.append(request.POST['user_name'])
return HttpResponse("ok he/she is your friend now!!")
except:
return render(request, 'login.html', {'error':"you are not logged in"})
Upvotes: 0
Views: 51
Reputation: 174624
You need to fix your models. Since a friend can have many friends, each of which is an object of type Friend
, you can add a ForeignKey
to the same model:
class Friend(models.Model):
username = models.CharField(max_length="30")
friends = models.ForeignKey('self')
The convention in Python is to have InitialCaps (also called CamelCase) for class names
Now, in your view:
from django.contrib import messages
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
@login_required
def addfriend(request):
if request.method == 'POST':
the_user = Friend.objects.get(username=request.user.username)
the_friend = Friend.objects.get(username=request.POST['user_name'])
the_user.friends_set.add(the_friend)
messages.add_message(request, messages.INFO, 'Friend added!')
return redirect('/index')
else:
messages.add_message(request, messages.ERROR, 'No friend selected!')
return redirect('/index')
For POST
requests, you should always redirect. Here I am using the redirect
shortcut to redirect the user back to the index page (you can change the URL to redirect them to anywhere else).
Django provides a messages framework which I am using to display messages to the user; the documentation will show you how to add code to your templates to show the messages.
Finally, the login_required
decorator is a way to make sure that a view is only accessible if a user is logged in. It is part of the built-in authentication framework.
Upvotes: 2