我正在尝试在 django 中预填充我的编辑页面

时间:2021-02-28 05:31:42

标签: python django forms

我想用标题及其可编辑的内容预先填充我的表单字段。

我尝试了所有可能的方法,但仍然没有显示初始值。

view.py:

class EditPageForm(forms.Form):
    title = forms.CharField(max_length=100)
    content = forms.CharField(widget=forms.Textarea)

def edit_page(request,pre_title):
    
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # dictionary for the intial values
        intial_dict = {
        "title": pre_title,
        "content": util.get_entries(pre_title)
        }
        # create a form instance :
        form = EditPageForm(request.POST,initial=intial_dict)
        
       # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            util.save_entries(title,content)
            # redirect to a new URL:
            return HttpResponseRedirect(reverse('wikiapp:index'))

        # if data is not valid we'll return the form with error message
        else:
            return render(request,"encyclopedia\edit_page.html",{
                "form": form
            })

    # if a GET (or any other method) we'll create a blank form
    return render(request,"encyclopedia\edit_page.html",{
        "form": EditPageForm()
    })

1 个答案:

答案 0 :(得分:0)

如果使用 get 方法,您需要预先填充表单。您只为 post 方法执行此操作。

def edit_page(request,pre_title):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance :
        form = EditPageForm(request.POST)
        
       # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            util.save_entries(title,content)
            # redirect to a new URL:
            return HttpResponseRedirect(reverse('wikiapp:index'))
    else:
        intial_dict = {
            "title": pre_title,
            "content": util.get_entries(pre_title)
        }
        form = EditPageForm(initial=intial_dict)
    # if a GET (or any other method) we'll create a blank form
    return render(request,"encyclopedia\edit_page.html",{
        "form": form
    })
相关问题