使用没有表单的视图创建

使用没有表单的视图创建

本文介绍了使用没有表单的视图创建 django 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何根据用户要访问的 URL 在数据库中创建对象.

I was wondering how I would be able to create an object in a database based the URL a user is going to.

例如,他们将转到/schedule/addbid/1/,这将在表中创建一个对象,其中包含投标的所有者、他们投标的时间表以及投标是否已完成.这是迄今为止我的模型的出价.

Say for example they would go to /schedule/addbid/1/ and this would create an object in the table containing the owner of the bid, the schedule they bidded on and if the bid has been completed. This here is what I have for my model so far for bids.

class Bids(models.Model):
   id = models.AutoField("ID", primary_key=True, editable=False,)
   owner = models.ForeignKey(User)
   biddedschedule = models.ForeignKey(Schedule)
   complete = models.BooleanField("Completed?", default=False)

biddedschedule 将基于 URL 中的数字,因为在这种情况下 1 将是调度表中的第一个调度

The biddedschedule would be based on the number in the URL as the 1 in this case would be the first schedule in the schedule table

关于如何做到这一点的任何想法?

Any ideas on how to do this?

推荐答案

您应该使用 urls.py 获取 id 参数:

You should get the id parameter using urls.py:

#urls.py
from appname.views import some_view

urlpatterns = patterns('',
    url(r'^schedule/addbid/(?P<id>d+)$', some_view),
    ...
)

查看关于在 urlconf 中捕获参数的文档.

然后,在 views.py 中,您应该使用 URL 中传递的 id 构造一个 Bids 对象,即当前登录的用户(request.user) 和来自您的数据库的 biddschedule.例如:

And then, in views.py you should construct a Bids Object using the id passed in the URL, the currently logged in user (request.user), and the biddschedule from your DB. For example:

#views.py
def some_view(request, id):
    if request.user.is_authenticated():
        # get the biddschedule from your DB
        # ...
        bids = models.Bids(id=id, owner=request.user, biddedschedule=biddedschedule)
        bids.save()
        return HttpResponse("OK")
    return Http404()

这篇关于使用没有表单的视图创建 django 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:15