0

I'm having problems with my for loop in my django application. I'm trying to get it to show other users that have logged under "Users who could be friends" But nothing is showing. I'm sure my app will work once I get this fixed. I'm not sure if its my views but I am at a lose as to what I should do about this problem

template
<!DOCTYPE html>
<html>
    <head>
        <a href="/logout">Logout</a>
        <form action="/success" method="GET">
            {% csrf_token %}
        <h1>Welcome! {{request.session.name}}</h1>
        <h2>Here is a list of your friends!</h2>
    </head>
    <body>
       <table>
        <thead>
           <th>Name</th>
           <th>Action</th>
        </thead>
        <tbody>
            <tr>
                {%for friends in friend%}
                <td><a href="show/{{friends.id}}">View Profile</a></td>
                <td><a href="remove/{{friends.id}}">Remove Friend</a></td>
                {%endfor%}
            </tr>
        </tbody>

       </table> 

    </body>
    <footer>
        <p>Other People who coudl be friends</p>
        <table>
            <thead>
                <th>Name</th>
                <th>Action</th>
            </thead>
            <tbody>
                <tr>
                    {%for friends in extra%}
                    <td><a href="show/{{friends.id}}"></a></td>
                    <td><a href="join/{{friends.id}}">Add a Friend</a></td>
                    {%endfor%}

                </tr>
            </form>
            </tbody>
        </table>
    </footer>

Views:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from .models import User
from .models import Friend
from django.contrib import messages
import bcrypt

# Create your views here.
def index(request):            
            return render(request,'index.html')

def register(request):
    errors = User.objects.validate(request.POST)
    #print 'this process works', request.POST
    if len(errors) > 0:
        for error in errors:
            messages.error(request, error)
        return redirect("/")

    else:
        hashpwd = bcrypt.hashpw(request.POST["password"].encode(), bcrypt.gensalt())
        newuser = User.objects.create(
            first_name=request.POST['first_name'],
            last_name=request.POST['last_name'],
            email=request.POST['email'],
            password=hashpwd)

        request.session['user_id'] = newuser.id
        request.session['name'] = newuser.first_name
        print "session info", newuser.id, newuser.first_name
        return redirect("/success")

def login(request):
    errors = User.objects.loginvalidate(request.POST)
    if len(errors) > 0:
        for error in errors:
            messages.error(request, error)
        return redirect("/")
    else:
        user = User.objects.filter(email=request.POST['email'])[0]
        request.session['user_id'] = user.id
        request.session['name'] = user.first_name
        return redirect("/home")



def success(request):
    current_user = User.objects.get(id=request.session['user_id'])
    return render(request,"dashboard.html")

def home(request):
    user=User.objects.filter(id=request.session['user_id'])
    friends=Friend.objects.filter(key=request.session['user_id'])
    extra=Friend.objects.exclude(id=request.session['user_id'])
    context={
    'user':user[0],
    'friend':friends,
    'extra':extra,
    }
    return render(request,"dashboard.html",context)

def logout(request):
    request.session.clear()
    #print 'goodbye'
    return redirect('/') 

def show(request,id):
    friends=Friend.objects.get(id=id)
    print 'show'
    context={
        'show':friends
    }
    return render(request,"show.html",context)
def remove(request):
    users = User.objects.filter(id = request.session['user_id'])
    print "delete"
    return('/home')

def makefriend(request):
    print "friending"
    users = User.objects.get(id = request.session['user_id'])
    friend = Friend.objects.get(id=id)
    print "printing friends",friend
    friend.joined.add(users)
    friend.save()
    print "printing joined friend", Friend.joined
    return redirect ('/home')

Models:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
import bcrypt
import re
from datetime import *
import datetime

EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
NAME_REGEX = re.compile(r'^[aA-zZ\s]+$')

# Create your models here.



class UserManage(models.Manager):
    def validate(self, postData):
        errors = {}
        if len(postData['first_name']) < 2:
            errors["First name field can be left blank"]="first_name"
        elif not NAME_REGEX.match(postData['first_name']):
            errors["This is not a valid first name. Try again."]="first_name"

        if len(postData['last_name']) < 2:
            errors["Last name cannot be left blank"]="last_name"

        elif not NAME_REGEX.match(postData['last_name']):
            errors["This is not a valid last name. Try again."]="last_name"


        if len(postData['email']) < 1:
            errors["Email cannot be left blank"]="email"

        elif not EMAIL_REGEX.match(postData['email']):
            errors["this is not a valid email try again"]="email"

        if (User.objects.filter(email=postData['email'])):
            errors['Email already in use']="email"
        print postData["email"]


        if len(postData['password']) < 8:
            errors["Passwords must at least 8 characters"]="password"

        if postData["password"] != postData["cpassword"]:
            errors["Passwords do not match"]="cpassword"
        return errors

    def loginvalidate(self, postData):
        errors = {}
        if len(postData['email'])<1:
            errors["Email field can not be blank"] = "email"

        if len(postData["password"])<8:
            errors["Password must be at least 8 characters" ] = "password"

        if len(self.filter(email=postData['email']))>0:
            #print 'TRUE for emails'
            currentuser =self.filter(email=postData['email'])[0]
            existingpwd = currentuser.password

            if not bcrypt.checkpw(postData["password"].encode(), existingpwd.encode()):
                    errors["Password does not match"] = "password"
        else:
            errors["Email does not match"] = "email" 
        return errors

class User(models.Model):
    first_name = models.CharField(max_length=45)
    last_name = models.CharField(max_length=45)
    email = models.CharField(max_length=45)
    password = models.CharField(max_length=45)
    birthdate = models.DateField(auto_now=True)
    objects = UserManage()
class Friend(models.Model):
    key=  models.ForeignKey(User,related_name="name")
    joined=models.ManyToManyField(User,related_name="social")
    objects= UserManage()
1

1 Answer 1

1

The context object you're sending is not properly formated. The key of the dict should be the name you use in the template to iterate over the values.

Try modifying your view with this updated function:

def show(request, id):
    friends = Friend.objects.get(id=id)
    print 'show'
    context={
        'friends': friends
    }
    return render(request, "show.html", context)

Then, in your template, modify the for loop: you mismatched friends (plural) with friend (singular)

            {% for friend in friends %}
                <td><a href="show/{{friend.id}}">View Profile</a></td>
                <td><a href="remove/{{friend.id}}">Remove Friend</a></td>
            {% endfor %}

BTW, if when querying your database with id=id (as you do here apparently) you receive several objects, you probably have a problem bigger than you think ;)

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

1 Comment

What I mean in the conclusion is that id should always be unique for a given table, thus your variable friends should always contain one (and only one) item. If you want all the items, you may write friends = Friend.objects.all() and then you'll have a list of all your friend instances in the Friend table. But that's a different topic ;-)

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.