使用没有窗体的视图创建django对象 [英] Create django object using a view with no form
问题描述
我想知道如何能够根据用户将要访问的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?
推荐答案
您应该使用 id
> urls.py :
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
中,您应该使用 id $来构造一个
出价
c $ c>传递到URL中,当前登录的用户( 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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!