我在使用Django快捷方式呈現頁面時遇到了一些困難。我的工作流程非常簡單:Django視圖不能正確重定向
- 用戶進入一個頁面,在這裏他們可以查看某些項目數據(detail_project)
- 如果他們想更新項目數據,他們應該點擊一個按鈕,將發送POST請求,加載update_project頁面。此頁面將加載當前的項目數據。
- 用戶更新並提交新數據。提交後,它們返回到detail_project頁面。
我的看法是這樣的:
def update_project(request):
if request.method == 'POST':
if 'update_project_submit' in request.POST:
# updates project with form data and returns to detail project page
return redirect('detail_project', project_name=project_name)
else:
# loads project original data into the form
return render(request, 'project/update_project.html', context)
def detail_project(request, project_name):
if request.method == 'POST':
if 'update_project' in request.POST:
return update_project(request)
else:
# does another stuff
else:
# shows project details
return render(request, 'project/detail_project.html', context)
urls.py:
url(r'^project/update/$', views.update_project, name='update_project'),
url(r'^project/details/(?P<project_name>[a-zA-Z][a-zA-Z0-9-_]+)/$', views.detail_project, name='detail_project'),
而且update_project.html:
<form class="form-horizontal" role="form" action="" method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<div class="col-sm-3">
<label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label>
</div>
<div class="col-sm-9">
{{field}}
</div>
<div class="col-sm-12">
{{ field.help_text }}
</div>
</div>
{{field.non_field_errors }}
{{field.errors}}
{% endfor %}
<button type="submit" name="update_project_submit" class="btn btn-primary">Submit</button>
</form>
[更新]
Forms.py
class UpdateProjectForm(forms.Form):
project_name_validator = RegexValidator(r'^[a-zA-Z][a-zA-Z0-9-_]{1,31}$', constants.PROJECT_NAME_INVALID)
project_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'required': 'true'}), validators=[project_name_validator])
project_description = forms.CharField(required=True, widget=forms.Textarea(attrs={'style':'resize:none;', 'required': 'true'}))
project_expiration = forms.DateField(required=False, widget=forms.TextInput(attrs={'class':'datepicker'}))
def __init__(self, *args, **kwargs):
super(UpdateProjectForm, self).__init__(*args, **kwargs)
self.fields['project_name'].label = "Project Name:"
self.fields['project_description'].label = "Project Description:"
self.fields['project_expiration'].label = "Expiration Date:"
的問題是,我不能更新我的項目。我的頁面正確加載表單(update_project)和當前數據(步驟2),但是當我提交它時(單擊提交按鈕,我將被重定向到詳細項目頁面而不輸入if 'update_project_submit' in request.POST:
聲明。也許我的工作流程是錯誤的。不能看着辦吧。
我印我的請求,我真的cofirmed,當我提交表單,我收到一個POST請求detail_project。
有我丟失的東西?還是我我試圖根據Django的邏輯做錯事?
你爲什麼不使用Django的形式和標準的配方? – e4c5
@ e4c5,那麼,我正在使用django表單。 「標準配方」是什麼意思? – revy
你知道,創建一個postdata爲一個職位的表格,沒有它獲得,呈現相同的形式,如果無效等您的代碼似乎並不遵循該模式 – e4c5