我想在我用 django 撰寫的網站上發布的頁面中包含超鏈接、參考、斜體文本等內容,但它似乎逃避了我的代碼。我可以做些什么來添加這個功能?其他人已經做了我可以使用的東西嗎?
uj5u.com熱心網友回復:
我是這樣做的。希望對您有所幫助。
假設你想要這樣:::
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
我們已經知道我們希望我們的 HTML 表單是什么樣子。我們在 Django 中的起點是:#forms.py from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
整個表單在第一次渲染時將如下所示:
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100" required>
要處理表單,我們需要在我們希望發布的 URL 的視圖中實體化它:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
我們不需要在 name.html 模板中做太多事情:
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
所有表單的欄位及其屬性都將通過 Django 的模板語言從該 {{ form }} 解壓縮到 HTML 標記中。
希望這可行,或者您可以遵循官方檔案。 https://docs.djangoproject.com/en/4.0/topics/forms/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/406271.html
標籤:
