且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何让Django的通用视图使用具有初始值的窗体?

更新时间:2022-11-22 22:21:25

Unfortunately, you cannot achieve this behavior through Django's create_object generic view; you will have to write your own. However, this is rather simple.

To start off, you must create a new form class, like this:

from django import forms
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel  # model has a user field

Then you would be able to create a view like this:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required
def create_mymodel(request):
    if request.method == 'POST':
        # Get data from form
        form = MyForm(request.POST)
        # If the form is valid, create a new object and redirect to it.
        if form.is_valid():
            newObject = form.save()
            return HttpResponseRedirect(newObject.get_absolute_url())
    else:
        # Fill in the field with the current user by default
        form = MyForm(initial={'user': request.user})
    # Render our template
    return render_to_response('path/to/template.html',
        {'form': form},
        context_instance=RequestContext(request))

相关阅读

技术问答最新文章