7.4.FormModel
FormModel
organization/form.py
import re
from django import forms
from operation.models import UserAsk
class UserAskForm(forms.ModelForm):
class Meta:
model = UserAsk
fields = ['name', 'mobile', 'course_name']
def clean_mobile(self):
"""
验证手机号码合法性
:return:
"""
mobile = self.cleaned_data['mobile']
regex_mobile = '^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$'
p = re.compile(regex_mobile)
if p.match(mobile):
return mobile
else:
raise forms.ValidationError('手机号码非法', code='mobile_invalid')
返回json对象
organization/views.py
from django.http import HttpResponse
...
class AddUserAskView(View):
"""
用户添加咨询
"""
def post(self, request):
user_ask_form = UserAskForm(request.POST)
if user_ask_form.is_valid():
user_ask = user_ask_form.save(commit=True)
return HttpResponse('{"status": "success"}', content_type='application/json')
else:
return HttpResponse('{"status": "fail", "msg": {0}}'.format(user_ask_form.errors),
content_type='application/json')
templates/org-list.html
<div class="right companyright">
<div class="head">我要学习</div>
<form class="rightform" id="jsStayForm">
<div>
<img src="/static/images/rightform1.png"/>
<input type="text" name="name" id="companyName" placeholder="名字" maxlength="25"/>
</div>
<div>
<img src="/static/images/rightform2.png"/>
<input type="text" name="mobile" id="companyMobile" placeholder="联系电话"/>
</div>
<div>
<img src="/static/images/rightform3.png"/>
<input type="text" name="course_name" id="companyAddress" placeholder="课程名" maxlength="50"/>
</div>
<p class="error company-tips" id="jsCompanyTips"></p>
<input class="btn" type="text" id="jsStayBtn" value="立即咨询 >"/>
{% csrf_token %}
</form>
</div>
<script>
$(function () {
$('#jsStayBtn').on('click', function () {
$.ajax({
cache: false,
type: "POST",
url: "{% url 'org:add_ask' %}",
data: $('#jsStayForm').serialize(),
async: true,
success: function (data) {
if (data.status == 'success') {
$('#jsStayForm')[0].reset();
alert("提交成功")
} else if (data.status == 'fail') {
$('#jsCompanyTips').html(data.msg)
}
},
});
});
})
</script>
url include
hello_django/urls.py
from django.urls import path, include
...
urlpatterns = [
...
# 课程机构
path('org/', include('organization.urls')),
]
organization/urls.py
from django.urls import path
from organization.views import OrgView
app_name = 'org'
urlpatterns = [
# 课程机构首页
path('list/', OrgView.as_view(), name='org_list'),
]
templates/index.html
<a href="{% url 'org:org_list' %}">授课机构</a>
视频播放 video js
获取请求url实现菜单选中
{% if request.path|slice:'7' == '/course' %}class = actibe {% endif %}
Last updated
Was this helpful?