本文整理汇总了Python中django.forms.Form.is_valid方法的典型用法代码示例。如果您正苦于以下问题:Python Form.is_valid方法的具体用法?Python Form.is_valid怎么用?Python Form.is_valid使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.forms.Form
的用法示例。
在下文中一共展示了Form.is_valid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: contact_edit
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def contact_edit(request, id, template_name='membership/entity_edit.html'):
contact = get_object_or_404(Contact, id=id)
# XXX: I hate this. Wasn't there a shortcut for creating a form from instance?
class Form(ModelForm):
class Meta:
model = Contact
before = contact.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here
if request.method == 'POST':
if not request.user.has_perm('membership.manage_members'):
messages.error(request, unicode(_("You are not authorized to modify memberships.")))
return redirect('contact_edit', id)
form = Form(request.POST, instance=contact)
if form.is_valid():
form.save()
after = contact.__dict__
log_change(contact, request.user, before, after)
messages.success(request, unicode(_("Changes to contact %s saved.") % contact))
return redirect('contact_edit', id) # form stays as POST otherwise if someone refreshes
else:
messages.error(request, unicode(_("Changes to contact %s not saved.") % contact))
else:
form = Form(instance=contact)
message = ""
logentries = bake_log_entries(contact.logs.all())
return render_to_response(template_name, {'form': form, 'contact': contact,
'logentries': logentries},
context_instance=RequestContext(request))
示例2: cancel
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def cancel(request, payload):
from itsdangerous import BadSignature
s = get_serializer()
try:
appointment_id = s.loads(payload)
except BadSignature:
return Http404
appointment = get_object_or_404(Appointment, pk=appointment_id)
if appointment.is_cancelled():
messages.warning(request, _("You've already cancelled this appointment."))
return redirect('finish')
if 'POST' == request.method:
form = Form(request.POST)
if form.is_valid():
appointment.cancel()
messages.info(request, _("You successfully cancelled your appointment."))
return redirect('finish')
# This doesn't seem to be the correct return code
return Http404
form = Form()
return render(request, 'cancel.html', {'form': form})
示例3: report_detail
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def report_detail(request, slug):
"""Render report detail or list of reports in case of wrong report slug is specified"""
data = {}
all_reports = {}
template = 'reporting/reports.html'
report = None
form = Form()
reports_date_init = True
try:
# Retrieving report name by slug specified in an URL
report = reporting.get_report(slug)(request)
except reporting.NoReportException:
pass
if report is not None:
form = report.form_class(request.POST or None)
if request.method == "POST" and form.is_valid():
if request.POST.get('generate', None):
data = report.generate(**form.cleaned_data)
reports_date_init = False
template = report.template_name
else:
# Wrong report slug is specified. rendering all the reports list
all_reports = [(slug, unicode(r.verbose_name)) for slug, r in reporting.all_reports()]
return direct_to_template(request, template, {
'form': form,
'data': data,
'report': report,
'reports_date_init': reports_date_init,
'object_list': all_reports,
})
示例4: setprimary
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def setprimary(request, **kwargs):
team_link = kwargs.get("team_link")
picture_id = kwargs["picture_id"]
account = get_object_or_404(Account, user=request.user)
team = team_link and team_control.get_or_404(team_link) or None
picture = get_object_or_404(Picture, id=picture_id)
prefix = team_link and "/%s" % team_link or ""
url = "%s/gallery/list/%s" % (prefix, picture.gallery.id)
if team:
assert_member(account, team)
if request.method == "POST":
form = Form(request.POST)
if form.is_valid():
control.setprimary(account, picture)
return HttpResponseRedirect(url)
else:
form = Form()
# TODO make template that shows the image being set!
args = {
"form" : form, "form_title" : _("SET_AS_PRIMARY_PICTURE"),
"cancel_url" : url
}
if team:
return rtr(team, None, request, "site/form.html", args)
else:
return render_response(request, "site/form.html", args)
示例5: bill_edit
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def bill_edit(request, id, template_name='membership/entity_edit.html'):
bill = get_object_or_404(Bill, id=id)
class Form(ModelForm):
class Meta:
model = Bill
exclude = ('billingcycle', 'reminder_count')
before = bill.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here
if request.method == 'POST':
form = Form(request.POST, instance=bill)
if form.is_valid():
form.save()
after = bill.__dict__
log_change(bill, request.user, before, after)
messages.success(request, unicode(_("Changes to bill %s saved.") % bill))
return redirect('bill_edit', id) # form stays as POST otherwise if someone refreshes
else:
messages.error(request, unicode(_("Changes to bill %s not saved.") % bill))
else:
form = Form(instance=bill)
logentries = bake_log_entries(bill.logs.all())
return render_to_response(template_name, {'form': form, 'bill': bill,
'logentries': logentries},
context_instance=RequestContext(request))
示例6: delete_tag
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def delete_tag(request, tag_id):
tag = Tag.objects.get(id=tag_id)
if request.method == 'POST':
# use a dummy form just to verify the CSRF token
form = Form(request.POST)
if form.is_valid():
tag.delete()
return redirect(tag.entry.specific_instance())
示例7: logout
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def logout(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
del request.session['ocf_user']
return redirect_back(request)
else:
form = Form()
return render_to_response('logout.html', {
'user': request.session['ocf_user']
}, context_instance=RequestContext(request))
示例8: testJsonResponseWithStatus400ReturnErrorsWhenSettingsSpecifyErrorReporting
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def testJsonResponseWithStatus400ReturnErrorsWhenSettingsSpecifyErrorReporting(self):
settings.DYNAMICRESPONSE_JSON_FORM_ERRORS = True
simple_form = Form()
simple_form.is_valid = Mock(return_value=False)
simple_form.errors[u'SimpleError'] = u'This was a very simple error, shame on you'
simple_form.errors[u'Error2'] = u'This was a bit more serious'
should_equal = simplejson.dumps({'field_errors': simple_form.errors}, indent=0)
dynRes = DynamicResponse({}, extra={ 'form': simple_form }, status=CR_INVALID_DATA)
serialized_result = dynRes.serialize()
self.assertTrue(isinstance(serialized_result, JsonResponse))
self.assertEqual(should_equal, serialized_result.content, 'Correct error message is not returned from JsonResponse')
示例9: upload_file
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def upload_file(request):
if request.method == 'POST':
if request.user.is_authenticated():
print "-------------------------upload file"
form = Form(request.POST, request.FILES)
if form.is_valid():
print "file valid"
print request.FILES
directory = request.POST['directory']
instance = UserFiles(user=request.user,directory=directory, file=request.FILES['file'])
if directory == '':
json_helper.update_file(settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/',
instance.file.name,
settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/'+
instance.file.name)
else:
json_helper.update_file(settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/',
directory+'/'+instance.file.name,
settings.MEDIA_ROOT+'users/'+str(request.user.username)+'/'+
directory + '/' + instance.file.name)
instance.save()
json_helper.logger(settings.MEDIA_ROOT+'log.txt', request.user.username, 'updated file: ', instance.file.name)
response = HttpResponse()
response.content = json.dumps(json_helper.read_json(settings.MEDIA_ROOT+'users/'+
str(request.user.username)+'/file_list.txt'))
response['Content-Type'] = 'application/json'
response.status_code = 200
return response
else:
response = HttpResponse()
response.content = "User not authenticated"
response.status_code = 497
return response
else:
form = Form()
if request.user.is_authenticated:
documents = UserFiles.objects.filter(user__username=request.user.username)
else:
documents = {}
return render_to_response(
'file_demo/upload_file.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
示例10: change_access
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def change_access(request, action, user_pk, login_pk):
user = User.objects.select_related('_profile_cache').get(pk=user_pk)
login = Login.objects.get(pk=login_pk)
if request.method == 'POST':
form = EmptyForm(request.POST) # Using empty form just for CSFR
if form.is_valid():
if action == 'permit':
login.users.add(user)
elif action == 'deny':
login.users.remove(user)
return redirect('ssheepdog.views.view_access_summary')
else:
form = EmptyForm()
return render_to_response('confirm_toggle.html',
{'user': user, 'form': form,
'login': login, 'action': action},
context_instance=RequestContext(request))
示例11: delete
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def delete(request, team_link, page_link):
team = team_control.get_or_404(team_link)
account = get_object_or_404(Account, user=request.user)
assert_member(account, team)
page = get_object_or_404(Page, link=page_link, team=team)
if request.method == "POST":
form = Form(request.POST)
if form.is_valid():
control.delete(account, page)
return HttpResponseRedirect("/%s" % team.link)
else:
form = Form()
cancel_url = "/%s/%s" % (team.link, page.link)
args = {
"form" : form, "form_title" : _("PAGE_DELETE?"),
"form_subtitle" : page.name, "cancel_url" : cancel_url
}
return rtr(team, page.link, request, "site/form.html", args)
示例12: handle
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def handle(request):
user_pro = UserProfile.objects.all()[:4]
blog_post = Post.objects.all()[:4]
if request.method == 'POST':
print('a form is posted')
form_data = Form(request.POST)
if form_data.is_valid():
apply_name = request.POST["contactLname"]
apply_email = request.POST["contactEmail"]
apply_group = request.POST["selectList"]
apply_msg = request.POST["contactMessage"]
information = Handle(
name=apply_name,
email=apply_email,
group=apply_group,
intro=apply_msg,
)
information.save()
return HttpResponseRedirect('/')
示例13: create_app_user
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def create_app_user(request):
try:
data = request.POST if request.POST else json.loads(request.body)
except ValueError:
return HttpResponseBadRequest()
role = data.get('role')
if not role or (role and role not in constants.USER_ROLES.keys()):
return HttpResponseBadRequest(json.dumps('Role not supported'), content_type="application/json")
form = Form()
if role == constants.ROLES.student:
form = StudentForm(data)
elif role == constants.ROLES.teacher:
form = TeacherForm(data)
if form.is_valid():
form.instance.is_active = True
form.instance.set_password(form.cleaned_data['password'])
form.instance.save()
return HttpResponse(json.dumps({'token': Token.objects.last().key,
'role': role}))
else:
return HttpResponseBadRequest(json.dumps(form.errors))
示例14: billingcycle_edit
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def billingcycle_edit(request, id, template_name='membership/entity_edit.html'):
cycle = get_object_or_404(BillingCycle, id=id)
class Form(ModelForm):
is_paid_forced = False
class Meta:
model = BillingCycle
exclude = ('membership', 'start', 'end', 'sum', 'reference_number')
def disable_fields(self):
self.fields['is_paid'].required = False
if cycle.amount_paid() >= cycle.sum and cycle.is_paid:
self.fields['is_paid'].widget.attrs['disabled'] = 'disabled'
self.is_paid_forced = True
def clean_is_paid(self):
if self.is_paid_forced:
return cycle.is_paid
else:
return self.cleaned_data['is_paid']
before = cycle.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here
if request.method == 'POST':
form = Form(request.POST, instance=cycle)
form.disable_fields()
if form.is_valid():
form.save()
after = cycle.__dict__
log_change(cycle, request.user, before, after)
messages.success(request, unicode(_("Changes to billing cycle %s saved.") % cycle))
return redirect('billingcycle_edit', id) # form stays as POST otherwise if someone refreshes
else:
messages.error(request, unicode(_("Changes to bill %s not saved.") % cycle))
else:
form = Form(instance=cycle)
form.disable_fields()
logentries = bake_log_entries(cycle.logs.all())
return render_to_response(template_name, {'form': form, 'cycle': cycle,
'logentries': logentries},
context_instance=RequestContext(request))
示例15: delete
# 需要导入模块: from django.forms import Form [as 别名]
# 或者: from django.forms.Form import is_valid [as 别名]
def delete(request, team_link, blog_id):
# get data
team = team_control.get_or_404(team_link)
account = get_object_or_404(Account, user=request.user)
blog = get_object_or_404(Blog, team=team, id=blog_id)
assert_member(account, team)
if request.method == "POST":
form = Form(request.POST)
if form.is_valid():
control.delete(account, blog)
return HttpResponseRedirect("/%s/blog" % team.link)
else:
form = Form()
args = {
"form": form,
"form_title": _("BLOG_DELETE?"),
"form_subtitle": blog.name,
"cancel_url": "/%s/blog" % team.link,
}
return rtr(team, "blog", request, "site/form.html", args)