本文整理汇总了Python中django.forms.Form类的典型用法代码示例。如果您正苦于以下问题:Python Form类的具体用法?Python Form怎么用?Python Form使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Form类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_payment_process_response
def get_payment_process_response(self, service, order, urls):
address = order.billing_address
payment = Payment(
order_number=order.identifier,
reference_number=order.reference_number[:20],
amount=str(int(order.taxful_total_price * 100)),
delivery_date=(order.order_date.date() + datetime.timedelta(1)).strftime("%Y%m%d"),
return_url=urls.return_url,
delayed_url=urls.return_url,
cancel_url=urls.cancel_url,
message=force_text(order),
contact=Contact(
first_name=flatten_unicode(address.first_name),
last_name=flatten_unicode(address.last_name),
email=flatten_unicode(address.email),
phone=flatten_unicode(address.phone),
address=flatten_unicode(address.street),
postcode=address.postal_code,
postoffice=flatten_unicode(address.city),
country=address.country.alpha3
)
)
form = Form()
for key, value in self._get_checkout_object(service).get_offsite_button_data(payment).items():
form.fields[key] = CharField(initial=value, widget=HiddenInput)
html = TEMPLATE % {
"form": form,
"continue_text": _("Continue to Checkout.fi"),
}
return HttpResponse(html)
示例2: setprimary
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)
示例3: report_detail
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: cancel
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})
示例5: contact_edit
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))
示例6: bill_edit
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))
示例7: __init__
def __init__(self, formdata, request, *args, **kwargs):
Form.__init__(self, formdata, *args, **kwargs)
self.fields["entries_selected"] = ModelMultipleChoiceField(
required=False, queryset=PomEntry.objects.filter(author=request.user)
)
self.fields["categories_selected"] = ModelMultipleChoiceField(
required=False, queryset=PomCategory.objects.filter(pomentry__author=request.user).distinct()
)
self.fields["users_selected"] = ModelMultipleChoiceField(
queryset=User.objects.exclude(username=request.user.username)
)
示例8: delete_tag
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())
示例9: __init__
def __init__(self, user, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
assocs = UserAssociation.objects.filter(user=user)
if assocs.count() == 0:
raise UserAssociation.DoesNotExist()
vals = assocs.order_by('openid_url').values_list('openid_url', flat=True)
self.fields['openid_url_to_delete'].choices = ((val, val) for val in vals)
self._user = user
self._assoc = None
示例10: logout
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))
示例11: testJsonResponseWithStatus400ReturnErrorsWhenSettingsSpecifyErrorReporting
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')
示例12: get_variation_selection_form
def get_variation_selection_form(request, product): # pragma: no cover
# TODO: Does this belong here? Eliding from coverage meanwhile.
variables = ProductVariationVariable.objects.filter(product=product).order_by("name").values_list("id", "name")
values = defaultdict(list)
for var_id, val_id, val in (
ProductVariationVariableValue.objects.filter(variable__product=product)
.values_list("variable_id", "id", "value")
):
values[var_id].append((val_id, val))
form = Form(data=request.POST if request.POST else None)
for variable_id, variable_name in variables:
var_values = sorted(values.get(variable_id, ()))
form.fields["var_%d" % variable_id] = IntegerField(label=variable_name, widget=Select(choices=var_values))
return form
示例13: create_form
def create_form(self, params):
form = Form()
form.fields[self.field_start] = DateField(
label="from date", widget=AdminDateWidget, required=False, initial=params.get(self.field_start, "")
)
form.fields[self.field_end] = DateField(
label="to date", widget=AdminDateWidget, required=False, initial=params.get(self.field_end, "")
)
for k, v in params.items():
if not k.startswith(self.field_generic):
form.fields[k] = CharField(widget=HiddenInput, required=False, initial=v)
return form
示例14: _create_mass_actions_form
def _create_mass_actions_form(self):
"""
Creates the actions form and bounds it to the request.POST
"""
form = Form()
form.fields['_selected_action'] = ChoiceField(
label='Actions',
required = False,
choices=[('', '---')] + [(a.__name__, a.short_description) for a in self.mass_actions]
)
form.fields['_selected_objects'] = CharField(
required = False,
widget=HiddenInput()
)
return form
示例15: upload_file
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)
)