我試圖使表單從用戶獲取信息並使用此信息發送電子郵件。這裏是我的代碼:DJANGO - 分配前引用的局部變量「表單」
#forms.py
from django import forms
class ContactForm(forms.Form):
nome = forms.CharField(required=True)
email = forms.EmailField(required=True)
msg = forms.CharField(
required=True,
widget=forms.Textarea
)
#views.py
from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect, render_to_response
from django.core.mail import send_mail
from .forms import ContactForm
def contato(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
nome = request.POST.get('nome')
email = request.POST.get('email')
msg = request.POST.get('msg')
send_mail('Subject here', msg, email, ['[email protected]'], fail_silently=False)
return HttpResponseRedirect('blog/inicio')
return render(request, 'blog/inicio.html', {'form': form})
#contato.html
{% extends "blog/base.html" %}
{% block content %}
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
,當我嘗試接觸頁面輸入我得到這個錯誤:
local variable 'form' referenced before assignment
跟它塔的錯誤是在這條線的意見。潘岳:
return render(request, 'blog/inicio.html', {'form': form})
我在Django的一個小新,你能幫幫我嗎?
非常感謝! –