【问题标题】:I'm tring to pre-populate my edit page in django我正在尝试在 django 中预先填充我的编辑页面
【发布时间】:2021-02-28 05:31:42
【问题描述】:

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

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

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()
    })

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    如果使用 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
        })
    

    【讨论】:

      猜你喜欢
      • 2019-03-10
      • 2011-08-19
      • 2018-09-05
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多