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.