Django表单 - 我的图像无效

时间:2017-10-08 07:11:59

标签: python django

Django表单 - 我的图像无效

这太烦人了。我正在尝试使用&#34; ImageField()&#34; 和django的内置< strong> &#34;来自django.contrib.auth.models导入用户 &#34;,但我的图片始终无法通过 &# 34; is_valid()&#34; 即可。请帮帮我。

PS。忽略RECAPTCHA位。它与bug无关。相信并相信我。

这是我的views.py

import json
import urllib
import PIL

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout
from django.views.generic import View
from .forms import UserForm, UserProfileForm
from django.conf import settings

def log_out(request):
    logout(request)
    form = UserProfileForm(request.POST or None)
    return redirect("/", request)

def login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth_login(request, user)
                return redirect("/", username=request.user.username, is_active=request.user.is_active)
            else:
                return render(request, 'Index/login.html', {'Error_Message': 'Your account has been disabled'.upper()})
        else:
            return render(request, 'Index/login.html', {'Error_Message': 'Invalid log in'.upper()})
    return render(request, 'Index/login.html', {"username": request.user.username})

def register(request):
    Form1 = UserForm(request.POST or None)
    Form2 = UserProfileForm(request.POST or None and request.FILES or None)

    if request.method == "POST":

        recaptcha_response = request.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response,
        }
        data = urllib.parse.urlencode(values).encode()
        req =  urllib.request.Request(url, data=data)
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())

        if result['success']:
            if Form1.is_valid():
                User1 = Form1.save(commit=False)

                username = Form1.cleaned_data["username"]
                email = Form1.cleaned_data["email"]
                password = Form1.cleaned_data["password"]
                User1.save()

                User1 = authenticate(username=username, email=email, password=password)

                if User1 is not None:
                    if User1.is_active:
                        auth_login(request, User1)
                        return redirect("/", request)
                    else:
                        return render(request, 'Index/login.html', {'Error_Message': 'Your account has been disabled'.upper()})

            else:
                return render(request, 'Index/register.html', {'Error_Message': 'Invalid sign up'.upper()})

            if Form2.is_valid():
                User2 = Form2.save(commit=False)

                logo = request.FILES["logo"]
                user = User1
                User2.save()

            else:
                return render(request, 'Index/register.html', {'Error_Message': 'Invalid logo'.upper()})

        else:
            return render(request, 'Index/register.html', {'Error_Message': a.upper() for a in result['error-codes']})

    return render(request, "Index/register.html", {"is_active": request.user.is_active, "username": request.user.username})

这是我的forms.py

from django import forms
from django.contrib.auth.models import User
from .models import UserProfile

class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["username", "email", "password"]

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ["logo"]

my models.py

from django.db import models
from django.contrib.auth.models import User


# Create your models here.
class UserProfile(models.Model):
    logo = models.ImageField(upload_to="logos/")
    user = models.OneToOneField(User, on_delete=models.CASCADE)

我的HTML

{% extends "Index/base.html" %}
<!DOCTYPE html>
<html>
<head>
    {% block head %}
    <title>
        REGISTER
    </title>
    {% endblock %}
</head>
<body>
    {% block title %}
    <h1 id="h1b">
        GreatestNinja Sign Up
    </h1>
    {% endblock %}
    {% block body %}
    <div class="container">
        {% if Error_Message %}
        <div class="alert alert-danger alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <strong >Warning!</strong><h4 style="text-align: center;"><strong>{{ Error_Message }}</strong></h4>
        </div>
        {% endif %}
        <form class="form-horizontal" action="/register/" method="post" enctype="multipart/form-data">
            {% csrf_token %} 
            <img src="#" id="logoImage" style="display: block; margin: 0 auto">
            <div class="input-group">
                <span class="input-group-addon" id="LogoDescribe">Logo:</span>
                <input type="file" accept="image/*" class="form-control" aria-describedby="LogoDescribe" name="logo" onchange="DisplayImage(this);">
            </div>
            <div class="input-group">
                <span class="input-group-addon" id="UsernameDescribe">Username:</span>
                <input type="text" class="form-control" aria-describedby="UsernameDescribe" placeholder="DonaldTrump" autocomplete="off" name="username" value="">
            </div>
            <div class="input-group">
                <span class="input-group-addon" id="EmailDescribe">Email:</span>
                <input type="email" class="form-control" aria-describedby="EmailDescribe" placeholder="email@gmail.com" autocomplete="off" name="email" value="">
            </div>
            <div class="input-group">
                <span class="input-group-addon" id="PasswordDescribe">Password:</span>
                <input type="password" class="form-control" aria-describedby="PasswordDescribe" placeholder="P@ssw0rd" autocomplete="off" name="password" value="">
            </div>
            <div class="g-recaptcha" data-sitekey="6LcDyDIUAAAAANjE4F6ckiCwiDLFvwWjEg-LTKHn" align="center"></div>
            <div>
                <button type="submit" style="width: 100%" class="btn btn-success">Submit</button>
            </div>
        </form>
    </div>
    <script>
        function DisplayImage(input) {
            if (input.files && input.files[0]) {
                var ImageReader = new FileReader();

                ImageReader.onload = function (e) {
                    $('#logoImage')
                        .attr("src", e.target.result)
                        .width(100)
                        .height(100);
                };

                ImageReader.readAsDataURL(input.files[0]);
            }
        }
    </script>
    {% endblock %}
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我解决了问题,我在views.py中的解决方案是:

import json
import urllib

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout
from django.views.generic import View
from django.conf import settings
from .forms import UserForm, UserProfileForm
from .models import UserProfile
from django.contrib.auth.models import User


def index(request):
    return render(request, 'Index/index.html')


def calculator(request):
    return render(request, 'Index/calculator.html')

def snake(request):
    return render(request, 'Index/snake.html')

def youtube(request):
    return render(request, 'Index/youtube.html')

def scratch(request):
    return render(request, 'Index/scratch.html')


def log_out(request):
    logout(request)
    form = UserProfileForm(request.POST)
    return redirect("/", request)

def login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth_login(request, user)
                return redirect("/", username=request.user.username, is_active=request.user.is_active)
            else:
                return render(request, 'Index/login.html', {'Error_Message': 'Your account has been disabled'.upper()})
        else:
            return render(request, 'Index/login.html', {'Error_Message': 'Invalid log in'.upper()})
    return render(request, 'Index/login.html', {"username": request.user.username})

def register(request):
    Form1 = UserForm(request.POST)
    Form2 = UserProfileForm(request.POST, request.FILES)

    if request.method == "POST":

        recaptcha_response = request.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response,
        }
        data = urllib.parse.urlencode(values).encode()
        req =  urllib.request.Request(url, data=data)
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())

        if result['success']:

            if Form1.is_valid():
                User1 = Form1.save(commit=False)

                username = Form1.cleaned_data["username"]
                email = Form1.cleaned_data["email"]
                password = Form1.cleaned_data["password"]
                User1.set_password(password)
                User1.save()

                User1 = authenticate(username=username, email=email, password=password)

                if User1.is_active:   
                    if Form2.is_valid():
                        User2 = Form2.save(commit=False)

                        #logo = UserProfile(logo=request.FILES["logo"])
                        User2.user = User1
                        User2.save()

                        auth_login(request, User1)

                        return redirect("/", request)

                    else:
                        return render(request, 'Index/register.html', {'Error_Message': request.POST})

                else:
                    return render(request, 'Index/login.html', {'Error_Message': 'Your account has been disabled'.upper()})

            else:
                return render(request, 'Index/register.html', {'Error_Message': 'Invalid sign up'.upper()})

        else:
            return render(request, 'Index/register.html', {'Error_Message': 'RECAPTCHA: ' + a.upper() for a in result['error-codes']})

    return render(request, "Index/register.html", {"is_active": request.user.is_active, "username": request.user.username})