我正在尝试使用由Django制作的表单将一些数据添加到我的数据库中。
模特:
class Image(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
picture = models.ImageField(upload_to="images/", null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, null=True, blank=True)
album = models.ForeignKey('Album', null=True, blank=True)
description = models.TextField(blank=True, null=True)
visible = models.BooleanField(blank=False, null=False, default=False)
def __str__(self):
return self.name
正如您所看到的,该模型具有更多属性,然后我尝试上传,仅用于测试目的。
观点:
def create(request):
if request.POST:
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
name = form.cleaned_data['name']
dexcription = form.cleaned_data['description']
visible = form.cleaned_data['visible']
image = Image.objects.create(
name = name,
description = description,
visible = visible,
)
#form.save()
#return render_to_response('imageall.html',context, context_instance=RequestContext(request))
return HttpResponseRedirect('/index/')
else:
form = ImageForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_image.html', args, context_instance=RequestContext(request))
你可以看到我一直在摆弄视图的“保存”部分。
我想form.save()
是最简单的方法,但这也不起作用。
和当然形式:
from django import forms
from forpix.models import Image
from forpix.models import Album
from django.contrib.auth.models import User
class ImageForm(forms.ModelForm):
class Meta:
model = Image
fields = ('name', 'description', 'visible')
主要的urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^accounts/login/$', 'mysite.views.login'),
url(r'^accounts/auth/$', 'mysite.views.auth_view'),
url(r'^accounts/logout/$', 'mysite.views.logout'),
url(r'^accounts/loggedin/$', 'mysite.views.loggedin'),
url(r'^accounts/invalid/$', 'mysite.views.invalid_login'),
url(r'^accounts/register/$', 'mysite.views.register_user'),
url(r'^accounts/register_success/$', 'mysite.views.register_success'),
url(r'^image/(?P<image_id>\d+)/$', 'forpix.views.showimage', name='image_url'),
url(r'^create/$', 'forpix.views.create'),
url(r'^$', 'forpix.views.index'),
url(r'^index/$', 'forpix.views.index'),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
和应用的urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^(?P<image_id>\d+)/$', views.results, name='results'),
)
现在,如果我测试一下,我可以看到并填写表格。 当我提交时,终端显示http消息
"POST /index/ HTTP/1.1" 200 3552
页面重定向到我的索引页面,但当我查看我的数据库时,没有添加任何内容。
有人可以解释一下我做错了吗?
我正在使用Python 3.4 我在Win7上 而数据库是一个sqllite我猜