UPDATE3
我通过再次阅读教程后添加更多代码解决了问题 ,但得到错误'WSGIRequest'对象在按下按钮
后没有属性'电子邮件'按下保存按钮后链接没有查询字符串
def post_new(request):
#post = get_object_or_404(Post)
#form = PostForm()
#return render_to_response(request, 'registration.html', {'pk': 12})
#return render(request, 'registration.html', {'form': form})
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
#post.author = request.user
post.Email = request.Email
post.ProjectName = request.ProjectName
post.UserName = request.UserName
post.Company = request.Company
post.Contact = request.Contact
post.InitialPassword = request.InitialPassword
post.UserType = request.UserType
post.BusinessType = request.BusinessType
post.published_date = timezone.now()
post.publish()
#self.published_date = timezone.now()
return redirect('post_detail', pk=post.pk)
#isexist = os.path.isfile('newusers.csv')
#with open('/home/martin/Downloads/site1/site1/reg/newusers.csv', 'a') as csvfile:
#fieldnames = ['name','email address','project','initial password','userType','contact','businessType','company']
#writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
#if isexist == 0:
#writer.writeheader()
#writer.writerow({'name': request.user, 'email address': request.Email, 'project': request.ProjectName, 'initial password': request.InitialPassword,'userType': request.UserType, 'contact': request.Contact, 'businessType': request.BusinessType, 'company': request.Company,})
return redirect('hello.html', pk=post.pk)
else:
form = PostForm()
return render(request, 'registration.html', {'form': form})
UPDATE2
尝试了很多方法后,仍有错误,请下载 https://drive.google.com/file/d/0Bxs_ao6uuBDUdHFQalFmQmY3U2c/view?usp=sharingUPDATE1
<form method={% url 'post_detail' %}" method="post"" class="post-form">{% csrf_token %}
在上述更新后,它仍然无法运行post_detail
只有
[25/May/2016 04:07:39] "GET /reg/?csrfmiddlewaretoken=uwMaoReQGeVFVdVdJKmsNWApxVIjyDna&Email=a&ProjectName=a&UserName=a&Company=a&Contact=a&InitialPassword=234&UserType=Cyberport+Tenant&BusinessType=Building HTTP/1.1" 200 2276
它没有转到hello.html,所以我猜它还没有运行post_detail
我不明白为什么它在url使用函数名称时传递
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.Email = request.Email
post.ProjectName = request.ProjectName
post.UserName = request.UserName
post.Company = request.Company
post.Contact = request.Contact
post.InitialPassword = request.InitialPassword
post.UserType = request.UserType
post.BusinessType = request.BusinessType
post.published_date = timezone.now()
self.published_date = timezone.now()
#isexist = os.path.isfile('newusers.csv')
#with open('/home/martin/Downloads/site1/site1/reg/newusers.csv', 'a') as csvfile:
#fieldnames = ['name','email address','project','initial password','userType','contact','businessType','company']
#writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
#if isexist == false:
#writer.writeheader()
#writer.writerow({'name': request.user, 'email address': request.Email, 'project': request.ProjectName, 'initial password': request.InitialPassword,'userType': request.UserType, 'contact': request.Contact, 'businessType': request.BusinessType, 'company': request.Company,})
return redirect('hello.html', pk=post.pk)
else:
render(request, 'hello.html', {'form': form})
#form = PostForm(instance=post)
return render(request, 'hello.html', {'form': form})
我跟随django女孩网并感觉非常困难,期望去/ reg填写表格并按保存按钮然后转到网络/reg/<a number>
只需按下保存按钮
即可触发功能它有错误
使用参数'()'和关键字反转'reg / {{post.pk}} /' 没有找到参数“{}”。尝试了0种模式:[]
然后尝试主键pk,又得到了另一个错误
/home/martin/Downloads/site1/site1/reg/models.py:37: RemovedInDjango19Warning:模型类site1.reg.models.Post没有 声明一个显式的app_label,并且不在应用程序中 INSTALLED_APPS或其他应用程序在其应用程序之前导入 加载。 Django 1.9将不再支持此功能。类 交(models.Model):
我已将site1.reg.models.Post
添加到MIDDLEWARE_CLASSES
但仍有错误
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'site1.reg.models.Post',
)
registration.html
{% block content %}
<h1>New user registration</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default" >Save</button>
</form>
{% endblock %}
urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^reg/$', views.post_new, name='post_new'),
url(r'^reg/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
views.py
from .forms import PostForm
from django.shortcuts import render
from django.template.loader import get_template
def post_new(request):
form = PostForm()
return render(request, 'registration.html', {'form': form})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.ProjectName = request.ProjectName
post.UserName = request.UserName
post.Company = request.Company
post.Contact = request.Contact
post.InitialPassword = request.InitialPassword
post.UserType = request.UserType
post.BusinessType = request.BusinessType
post.published_date = timezone.now()
post.save()
return redirect('registration.html', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'registration.html', {'form': form})
models.py
from django.db import models
from django.utils import timezone
from django.apps import AppConfig
import csv
import os.path
USERTYPE = (
('Cyberport Tenant', 'Cyberport Tenant'),
('SmartSpace User', 'SmartSpace User'),
('Cyberport Incubate', 'Cyberport Incubate'),
('Collaboration Center Subscriber', 'Collaboration Center Subscriber'),
('Cyberport Alumnus', 'Cyberport Alumnus'),
('Technology Partner', 'Technology Partner'),
('HKOSUG', 'HKOSUG'),
('Others', 'Others'),
)
BUSINESSTYPE = (
('Building', 'Building'),
('Data Analysis', 'Data Analysis'),
('Digital Entertainment', 'Digital Entertainment'),
('Education', 'Education'),
('Games', 'Games'),
('Gaming', 'Gaming'),
('ICT', 'ICT'),
('Marketing', 'Marketing'),
('Social Media', 'Social Media'),
('Others', 'Others'),
)
class MyAppConfig(AppConfig):
name = 'src.my_app_label'
def ready(self):
post_migrate.connect(do_stuff, sender=self)
class Post(models.Model):
author = models.ForeignKey('auth.User')
Email = models.CharField(max_length=70)
ProjectName = models.CharField(max_length=70)
UserName = models.CharField(max_length=70)
Company = models.CharField(max_length=70)
Contact = models.CharField(max_length=70)
InitialPassword = models.CharField(max_length=70)
UserType = models.CharField(max_length=30, choices=USERTYPE)
BusinessType = models.CharField(max_length=30, choices=BUSINESSTYPE)
#UserType = models.ChoiceField(choices=USERTYPE, required=True )
#BusinessType = models.ChoiceField(choices=BUSINESSTYPE, required=True )
#ProjectName = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
isexist = os.path.isfile('newusers.csv')
with open('/home/martin/Downloads/site1/site1/reg/newusers.csv', 'a') as csvfile:
fieldnames = ['name','email address','project','initial password','userType','contact','businessType','company']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if isexist == false:
writer.writeheader()
writer.writerow({'name': UserName, 'email address': Email, 'project': ProjectName, 'initial password': InitialPassword,'userType': UserType, 'contact': Contact, 'businessType': BusinessType, 'company': Company,})
self.save()
def __str__(self):
return self.title
forms.py
from django import forms
from .models import Post
USERTYPE = (
('Cyberport Tenant', 'Cyberport Tenant'),
('SmartSpace User', 'SmartSpace User'),
('Cyberport Incubate', 'Cyberport Incubate'),
('Collaboration Center Subscriber', 'Collaboration Center Subscriber'),
('Cyberport Alumnus', 'Cyberport Alumnus'),
('Technology Partner', 'Technology Partner'),
('HKOSUG', 'HKOSUG'),
('Others', 'Others'),
)
BUSINESSTYPE = (
('Building', 'Building'),
('Data Analysis', 'Data Analysis'),
('Digital Entertainment', 'Digital Entertainment'),
('Education', 'Education'),
('Games', 'Games'),
('Gaming', 'Gaming'),
('ICT', 'ICT'),
('Marketing', 'Marketing'),
('Social Media', 'Social Media'),
('Others', 'Others'),
)
class PostForm(forms.ModelForm):
#if form.is_valid():
#post = form.save(commit=False)
#post.author = request.user
#post.published_date = timezone.now()
#post.save()m
class Meta:
model = Post
fields = ('Email', 'ProjectName', 'UserName', 'Company', 'Contact', 'InitialPassword','UserType','BusinessType')
#fields = ('title', 'text',)
UserType = forms.ChoiceField(choices=USERTYPE, required=True )
BusinessType = forms.ChoiceField(choices=BUSINESSTYPE, required=True )
答案 0 :(得分:0)
这不是有效的语法:
<form method={% url 'post_detail' %}" method="post"" class="post-form">
您要将表单发布到的网址应位于action
属性中:
<form action="{% url 'post_detail' %}" method="post"" class="post-form">
答案 1 :(得分:0)
urls.py
from django.conf.urls import url
from views import post_detail
urlpatterns = [
url(r'^reg/(?P<pk>[0-9A-Za-z]+)/$',
post_detail,
name='post_detail'),
]
template.html
从视图传递“pk”值
<form action="{% url 'post_detail' pk=pk %}" method="post" class="post-form">
模板中的url结构是 {%url'命名空间:名称'args,kwargs在这里%}}
答案 2 :(得分:0)
我使用post而不是request 并在post_new中添加更多代码
def post_new(request):
#post = get_object_or_404(Post)
#form = PostForm()
#return render_to_response(request, 'registration.html', {'pk': 12})
#return render(request, 'registration.html', {'form': form})
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
#post.author = request.user
#post.Email = request.Email
#post.ProjectName = request.ProjectName
#post.UserName = request.UserName
#post.Company = request.Company
#post.Contact = request.Contact
#post.InitialPassword = request.InitialPassword
#post.UserType = request.UserType
#post.BusinessType = request.BusinessType
#post.published_date = timezone.now()
#post.publish()
#self.published_date = timezone.now()
#return redirect('post_detail', pk=post.pk)
isexist = os.path.isfile('/home/martin/Downloads/site1/site1/reg/newusers.csv')
with open('/home/martin/Downloads/site1/site1/reg/newusers.csv', 'a') as csvfile:
fieldnames = ['name','email address','project','initial password','userType','contact','businessType','company']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
print "isexist"
print isexist
if isexist == 0:
writer.writeheader()
writer.writerow({'name': post.UserName, 'email address': post.Email, 'project': post.ProjectName, 'initial password': post.InitialPassword,'userType': post.UserType, 'contact': post.Contact, 'businessType': post.BusinessType, 'company': post.Company,})
return render(request, 'approval.html', {'form': form})
else:
form = PostForm()
return render(request, 'registration.html', {'form': form})