0

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"})
2
  • I think that all your friend instances ('friend' must be uppercase) are sharing class variable myFirned of fieldList class. Commented Jul 3, 2013 at 12:14
  • i used this print friend.objects.filter(username = user.username)[0].friends before return HttpResponse and it was ok but in my db it wont saved Commented Jul 3, 2013 at 12:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.