基于网络请求预填充 Django 表单

Pre-populating Django form based on web request

我正在尝试根据用户的 Web 请求预填充 Django 表单。例如,当他们单击超链接 - http://myapp:8000//23 时,它会 returns 一个预填充的 django 表单,其中包含与 id 23 相关的所有数据。有关如何执行此操作的任何提示或想法,循序渐进就好了。提前致谢。

曼尼

你正在寻找的是在 Django 文档中,正是这个 Django Modelforms.

首先需要定义一个url获取对象:

url(r'^client/(?P<foo>\w{4})$', views.view_function, name='element'),

而视图函数应该是这样的:

def view_function(request, foo):
 obj = get_object_or_404(MyModel, id=foo) # Django shortcut
 form = NameForm(instance=obj)

 return render(request, 'mytemplate.html', {'form': form})

有了这个,您将预填充要在您的应用中显示的表单。您必须编写 Modelform 的方法在文档中。

您还可以将新数据保存到该对象。以下代码是相同的功能,但检查请求是 GET 还是 POST.

def view_function(request, foo):
   obj = get_object_or_404(MyModel, id=foo) # Django shortcut
   if request.method == 'GET':
       # The request uses the GET method, the form is pre-populate with the data of the Model if exists else send an Error 404
       form = NameForm(instance=obj)
       return render(request, 'mytemplate.html', {'form': form})

   elif request.method == 'POST':
       # The request uses POST, we will get the new data and if it is correct then we will save to the DB else we will show the same page as GET but this time will show the errors.
       form = NameForm(request.POST, instance=obj)
       if form.is_valid():
           form.save()
           return render(request, 'changesSaved.html', {})
       else: # This render will display the errors
           return render(request, 'myTemplate.html', {'form': form})

Django 快捷方式函数:https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/