gpt4 book ai didi

javascript - 使用 ajax 和基于类的 View 处理引导模式中的表单提交

转载 作者:行者123 更新时间:2023-11-28 04:43:04 25 4
gpt4 key购买 nike

我是 django 的新手,我已经被这个问题困扰好几天了。我的模板上的引导模式中有一个 form.Form,只有 1 个字段(email_field),基本上我需要通过 ajax 提交该表单,检查该电子邮件地址是否在数据库中注册,然后向该电子邮件发送邀请,然后关闭模式。如果电子邮件未注册,则显示表单错误而不关闭模式。我尝试过不同的示例,但可以找到解决方案,因为这些示例不处理错误,或者表单不在模式内,或者不使用基于类的 View

.

我的代码有两个问题:

  1. 不确定如果表单有效或无效,在我的 View 中要返回什么,以及如何处理 js 代码中的错误以在模式上显示它们。(返回表单以呈现错误或 JSON 响应??)。
  2. 第一次成功提交后,表单将无法再次使用。(提交按钮的大小会发生变化,如果单击它会返回错误:CSRF token 缺失或不正确)

Form.py

class CollaboratorForm(forms.Form):
email_address = forms.EmailField(required=True,widget=forms.TextInput(attrs={'class': 'form-control focus-text-box', 'type': 'email',
'placeholder': 'Enter email'}))

def clean_email_address(self):
email = self.cleaned_data['email_address']
if not User.objects.filter(email=email):
raise forms.ValidationError('This user is not registered')
return email

def sendEmail(self, datas):
message = "Hello, " + datas['user_name']+" "+ datas['email_from'] + " invited you to collaborate in an existing project. Follow this link if you are interested " + datas['invitation_link']
msg = EmailMessage('Invitation from ' + datas['user_name'],
message, to=[datas['email_to']])
msg.send()

Template.html (project_detail.html)

<script src="{% static '/experiments/js/invite_collaborator.js' %}"></script>

<div class="bootstrap-modal modal fade in" id="collaboratorModal" style="display: none;">
<div class="modal-body">
<form action="{% url 'experiments:invite-collaborator' project_id=project.id %}" method="post" id=collaborator-form >
{% csrf_token %}

<div class="form-group">
{% if collaborator_form.errors %}
<ol>
{% for error in collaborator_form.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %}

<label class="control-label">Invite someone by email</label>
<div class="input-group mt10">
{{ collaborator_form }}
<span class="input-group-btn">
<input name="collaborator-commit" onClick="invite({{project.id}});" class="btn btn-primary" data-disable-with="Send Invitation" id="invite-button" type="submit">
</span>
</div>
</div>
</form>
</div>
</div>

网址.py

urlpatterns = [
url(r'^(?P<project_id>[0-9]+)/invite_collaborator$', views.InviteCollaborator.as_view(), name='invite-collaborator'),
]

View.py

class ProjectDetail(DetailView):
model = Project
template_name = 'experiments/project_detail.html'
pk_url_kwarg = 'project_id'


def get_context_data(self, **kwargs):
context = super(ProjectDetail, self).get_context_data()
project = get_object_or_404(Project,pk=self.kwargs["project_id"])
context["project"] = project
context["collaborator_form"] = CollaboratorForm()
return context

class InviteCollaborator(FormView):
form_class = CollaboratorForm
template_name = 'experiments/project_detail.html'

def post(self, request, *args, **kwargs):
collaborator_form = CollaboratorForm(data=request.POST)
project_id = request.POST['project_id']
current_project = Project.objects.get(id=project_id)
datas={}
if collaborator_form.is_valid():
cleaned_data = collaborator_form.cleaned_data
email_address = cleaned_data.get('email_address')
user = User.objects.get(pk=request.user.id)
invitation_link = "http://exp.innovationhackinglab.com/projects/"+ str(current_project.id) + "/join/" + current_project.invitation_key
datas['user_name'] = user.first_name + ' ' + user.last_name
datas['email_from'] = user.email
datas['email_to'] = email_address
datas['invitation_link'] = invitation_link
collaborator_form.sendEmail(datas)
data = simplejson.dumps("Success")
return HttpResponse(data, content_type='application/json')
else:
return super(InviteCollaborator, self).form_invalid(collaborator_form)

invite_collaborator.js

function invite(project_id) {
$('#collaborator-form').submit(function(e) {
e.preventDefault();
$.ajax({
data: $(this).serialize()+'&'+$.param({ 'project_id': project_id }),
type: $(this).attr('method'),
url: $(this).attr('action'),
});
$('#collaboratorModal').modal('toggle');
$('#collaboratorModal').on('hidden.bs.modal', function () {
$(this).find("input,textarea,select").val('').end();
});
});
};

我读过有关在 js 文件上使用 success: & error: 的内容,但不知道如何在 View 中没有适当的“返回”的情况下使用它

最佳答案

您需要有两种 ajax 方法,一种用于获取表单(作为原始 html),另一种用于发布表单。您的 View 中也会有相应的 get 和 post 方法。

获取 View 类的函数:

def get(self, request, *args, **kwargs):

form = CollaboratorForm()
return render(request,'template.html',{'form':form})

def post(self, request, *args, **kwargs):

form = CollaboratorForm(request.POST)
if form.is_valid():
//save form
//return whatever you want to show on successful form submission
else:
//return bound form as html with errors
return render(request,'template.html',{'form':form})

js函数

有两个独立的ajax函数,一个用于get(显示表单),一个用于post(提交表单)

关于javascript - 使用 ajax 和基于类的 View 处理引导模式中的表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43605140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com