MultiValueDictKeyError / создать проверку Django - PullRequest
0 голосов
/ 26 апреля 2018

Я столкнулся с проблемой проверки моих проверок. Я пытаюсь убедиться, что это поле нельзя оставить пустым в поле страницы. Когда я нажимаю на страницу, я сталкиваюсь с MultiValueDictKeyError. Это приводит меня к строке 61 моих взглядов.

if len(postData["recipe_name"])< 1:

и 66 моих моделей

if len(postData["recipe_name"])<1:

вот остальная часть кода для контекста:

html
<DOCTYPE html>
    <head
            <a href="/home">Home</a>||<a href="/logout">Logout</a>
    </head>
    <body>
        <h1>Add a New Recipe</h1>
        <form action="/create" method="POST">
            {% csrf_token %}
            {% if messages %}
            <ul class="messages">
                {% for message in messages %}
                <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
                {% endfor %}
            </ul>
            {% endif %}
        <label for="recipe_name">
        <p>Recipe Name: </p> <input type="text">
        </label>
        <label for="instructions">
        <p>Instructions:</p><textarea name="" id="" cols="30" rows="10"></textarea>
    </label>
    <label for="vegetarian">
        <p>Vegetarian:(Y/N)</p> <input type="text">
    </label>
    <label for="price">
        <p>Price:</p> <input type="text">
    </label>
        <button type="submit">Add Recipe</button>
    </body>
</form>
</DOCTYPE>>

модель

# -*- 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 RecipeManage(models.Manager):
    def rvalidate(self,postData):
        errors={}
        if len(postData["recipe_name"])<1:
            errors["Recipe name too short try something longer"]="recipe_name"
        if len(postData["recipe_name"])>20:
            errors["Recipe name too long"]="recipe_name"
        if len(postData["instructions"])<1:
            errors["Instruction field must not be left blank"]="instructions"
        if len(postData["instructions"])>65:
            errors["Instruction is too long be more consice"]="instructions"
        if len(postData["vegetarian"])<1:
            errors["Vegetarian field must be filled out"]="vegetarian"
        if len(postData["price"])<1:
            errors["Price field must be field out"]="price"
        if len(postData["price"])>15:
            errors["Price field to large ."]="price"
        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)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    timesliked=models.IntegerField(default=0)
    objects = UserManage()
class Recipe(models.Model):
    recipe_name=models.CharField(max_length=20)
    instructions=models.CharField(max_length=65)
    vegetarian=models.CharField(max_length=1)
    price=models.CharField(max_length=55)
    key=models.ForeignKey(User,related_name="cookbook")
    liker=models.ForeignKey(User,related_name="likebutton")
    likee=models.ForeignKey(User,related_name="liked")
    objects=RecipeManage()

вид

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

# Create your views here.
def index(request):            
    return render(request,'index.html')
def home(request):
    current_user = User.objects.get(id=request.session['user_id'])
    chef=Recipe.objects.filter(key=current_user)
    otherchef=Recipe.objects.exclude(id=request.session['user_id'])
    context={
    'user':current_user,
    'chef':chef,
    'otherchef':otherchef,
    }
    return render(request,"homepage.html",context)

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 add(request):
    return render(request,"add.html")
def create(request):
    errors=Recipe.objects.rvalidate(request.POST)
    if len(errors)>0:
        for error in errors:
            messages.error(request,error)
        return redirect("/add")
    else:
        users = User.objects.get(id = request.session['user_id'])
        Recipe.objects.create(
            users=users,
            recipe_name=request.POST["recipe_name"],
            instructions=request.POST["instructions"],
            vegetarian=request.POST["vegetarian"],
            price=request.POST["price"],
        )
        print "creating"
        return redirect("/home")
def profile(request,id):
    profile=Recipe.objects.get(id=id)
    context={
        'profile':profile
    }
    return render(request,"profile.html",context)
def join(request,id):
    current_user = User.objects.get(id = request.session['user_id'])
    target_user=User.objects.get(id=id)
    possible_like=Recipe.objects.filter(target=target_user,liker=current_user)
    if len(possible_like)==0:
        Recipe.objects.create(
            liker=current_user,
            target=target_user,
            like=1,
        )
    else:
        possible_like[0].like+=1
        possible_like[0].save()
    target_user.timesliked+=1
    target_user.save()
    return redirect('/home')

1 Ответ

0 голосов
/ 26 апреля 2018

Используйте метод dict.get в rvalidate

Ex:

def rvalidate(self, postData):
    errors = {}
    if len(postData.get("recipe_name", [])) < 1:
        errors["Recipe name too short try something longer"] = "recipe_name"
    if len(postData.get("recipe_name", [])) > 20:
        errors["Recipe name too long"] = "recipe_name"
    if len(postData.get("instructions", [])) < 1:
        errors["Instruction field must not be left blank"] = "instructions"
    if len(postData.get("instructions", [])) > 65:
        errors["Instruction is too long be more consice"] = "instructions"
    if len(postData.get("vegetarian", [])) < 1:
        errors["Vegetarian field must be filled out"] = "vegetarian"
    if len(postData.get("price", [])) < 1:
        errors["Price field must be field out"] = "price"
    if len(postData.get("price", [])) > 15:
        errors["Price field to large ."] = "price"
    return errors
...