预期的字符串或缓冲区Django

时间:2018-05-03 00:54:49

标签: python django string syntax-error buffer

我在申请时碰到了墙。我可以登录我的主页,但我遇到了“预期的强大或缓冲”。我在我的观点第16行找到了错误

today=Appointment.objects.order_by('date').filter(date=now,user=user)

我做了很多事来解决这个问题无济于事。 的观点:

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

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

def home(request):
    now=datetime.now().strftime("%Y-%m-%d"),
    user =User.objects.get(id=request.session['user_id'])
    today=Appointment.objects.order_by('date').filter(date=now,user=user)
    laterdate=Appointment.objects.order_by('date').filter(user=user).exclude(date=now)
    context={
    'user':user,
    'laterdate':laterdate,
    'today':today,
    }
    return render(request,"welcome.html",context,now)

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("/home")

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 logout(request):
    request.session.clear()
    print 'goodbye'
    return redirect('/')
def delete(request,id):
    Appointment.objects.get(id=id).delete()
    return redirect('/home')

def edit(request):
    appointment=Appointment.objects.get(id=id)
    context={
        'edit':appointment
    }
    return render(request,"update.html",context)

def create(request):
    errors=Appointment.objects.appointvalidate(request.POST)
    if len(errors)>0:
        for error in errors:
            messages.error(request,error)
        return redirect("/home")
    else:
        users = User.objects.get(id = request.session['user_id'])
        Appointment.objects.create(
           task=request.POST["task"],
           time=request.POST["time"],
           date=request.POST["date"],
           status="pending",
           key=users,
        )
        return redirect("/home")

def update(request,id):
    errors=Appointment.objects.appointvalidate(request.POST)
    if errors['status']==True:
        update=Appointment.objects.get(id=id)
        update.task=request.POST['task']
        update.time=request.POST['time']
        update.date=request.POST['date']
        update.status=request.POST['status']
        update.save()
        return redirect("/home")
    else:
        for error in errors:
            messages.error(request,error)
        return redirect("/update")   

型号:

    # -*- 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 AppointmentManage(models.Manager):
        def appointvalidate(self,postData):
            errors={}
            if len(postData['task'])<2:
                errors["Task field cannot be left blank"]="task"
            if len(postData['task'])<20:
                errors["Task field is too long"]="task"
            if len(postData['date'])<1:
                errors["Date field cannot be left blank"]="date"
            else:
                pause=datetime.strptime(time,"%Y-%m-%d %H:%M")
                if pause< datetime.now():
                    errors["Only present and future dates are permissable"]="date"
            if len(postData['time'])<1:
                errors["Time field cannot be left blank"]="time"
            return errors

        def sorter(self):
            return (self.all().order_by('-date'))

    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 Appointment(models.Model):
        date=models.DateField(auto_now=True)
        status=models.CharField(max_length=20)
        time=models.TimeField()
        task=models.CharField(max_length=20)
        key=models.ForeignKey(User,related_name="other")
        objects=AppointmentManage()
        def current_day(self):
            # return date.today().strftime("%Y-%m-%d") == self.date
            return {'date': datetime.now()}

Html页面:

    <DOCTYPE html>
        <html>
            <head> <link rel="stylesheet" type="text/css" href="style.css">
                {% load static %}
             </head><body>
    <h1>Welcome{{request.session.name}} </h1>
    <a href="/logout"><button>logout</button></a>
    <h1>Here are your

 appointments for {{request.session.datetime}}</h1>
    <table>
        <thead><th>Task</th><th>Date</th><th>Time</th> <th>Status</th> <th>Actions</th></thead>
        {%for meeting in today%}
        <tr><td>{{meeting.task}}</td><td>{{meeting.date}}</td><td>{{meeting.time}}</td><td>{{meeting.status}}</td><td><a href="/edit"><button>Edit</button></a></td><td><a href="/delete"><button>Delete</button></a></td></tr>
        {%endfor%}
    </table>

<p>Other appointments</p>
<table>
    <thead><th>Task</th><th>Date</th><th>Time</th></thead>
    {%for meeting in laterdate%}
    <tr><td>{{meeting.task}}</td><td>{{meeting.date}}</td><td>{{meeting.time}}</td></tr>
    {%endfor%}
</table>

<h2>Add a new Appointment</h2>
<form action="/create" method="POST">
{% csrf_token %} 
<label for="task">
<p>Task:</p> <input type="text" name="task">
</label>
<label for="time">
<p>Time:</p><input type="time" name="time" id="">
</label>
<label for="date">
<p>Date</p><input type="date" name="date" id="">
</label>
<button type="submit">Submit</button>
<br>
{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
</form>
</body>

1 个答案:

答案 0 :(得分:0)

尝试:

from datetime import datetime
today=Appointment.objects.order_by('date').filter(date=datetime.today(), user=user)