保存modelForm以更新现有记录 [英] Save modelForm to update existing record

查看:74
本文介绍了保存modelForm以更新现有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个带有现有模型实例的modelForm(书)。我无法更新图书记录。添加新记录很好,但是当我尝试更新时,它似乎找不到发布者(这是外键)。错误是没有发布者匹配给定查询。



models.py



class Publisher(models.Model ):

  name = models.CharField(max_length = 30)

address = models.CharField( max_length = 50)

城市=模型.CharField(max_length = 60)

state_province =模型.CharField(max_length = 30)

国家= models.CharField(max_length = 50)

网站= models.URLField()

def __unicode __(self):
返回self.name

类元:

顺序= [名称]

class Author(models.Model):

  first_name = models.CharField(max_length = 30)

last_name = models.CharField(max_length = 40)

email = models.EmailField(blank = True,verbose_name ='e-mail')

objects = models.Manager( )

sel_objects = AuthorManager()

def __unicode __(self):

return self.first_name +''+ self.last_name

课堂书(models.Model):

  title = models.CharField(max_length = 100)

authors = models.ManyToManyField(Author)

Publisher = models.ForeignKey(Publisher)

publication_date = models.DateField(blank = True,null = True)

num_pages = models.IntegerField(blank = True,null = True)

class BookForm(ModelForm):

  class Meta:

模型=图书



views.py



def authorcontactupd(request,id):

  if request.method ==' POST':

a = Author.objects.get(pk = int(id))

form = AuthorForm(request.POST,instance = a)

如果form.is_valid():

form.save()

return HttpResponseRedirect('/ contact / created')

else :

a = Author.objects.get(pk = int(id))

表格= AuthorForm(instance = a)

return render_to_response('author_form.html',{'form':form})



错误消息



找不到页面(404)
请求方法:POST
请求URL: http://127.0.0.1:8000/books/bookupd/



没有与之匹配的发布商



您会看到此错误,因为Django设置文件中的DEBUG = True。将其更改为False,Django将显示一个标准的404页面。



urls.py



来自django。 conf.urls.defaults import *

从django.views.generic.simple中导入

从mysite10中导入

。 books.views从django.views.generic导入list_detail



导入about_pages,books_by_publisher,authorcontact,bookcontact,booklisting,authorcontactupd



from mysite10.books.models导入发布者,书



来自django.contrib导入管理员



admin .autodiscover()



def get_books():

 返回书.objects.all()

publisher_info = {

 'queryset':Publisher.objects.all(),

'template_name':'books / publisher_publisher_list_page.html',

'template_object_name':'publisher',

'extra_context':{'book_list':Book.objects.all},

}



book_info = {

 'queryset':Book.objects.order_by('-publication_date'),

'template_name':'books / publisher_publisher_list_page.html',

'template_object_name':' book',

'extra_context':{'publisher_list':Publisher.objects.all},

}



oreilly_books = {

 ' queryset':Book.objects.filter(publisher__name = O'Reilly),

'template_name':'books / publisher_publisher_list_page.html',

'template_object_name': 'book',

'extra_context':{'publisher_list':Publisher.objects.all},

}



urlpatterns = pattern('',

 (r'^ admin /(.*)',admin.site.root),

(r'^ polls /',include('mysite10.polls.urls')) ,

(r'^ search-form / $','mysite10.views.search_form'),

(r'^ search / $','mysite10.views .search'),

(r'^ contact / $ ','mysite10.contact.views.contact'),

(r'^ contact / thanks2 /(\d +)$','mysite10.contact.views.thanks2'),

(r'^ contact / thanks / $','mysite10.contact.views.thanks'),

(r'^ publishers / $',list_detail.object_list,Publisher_info ),

(r'^ books / $',list_detail.object_list,book_info),

(r'^ books / oreilly / $',list_detail.object_list或oreilly_books ),

(r'^ books /(\w +)/ $',books_by_publisher),

(r'^ author / $',authorcontact),

(r'^ authorupd /(\d +)/ $',authorcontactupd),

(r'^ contact / created / $','mysite10.books.views。已创建),

(r'^ bookform / $',bookcontact),

(r'^ contact / bookscreated / $','mysite10.books.views。 books_created'),

(r'^ booklist / $','mysite10.books.views.booklisting'),

(r'^ books / bookupd /(\ \d +)$','mysite10.books.views.book_upd'),



-------------------------------------- -----------



我终于使它与以下代码一起使用。 urls.py中的
错误,因为$之前缺少正斜杠。
修改为(r'^ books / bookupd /(\d +)/ $'



views.py



def book_upd(request,id):

 如果request.method =='POST':

a = Book.objects.get(pk = int(id))

form = BookForm(request.POST,instance = a)

if form。 is_valid():

form.save()

return HttpResponseRedirect('/ contact / bookscreated')
else:

a = Book.objects.get(pk = int(id))

form = BookForm(instance = a)

return render_to_response('book_form.html',{'form' :form})



urls.py



(r'^ books / bookupd /(\d +)/ $','mysite10.books.views.book_upd'),

解决方案

有一些缺少的信息,例如urls.py中的信息。您也可以将其发布吗?是否在数据库中检查了记录实际上没有更新?(错误可能是处理重定向的结果)






您的编辑不足:
-您是否检查数据库以查看记录是否已更新?
-请粘贴整个urls.py,例如,有趣的是,查看/ contact / created映射到的内容(如果成功的话),或者其中是否包含某些Publisher.get()方法



此外,回溯还可以提供许多有关问题根源的有用信息。






即使出现错误,您是否仍检查对象是否在数据库中已更新?



您可以尝试删除 oreilly_books部分吗(或至少是queryset部分),然后尝试在没有它的情况下进行同样的操作?


I create a modelForm with instance to existing model (Book). I am not able to update the Books record. Adding a new record is fine but when I attempt to update, it appears to be unable to find the publisher (which is a foreign key). Error is "No Publisher matches the given query."

models.py

class Publisher(models.Model):

name = models.CharField(max_length=30)

address = models.CharField(max_length=50)

city = models.CharField(max_length=60)

state_province = models.CharField(max_length=30)

country = models.CharField(max_length=50)

website = models.URLField()

def __unicode__(self):
    return self.name

class Meta:

    ordering = ["name"]

class Author(models.Model):

first_name = models.CharField(max_length=30)

last_name = models.CharField(max_length=40)

email = models.EmailField(blank=True, verbose_name='e-mail')

objects = models.Manager()

sel_objects=AuthorManager()

def __unicode__(self):

return self.first_name+' '+ self.last_name

class Book(models.Model):

title = models.CharField(max_length=100)

authors = models.ManyToManyField(Author)

publisher = models.ForeignKey(Publisher)

publication_date = models.DateField(blank=True, null=True)

num_pages = models.IntegerField(blank=True, null=True)

class BookForm(ModelForm):

class Meta:

    model = Book

views.py

def authorcontactupd(request,id):

if request.method == 'POST':

    a=Author.objects.get(pk=int(id))

    form = AuthorForm(request.POST, instance=a)

    if form.is_valid():

        form.save()

        return HttpResponseRedirect('/contact/created')

else:

    a=Author.objects.get(pk=int(id))

    form = AuthorForm(instance=a)

return render_to_response('author_form.html', {'form': form})

error msg

Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/books/bookupd/

No Publisher matches the given query.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

urls.py

from django.conf.urls.defaults import *

from django.views.generic.simple import direct_to_template

from mysite10.books.views import about_pages, books_by_publisher, authorcontact,bookcontact, booklisting, authorcontactupd

from django.views.generic import list_detail

from mysite10.books.models import Publisher, Book

from django.contrib import admin

admin.autodiscover()

def get_books():

return Book.objects.all()

publisher_info = {

'queryset': Publisher.objects.all(),

'template_name':'books/publisher_publisher_list_page.html',

'template_object_name': 'publisher',

'extra_context': {'book_list': Book.objects.all},

}

book_info = {

'queryset': Book.objects.order_by('-publication_date'),

'template_name':'books/publisher_publisher_list_page.html',

'template_object_name': 'book',

'extra_context': {'publisher_list': Publisher.objects.all},

}

oreilly_books = {

'queryset': Book.objects.filter(publisher__name="O'Reilly"),

'template_name':'books/publisher_publisher_list_page.html',

'template_object_name': 'book',

'extra_context': {'publisher_list': Publisher.objects.all},

}

urlpatterns = patterns('',

(r'^admin/(.*)', admin.site.root),

(r'^polls/', include('mysite10.polls.urls')),

(r'^search-form/$', 'mysite10.views.search_form'),

(r'^search/$', 'mysite10.views.search'),

(r'^contact/$', 'mysite10.contact.views.contact'),

(r'^contact/thanks2/(\d+)$', 'mysite10.contact.views.thanks2'),

(r'^contact/thanks/$', 'mysite10.contact.views.thanks'),

(r'^publishers/$', list_detail.object_list, publisher_info),

(r'^books/$', list_detail.object_list, book_info),

(r'^books/oreilly/$', list_detail.object_list, oreilly_books),

(r'^books/(\w+)/$', books_by_publisher),

(r'^author/$', authorcontact),

(r'^authorupd/(\d+)/$', authorcontactupd),

(r'^contact/created/$', 'mysite10.books.views.created'),

(r'^bookform/$', bookcontact),

(r'^contact/bookscreated/$', 'mysite10.books.views.books_created'),

(r'^booklist/$', 'mysite10.books.views.booklisting'),

(r'^books/bookupd/(\d+)$', 'mysite10.books.views.book_upd'),

)

-------------------------------------------------

I finally got it working with below codes. error in urls.py because of missing forward slash before $. Amended to (r'^books/bookupd/(\d+)/$'

views.py

def book_upd(request,id):

if request.method == 'POST':

    a=Book.objects.get(pk=int(id))

    form = BookForm(request.POST, instance=a)

    if form.is_valid():

        form.save()

        return HttpResponseRedirect('/contact/bookscreated')
else:

    a=Book.objects.get(pk=int(id))

    form = BookForm(instance=a)

return render_to_response('book_form.html', {'form': form})

urls.py

(r'^books/bookupd/(\d+)/$', 'mysite10.books.views.book_upd'),

解决方案

There's some missing information like what you have in your urls.py. Can you post it as well? Did you check in the database that the record was actually not updated? (the error might be a result of processing the redirect)


Your edit is not sufficient: - did you check the databse to see if the record is updated? - Please paste the entire urls.py as for example it is interesting to see what /contact/created is mapped to in case it did succeed, or whether you have some publisher.get() methods in it

In addition the traceback can also provide lots of useful information as to the source of the problem.


did you check if the object is updated in the database even though you get the error?

Can you try removing the "oreilly_books" section (or at least the queryset part) and try doing the same without it?

这篇关于保存modelForm以更新现有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆