Python For循环不起作用

时间:2018-03-30 02:25:24

标签: python html django for-loop views

我的django应用程序中的for循环出现问题。我试图让它显示已登录“可能成为朋友的用户”的其他用户但没有显示任何内容。我确定我的应用程序将在我修复后运行。我不确定它是否是我的观点,但我对于我应该对这个问题做什么感到失望

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>

查看:

# -*- 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')

型号:

# -*- 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 个答案:

答案 0 :(得分:1)

您发送的上下文对象格式不正确。 dict的键应该是您在模板中使用的名称来迭代值。

尝试使用此更新功能修改您的视图:

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

然后,在您的模板中,修改for循环:friends(复数)与friend(单数)不匹配

            {% 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 %}

顺便说一句,如果用id=id查询数据库(显然你在这里),你会收到几个对象,你可能遇到的问题比你想象的要大;)