表格没有在Django应用程序中显示

时间:2018-03-06 09:39:01

标签: django django-models django-forms django-views cookiecutter-django

我选择了一个非常简单的django挑战,但是输入细节并将其提交到数据库时出现问题。我的表格甚至没有说明输入细节,我不知道做错了什么。

models.py

class Users(models.Model):
    name = models.CharField(max_length=200)
    email = models.CharField(max_length=60, unique=True)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now_add=True)

views.py

from django.shortcuts import render

from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime
from django.http import HttpResponseRedirect

from .models import Users
from .forms import UserForm

def home(request):
    return render(request, 'pages/home.html', {})


def list(request):
    users = Users.objects.order_by('created_at').all()
    context = {'users': users}
    return render(request, 'pages/list.html', context)


def add(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            user = User(name=request.POST['name'], email=request.POST['email'])
            user.save()
            return HttpResponseRedirect('/list/')

    return render(request, 'pages/list.html', {'form': form})

forms.py

from django import forms
from django.core.validators import validate_email
from .models import Users
class UserForm(forms.Form):
    name = forms.CharField(label='Name', max_length=200, widget=forms.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(label='Email', max_length=60, widget=forms.TextInput(attrs={'class': 'form-control'}))
    def clean_email(self):
        email = self.cleaned_data['email']
        if Users.objects.filter(email=email).exists():
            raise forms.ValidationError('Email already exists')
        return email

add.html (模板):

{% extends "base.html" %}

{% block content %}

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h1>Add user</h1>
            {{ form.non_field_errors }}
            <form name='form' method="POST" action="/add/">
                {% csrf_token %} {% for field in form %}
                <div class="form-group">
                    {{ field.label_tag }} {{ field }} {% if field.errors %}
                    <ul class="errorlist">
                        {% for error in field.errors %}
                        <li>{{ error|escape }}</li>
                        {% endfor %}
                    </ul>
                    {% endif %}
                </div>
                {% endfor %}
                <button type="submit" class="btn btn-primary">Add</button>
            </form>
        </div>
    </div>
</div>
{% endblock %}

urls.py

from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
    url(r'^list/', TemplateView.as_view(template_name='pages/list.html'), name='list'),
    url(r'^add/', TemplateView.as_view(template_name='pages/add.html'), name='add'),
    url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),

    # Django Admin, use {% url 'admin:index' %}
    url(settings.ADMIN_URL, admin.site.urls),

    # User management
    url(r'^users/', include('seedstar_django_challenge.users.urls', namespace='users')),
    url(r'^accounts/', include('allauth.urls')),

    # Your stuff: custom urls includes go here


] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
    # This allows the error pages to be debugged during development, just visit
    # these url in browser to see how these error pages look like.
    urlpatterns += [
        url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}),
        url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}),
        url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}),
        url(r'^500/$', default_views.server_error),
    ]
    if 'debug_toolbar' in settings.INSTALLED_APPS:
        import debug_toolbar
        urlpatterns = [
            url(r'^__debug__/', include(debug_toolbar.urls)),
        ] + urlpatterns

当我查看我的日志时,我会在下面看到:

Error Log

因此,当我单击添加没有任何操作时,没有输入表单,也没有谈论在DB中保存详细信息。如果你需要那么好,那么回购是here

我哪里错了?

注意我正在使用cookiecutter。

2 个答案:

答案 0 :(得分:0)

试试这个:

<强> URLS

url(r'^add/', views.AddUserView.as_view(), name='add'),

<强>视图

from django.views.generic import TemplateView

class AddUserView(TemplateView):
    template_name = "pages/add.html"
    def post(self, request, **kwargs):     
        print(request)
        return render(request, 'pages/list.html', {'form': form})

答案 1 :(得分:0)

您的所有网址都没有真正转到您定义的视图。因此永远不会接受POST,并且表单永远不会出现在上下文中。我不知道你为什么这样做,但你不应该。

 public static void parseCsvFile(String path) throws IOException {
    FileInputStream inputStream = null;
    Scanner sc = null;
    try {
        inputStream = new FileInputStream(path);
        sc = new Scanner(inputStream, "UTF-8");
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            //logger.info(line);
        }
        // note that Scanner suppresses exceptions
        if (sc.ioException() != null) {
            throw sc.ioException();
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (sc != null) {
            sc.close();
        }
    }
  }

    public static void parseCsvUsingJavaStream(String path) {
    try (Stream<String> stream = Files.lines(Paths.get(path))) {
         stream.forEach(System.out :: println);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
  }