簡體   English   中英

[DJANGO]:如何將 Django 表單字段值傳遞給模板表單操作?

[英][DJANGO]: How to pass a Django form field value to a template form action?

我有一個 Django 表格,要求輸入身份證號碼。 因此,當用戶單擊提交時,該 ID 號作為參數傳遞給端點。

此 URL path('verify/nin/', views.post_nin, name='post_nin')包含表單並在我將數據提交到此 URL 時詢問 ID 號

   path('nin/<str:nin>',
             views.nin_verification_vw, name="nin_verification")

所以我希望被重定向到http://127.0.0.1:8000/api/nin/15374020766但它卻將我重定向到http://127.0.0.1:8000/%2nintext/3.0.1:8200/%2input/ %22%20name=%22nin%22%20required%20id=%22id_nin%22%3E?nin=15374020766&csrfmiddlewaretoken=u5UmwDW4KRUIvYWXAa64J8g1dTPoJ3yDqtoCuKjboIE2TNxI3tPbjPmCK6FztVwW

如何避免不必要的參數?

這是我的 forms.py:

class NINPostForm(forms.Form):
    """Form for a user to verify NIN"""
    nin = forms.CharField(required=True, help_text='e.g. 123xxxxxxxx')

    # check if the nin is a valid one
    def clean_nin(self):
        nin = self.cleaned_data['nin']
        regex = re.compile("^[0-9]{11}$")
        if not regex.match(nin):
            raise forms.ValidationError("NIN is incorrect.")

        return nin

這是我的views.py:

def post_nin(request):
    submitted = False
    if request.method == 'POST':
        form = NINPostForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data['nin']
            return HttpResponseRedirect('/verify/nin?submitted=True')
    else:
        form = NINPostForm()
    context = {
        'form': form,
        # 'cd': cd,
    }
    return render(request, 'ninform.html', context)

這是我的 HTML 模板:

<form action="{% url 'nin_verification' form.nin %}" method="POST">
    <table>
        {{ form.as_table }}
        <tr>
            <td><input type="submit" value="Submit"></td>
        </tr>
    </table>
    {% csrf_token %}
</form>

第一個導入redirectfrom django.shortcuts import redirect

將您的視圖更改為:

<form action="{% url 'post_nin'  %}" method="POST">
    <table>
        {{ form.as_table }}
        <tr>
            <td><input type="submit" value="Submit"></td>
        </tr>
    </table>
    {% csrf_token %}
</form>

您通過在表單action中使用form.nin來傳遞整個字段而不是字符串,您應該使用您的post_nin視圖來解析 nin 字段,所以......

將您的視圖更改為:

def post_nin(request):
    submitted = False # Don't understand this part
    if request.method == 'POST':
        form = NINPostForm(request.POST)
        if form.is_valid():
            nin = form.cleaned_data['nin']
            return redirect('nin_verification', nin=nin)
    else:
        form = NINPostForm()
    context = {
        'form': form,
    }
    return render(request, 'ninform.html', context)

`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM