def crossSearchView(request): """ This view generates a implicational-type search where the results from one search are collated against an infinite number of secondary searches :param request: :return: """ mainSearch = formset_factory(NonModelSearchForm, extra=1) crossSearch = formset_factory(NonModelSearchForm, extra=1) if request.method == 'POST': mainresults = mainSearch(request.POST, request.FILES, prefix="ms") crossresults = crossSearch(request.POST, request.FILES, prefix = "cs") if mainresults.is_valid() and crossresults.is_valid(): first = True mainQS = "" #is this necessary? Don't understand python scope dialectQS = None mainsearchtext = "" headerRows = ["Dialect"] bodyRows = [] #Going to be a list of lists for msform in mainresults: #Everything from this section should be 'anded' to produce the final main query if first: mainQS = searchLanguageDatum(msform.cleaned_data, request.user) dialectQS = Dialect.objects.filter(languagedatum__in=mainQS) mainsearchtext = searchText(msform.cleaned_data) + "\n" first = False else: currentQS = searchLanguageDatum(msform.cleaned_data, request.user) dialectQS = dialectQS & Dialect.objects.filter(languagedatum__in=currentQS) mainQS = mainQS.distinct() & currentQS.distinct()#Still need to 'and' to get only those forms that match the criteria mainsearchtext + searchText(msform.cleaned_data) + "\n" finalQS = mainQS.filter(dialect__in=dialectQS) headerRows.append("Main:" + mainsearchtext) dialectsList = Dialect.objects.filter(languagedatum__in=finalQS).distinct().order_by('dialectCode') first = True columnQSs = [finalQS,] for csform in crossresults: #every one of these things is its own search headerRows.append(searchText(csform.cleaned_data)) columnQSs.append(searchLanguageDatum(csform.cleaned_data, request.user)) #Each of these queries should include all of the results of these searches for dl in dialectsList: thisRow = [dl.dialectCode, ] for cqs in columnQSs: filteredQS = cqs.filter(dialect=dl) textofQS = ", ".join([x.normalizedEntry for x in filteredQS]) #converts queryset into list, thence into breaklined text thisRow.append(textofQS) bodyRows.append(thisRow) return render(request, "Cross_search.html", {'pageTitle' : 'Cross Search', 'paradigmDict': paradigmDict.items(), 'mainFormset' : mainresults, 'relatedFormset': crossresults, 'headerRows' : headerRows, 'bodyRows': bodyRows}) else: mainSearchFS = mainSearch(prefix="ms") crossSearchFS = crossSearch(prefix="cs") return render(request, "Cross_search.html", {'pageTitle' : 'Cross Search', 'paradigmDict': paradigmDict.items(), 'mainFormset' : mainSearch(prefix="ms"), 'relatedFormset': crossSearchFS})
def informacion_extra(request, encuesta_id): cosa = get_object_or_404(Encuesta, pk=encuesta_id) #extra = ExtraInformacion(encuesta = encuesta) initial_one = [{'integradas':1}, {'integradas':2}, {'integradas':3}, {'integradas':4}, {'integradas':5}, {'integradas':6}, {'integradas':7} ] initial_two = [{'tipos':1}, {'tipos':2}, {'tipos':3}, {'tipos':4}, {'tipos':5} ] Form1InlineFormSet = formset_factory(ExtraInformacionForm, extra = 7, max_num=7) Form3InlineFormSet = formset_factory(FrecuenciaInfoForm, extra = 5, max_num=5) if request.method == "POST": form1 = Form1InlineFormSet(request.POST) form2 = RubrosManejadosForm(request.POST) form3 = Form3InlineFormSet(request.POST) if form1.is_valid() and form2.is_valid(): for unform1 in form1: obj = unform1.save(commit=False) obj.encuesta = cosa obj.save() unform2 = form2.save(commit=False) unform2.encuesta = cosa unform2.save() for unform3 in form3: obj = unform3.save(commit=False) obj.encuesta = cosa obj.save() return redirect('llenar-encuesta', encuesta_id=cosa.id) else: form1 = Form1InlineFormSet(initial=initial_one) form2 = RubrosManejadosForm() form3 = Form3InlineFormSet(initial=initial_two) return render_to_response('encuesta/extra_info.html', {'form1':form1, 'form2':form2,'form3':form3}, context_instance=RequestContext(request))
def test_uni_form_formset(self): template = get_template_from_string(u""" {% load uni_form_tags %} {% uni_form testFormSet formset_helper %} """) form_helper = FormHelper() form_helper.form_id = 'thisFormsetRocks' form_helper.form_class = 'formsets-that-rock' form_helper.form_method = 'POST' form_helper.form_action = 'simpleAction' from django.forms.models import formset_factory TestFormSet = formset_factory(TestForm, extra = 3) testFormSet = TestFormSet() c = Context({'testFormSet': testFormSet, 'formset_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) self.assertEqual(html.count('<form'), 1) self.assertEqual(html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) self.assertTrue('class="uniForm formsets-that-rock"' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks">' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html)
def get_required_formsets(self): required_metadata = self.content_type_class.required_metadata() ctx = {} formset_pairs = [ ('author', AuthorForm), ('image', ImageForm), ('file', FileForm), ('website', WebsiteForm) ] for key, formKlass in formset_pairs: if key in required_metadata.keys(): formsetKlass = formset_factory( formKlass, min_num=required_metadata[key]['min'], max_num=required_metadata[key]['max'], validate_min=True, validate_max=True, extra=0) formset = formsetKlass(prefix=key, **self.get_form_kwargs()) if( key is "author" and len(formset.forms) == 1 and not formset.forms[0].is_bound ): # remove any unbound author forms, # even though a min is required del formset.forms[0] for form in formset: form.empty_permitted = False ctx["%s_formset" % key] = formset return ctx
def test_formset_with_helper_without_layout(settings): template = get_template_from_string( """ {% load crispy_forms_tags %} {% crispy testFormSet formset_helper %} """ ) form_helper = FormHelper() form_helper.form_id = "thisFormsetRocks" form_helper.form_class = "formsets-that-rock" form_helper.form_method = "POST" form_helper.form_action = "simpleAction" TestFormSet = formset_factory(TestForm, extra=3) testFormSet = TestFormSet() c = Context({"testFormSet": testFormSet, "formset_helper": form_helper, "csrf_token": _get_new_csrf_key()}) html = template.render(c) assert html.count("<form") == 1 assert html.count("<input type='hidden' name='csrfmiddlewaretoken'") == 1 # Check formset management form assert "form-TOTAL_FORMS" in html assert "form-INITIAL_FORMS" in html assert "form-MAX_NUM_FORMS" in html assert "formsets-that-rock" in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse("simpleAction") in html if settings.CRISPY_TEMPLATE_PACK == "uni_form": assert 'class="uniForm' in html
def showProductDetails(request, product_id, product_name=''): """ Shows the product details and a list of the ratings. """ try: p = Product.objects.get(id=product_id,isActive=True) except: raise Http404, "Das Produkt gibt es leider nicht." listname = p.get_option_desc(fieldnb=1) ratings = Rating.objects.all().filter(product__id=product_id) formset = '' new_rating = False try: r = Rating.objects.get(user=request.user, product__id=product_id) except Rating.DoesNotExist: new_rating = True RatingFormSet = formset_factory(RatingForm, max_num=1) init_data = {} init_data['product'] = p.id formset = RatingFormSet(initial=[init_data]) return render_to_response('product/product_detail.html',{ 'listname': listname, 'ratings': ratings, 'product': p, 'new_rating': new_rating, 'formset': formset, }, context_instance=RequestContext(request))
def test_uni_form_formset(self): template = get_template_from_string(u""" {% load uni_form_tags %} {% uni_form testFormSet formset_helper %} """) form_helper = FormHelper() form_helper.form_id = 'this-formset-rocks' form_helper.form_class = 'formsets-that-rock' form_helper.form_method = 'GET' form_helper.form_action = 'simpleAction' from django.forms.models import formset_factory TestFormSet = formset_factory(TestForm, extra = 3) testFormSet = TestFormSet() c = Context({'testFormSet': testFormSet, 'formset_helper': form_helper}) html = template.render(c) self.assertTrue('<form' in html) self.assertEqual(html.count('<form'), 1) self.assertTrue('class="uniForm formsets-that-rock"' in html) self.assertTrue('method="get"' in html) self.assertTrue('id="this-formset-rocks">' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html)
def checkout(request): c = RequestContext(request, dictionary) CheckoutFormSet = formset_factory(CheckoutForm) if request.method == "POST": formset = CheckoutFormSet(data = request.POST) if formset.is_valid(): for form in formset: form.save() c['valid'] = formset.is_valid() else: formset = CheckoutFormSet() extraBooksFormset = formset_factory(ExtraBookCheckoutForm) c['form'] = CheckoutFormSet c['extraBooksFormset'] = extraBooksFormset c['context'] = 'checkout' return render_to_response('lib_admin/checkout.html', {}, c)
def test_formset_with_helper_without_layout(self): template = loader.get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy testFormSet formset_helper %} """) form_helper = FormHelper() form_helper.form_id = 'thisFormsetRocks' form_helper.form_class = 'formsets-that-rock' form_helper.form_method = 'POST' form_helper.form_action = 'simpleAction' TestFormSet = formset_factory(TestForm, extra = 3) testFormSet = TestFormSet() c = Context({'testFormSet': testFormSet, 'formset_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) self.assertEqual(html.count('<form'), 1) self.assertEqual(html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) # Check formset management form self.assertTrue('form-TOTAL_FORMS' in html) self.assertTrue('form-INITIAL_FORMS' in html) self.assertTrue('form-MAX_NUM_FORMS' in html) self.assertTrue('formsets-that-rock' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks"' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html) if (self.current_template_pack == 'uni_form'): self.assertTrue('class="uniForm' in html)
def test_uni_form_formset(self): template = get_template_from_string( u""" {% load uni_form_tags %} {% uni_form testFormSet formset_helper %} """ ) form_helper = FormHelper() form_helper.form_id = "thisFormsetRocks" form_helper.form_class = "formsets-that-rock" form_helper.form_method = "POST" form_helper.form_action = "simpleAction" TestFormSet = formset_factory(TestForm, extra=3) testFormSet = TestFormSet() c = Context({"testFormSet": testFormSet, "formset_helper": form_helper, "csrf_token": _get_new_csrf_key()}) html = template.render(c) self.assertEqual(html.count("<form"), 1) self.assertEqual(html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) self.assertTrue('class="uniForm formsets-that-rock"' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks">' in html) self.assertTrue('action="%s"' % reverse("simpleAction") in html)
def test_formset_with_helper_without_layout(settings): template = Template(""" {% load crispy_forms_tags %} {% crispy testFormSet formset_helper %} """) form_helper = FormHelper() form_helper.form_id = 'thisFormsetRocks' form_helper.form_class = 'formsets-that-rock' form_helper.form_method = 'POST' form_helper.form_action = 'simpleAction' SampleFormSet = formset_factory(SampleForm, extra=3) testFormSet = SampleFormSet() c = Context({'testFormSet': testFormSet, 'formset_helper': form_helper, 'csrf_token': _get_new_csrf_key()}) html = template.render(c) assert html.count('<form') == 1 assert html.count("<input type='hidden' name='csrfmiddlewaretoken'") == 1 # Check formset management form assert 'form-TOTAL_FORMS' in html assert 'form-INITIAL_FORMS' in html assert 'form-MAX_NUM_FORMS' in html assert 'formsets-that-rock' in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse('simpleAction') in html if settings.CRISPY_TEMPLATE_PACK == 'uni_form': assert 'class="uniForm' in html
def bet(request): if not request.user.is_authenticated: return HttpResponseRedirect('/accounts/login/?next=%s' % request.path) context = RequestContext(request=request) BetFormSet = formset_factory(BetForm, extra=0) initial_data = [] info_data = [] locked = [] if request.method == 'POST': formset = BetFormSet(request.POST) if formset.is_valid(): print formset.cleaned_data # Process the data in form.cleaned_data return HttpResponseRedirect('/matches') else: for match in Match.objects.filter(date__gt=datetime.now() - timedelta(minutes=15)).order_by('date'): data = { 'match': match.pk, 'user': request.user.pk } info_data.append(match) initial_data.append(data) formset = BetFormSet(initial=initial_data) for match in Match.objects.filter(date__lte=datetime.now() - timedelta(minutes=15)).order_by('date'): ###print Bet.objects.get(match=match.id, user=request.user.pk) data = { 'match': match, 'bet': Bet.objects.filter(match=match).filter(user=request.user)} print data locked.append(data) context['locked'] = locked context['formset'] = zip(info_data, formset) return render_to_response('bet_list.html', context)
def add_rules(request, template_name="compass_tweets/add_rules.html"): if not 'context' in request.session: raise Http404 context = request.session['context'] RuleForm = make_rule_form(context) RuleFormSet = formset_factory(form=RuleForm, extra =10) if request.POST: ruleformset=RuleFormSet(request.POST, prefix='rules') print ruleformset.data if ruleformset.is_valid(): for rf in ruleformset.forms: if not rf.cleaned_data.get('message_type') == None: #terrible hack, please correct message = rf.cleaned_data.get('message_type') sender = rf.cleaned_data.get('sender_role') receiver = rf.cleaned_data.get('receiver_role') rule, created = Rule.objects.get_or_create(message_type=message,sender_role=sender,receiver_role=receiver) if not created: rule.save() context.rules.add(rule) return HttpResponseRedirect(reverse('add_members')) else: return HttpResponse(ruleformset.errors) else: ruleformset=RuleFormSet(prefix='rules') return render_to_response(template_name,{"ruleformset":ruleformset,"contextname":context.name})
def submit(request): PhotoFormSet = formset_factory(PhotoForm, extra=1) if request.method == 'POST': storyform = StoryForm(request.POST, request.FILES) photoformset = PhotoFormSet(request.POST, request.FILES) if storyform.is_valid() and photoformset.is_valid(): s = Story( title = storyform.cleaned_data['title'], moderator = request.user ) s.save(); for form in photoformset.cleaned_data: image = form['image'] p = Photo( name=s.title, story=s, image=image ) p.save() else: storyform = StoryForm() photoformset = PhotoFormSet() return render(request, 'stories/submit.html', {'storyfrom': storyform, 'photoformset': photoformset})
def crear_Post(request): logger.debug("Hemos entrado en mi_vista: crear_Post") pformset = PostForm tformset = formset_factory(TagForm, extra=4, can_delete=False) if request.method == "POST": formset = pformset(request.POST, request.FILES, prefix="post") tagformset = tformset(request.POST, request.FILES, prefix="tag") logger.debug("Formulario Crear Valido...") if formset.is_valid(): post = formset.save(commit=False) post.autor = request.user post.save() logger.debug("Post: " + str(post.id)) for tag in tagformset: t = tag.save(commit=False) if not (t.etiqueta is None or t.etiqueta == ""): try: t = Tag.objects.get(etiqueta=t.etiqueta) except Tag.DoesNotExist: t.save() logger.debug(" Tag id: " + str(t.id)) Post_Tag.objects.create(post=post, tag=t) cantidad = Post.activo.all().count() / 5 return HttpResponseRedirect("/blog/") else: formset = pformset(prefix="post") tagformset = tformset(prefix="tag") return direct_to_template(request, "blog/post/post_form.html", {"form": formset, "tform": tagformset})
def post(self, *args, **kwargs): self.asset_id = self.kwargs.get('asset_id') self.asset = Asset.objects.get(id=self.asset_id) AssetFormSet = formset_factory( form=SplitDevice, extra=0, ) self.asset_formset = AssetFormSet(self.request.POST) if self.asset_formset.is_valid(): with transaction.commit_on_success(): for instance in self.asset_formset.forms: form = instance.save(commit=False) model_name = instance['model_user'].value() form.model = self.create_asset_model(model_name) form.type = AssetType.data_center form.part_info = self.create_part_info() form.modified_by = self.request.user.get_profile() form.save(user=self.request.user) messages.success(self.request, _("Changes saved.")) return HttpResponseRedirect(self.request.get_full_path()) self.valid_duplicates('sn') self.valid_duplicates('barcode') self.valid_total_price() messages.error(self.request, _("Please correct the errors.")) return super(SplitDeviceView, self).get(*args, **kwargs)
def test_formset_layout(self): template = get_template_from_string(u""" {% load crispy_forms_tags %} {% crispy testFormSet formset_helper %} """) form_helper = FormHelper() form_helper.form_id = 'thisFormsetRocks' form_helper.form_class = 'formsets-that-rock' form_helper.form_method = 'POST' form_helper.form_action = 'simpleAction' form_helper.add_layout( Layout( Fieldset("Item {{ forloop.counter }}", 'is_company', 'email', ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row('password1', 'password2'), Fieldset("", 'first_name', 'last_name' ) ) ) TestFormSet = formset_factory(TestForm, extra = 3) testFormSet = TestFormSet() c = Context({ 'testFormSet': testFormSet, 'formset_helper': form_helper, 'csrf_token': _get_new_csrf_key() }) html = template.render(c) # Check form parameters self.assertEqual(html.count('<form'), 1) self.assertEqual(html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) self.assertTrue('formsets-that-rock' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks"' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html) # Check form layout self.assertTrue('Item 1' in html) self.assertTrue('Item 2' in html) self.assertTrue('Item 3' in html) self.assertEqual(html.count('Note for first form only'), 1) if settings.CRISPY_TEMPLATE_PACK == 'uni_form': self.assertEqual(html.count('formRow'), 3) else: self.assertEqual(html.count('row'), 3)
def articleEdit(request, category, slg, errMsg="", msg=""): returnForm, language = init(request) returnForm = setMsg(returnForm) currentArticle = Article.objects.get(slg=slg) try: assert request.user.is_staff or (request.user.userprofile in currentArticle.author.all()) except: return HttpResponseRedirect(reverse('article', args=(category,slg,))) ImageFormSet = formset_factory(form=ImgForm, extra=3, max_num=10) selectedLang = request.GET.get('lang',language) try: returnForm = getArticleInfo(slg,returnForm,selectedLang) except: return HttpResponseRedirect('/') if not selectedLang in [ a[0] for a in settings.LANGUAGES]: return HttpResponseRedirect('/') if request.method == 'POST': form = ArticleForm(request.POST) data = request.POST files = request.FILES currentGallery = [{'imgfile':x.imgfile} for x in returnForm['currentGallery']] formset = ImageFormSet(data,files,initial=currentGallery) success, label = updateArticle(request.user.is_staff,currentArticle,data,formset,files,language=selectedLang) if success: try: articleContent = currentArticle.article.get(language=selectedLang) except: articleContent = ArticleContent.objects.create(language=selectedLang,title=data['title'],article=currentArticle) articleContent.title = data['title'] articleContent.abstract = data['abstract'] articleContent.content = data['content'] articleContent.status = 1 articleContent.save() path = reverse('articlePreview', args=(str(category),slg,),) return HttpResponseRedirect(url_with_querystring(path,{'lang':selectedLang})) else: try: returnForm['msg'] += "Edit article <b>" + str(returnForm['currentArticleContent']) + " (Version : " + selectedLang + "). </b>" except: returnForm['msg'] += "Translate article <b> No. " + str(currentArticle.id) + " (Version : " + selectedLang + "). </b>" if currentArticle.article.count() != len(settings.LANGUAGES): returnForm['warnMsg'] += "This article's translations aren't completed. <a href='./status'> More detail </a>" articleForm = ArticleForm() numeros = Numero.objects.all() categoryFR = CategoryDetail.objects.filter(language='fr') categoryTW = CategoryDetail.objects.filter(language='tw') returnForm['selectedLang'] = selectedLang returnForm['formset'] = ImageFormSet(initial=[{'imgfile':x.imgfile} for x in returnForm['currentGallery']]) returnForm['form'] = articleForm returnForm['categoryFR'] = categoryFR returnForm['categoryTW'] = categoryTW returnForm['users'] = getUsersLst(request.user,article=currentArticle) returnForm['action'] = 'edit' return render(request, 'admin/createArticle.html', returnForm)
def event_verify(request, eventId): eventFormset = formset_factory(ShiftEndReportForm) event = Event.objects.get(id=eventId) shifts = [] for shift in event.shifts.all(): end_report = dict(shift_id=shift.id, event_id=event.id, verified=False, signed=request.user) shifts.append(end_report) print shifts form = eventFormset(initial=shifts) return render_to_response('shift_verify.html', dict(form=form))
def test07(self): form_class = modelform_factory(Country) fs_class = formset_factory(form_class,can_delete=True) fs = fs_class() s=fs.forms[0].as_table() #print "\n"+s self.assertEquals(s.split(),u""" <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" maxlength="200" /></td></tr> <tr><th><label for="id_form-0-isocode">Isocode:</label></th><td><input id="id_form-0-isocode" type="text" name="form-0-isocode" maxlength="2" /></td></tr> <tr><th><label for="id_form-0-DELETE">Delete:</label></th><td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE" /></td></tr> """.split())
def formset_error_bkp(request): #wdb.set_trace() FormSetClass = formset_factory(CustomForm, formset=CustomFormset, extra=2) if request.method == 'POST': print(request.POST) formset = FormSetClass(request.POST) if formset.is_valid(): pass else: formset = FormSetClass() return render(request, "OOModel/form.html", { 'formset': formset })
def create_exchange_formset(context_agent, assoc_type_identifier, prefix, data=None): ExchangeFormSet = formset_factory(MultipleExchangeEventForm, extra=10) #init = {"paid": "paid"} formset = ExchangeFormSet(data=data, prefix=prefix) to_agents = context_agent.all_has_associates_by_type(assoc_type_identifier=assoc_type_identifier) for form in formset: #id = int(form["facet_id"].value()) form.fields["to_agent"].queryset = to_agents form.fields["paid_stage_1"].initial = "never" form.fields["paid_stage_2"].initial = "later" return formset
def test05(self): form_class = modelform_factory(Contact) fs_class = formset_factory(form_class,can_delete=True,extra=1) fs = fs_class() s=fs.as_table() #print "\n"+s self.assertEquals(s.split(),u""" <input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /> <tr><th><label for="id_form-0-fname">Fname:</label></th><td><input id="id_form-0-fname" type="text" name="form-0-fname" maxlength="20" /></td></tr> <tr><th><label for="id_form-0-lname">Lname:</label></th><td><input id="id_form-0-lname" type="text" name="form-0-lname" maxlength="20" /></td></tr> <tr><th><label for="id_form-0-DELETE">Delete:</label></th><td><input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE" /></td></tr> """.split())
def articleStatus(request, category, slg, errMsg="", msg=""): returnForm, language = init(request) returnForm = setMsg(returnForm) currentArticle = Article.objects.get(slg=slg) try: assert request.user.is_staff or request.user.userprofile in currentArticle.author.all() except: return HttpResponseRedirect(reverse('article', args=(category,slg,))) try: returnForm = getArticleInfo(slg,returnForm,language) except: return HttpResponseRedirect('/') currentGallery = [{'imgfile':x.imgfile} for x in returnForm['currentGallery']] ImageFormSet = formset_factory(form=ImgForm, extra=3, max_num=10) if request.method == 'POST': form = ArticleForm(request.POST) data = request.POST files = request.FILES formset = ImageFormSet(data,files,initial=currentGallery) success, label = updateArticle(request.user.is_staff,currentArticle,data,formset,files,language=language) request.method="" if success: return articleStatus(request, category, slg, msg=label) else: return articleStatus(request, category, slg, errMsg=label) else: returnForm["msg"] += "Status of article <b> No. " + str(currentArticle.id) + "</b>." articleForm = ArticleForm() numeros = Numero.objects.all() categoryFR = CategoryDetail.objects.filter(language='fr') categoryTW = CategoryDetail.objects.filter(language='tw') users = getUsersLst(request.user,article=currentArticle) contentStatus = currentArticle.article.values("status","title","language").all() statusLst = [] for lang in settings.LANGUAGES: exists = False for t in contentStatus: if t['language']==lang[0]: exists=True statusLst.append(t) break if not exists: statusLst.append({'status':0,'title':'','language':lang[0]}) returnForm['statusLst'] = sorted(statusLst, key=itemgetter('language')) returnForm['formset'] = ImageFormSet(initial=currentGallery) returnForm['form'] = articleForm returnForm['categoryFR'] = categoryFR returnForm['categoryTW'] = categoryTW returnForm['users'] = users returnForm['action'] = 'status' returnForm['selectedLang'] = language return render(request, 'admin/articleStatus.html', returnForm)
def post(self, request, *args, **kwargs): self.options = self.get_options() catering_items = Item.objects.filter(catering_active=True)\ .order_by('section', 'position') CateringFormSet = formset_factory(CateringForm) catering_formset = CateringFormSet(data=request.POST, prefix='catering') contact_form = ContactForm(data=request.POST, prefix='contact') if catering_formset.is_valid() and contact_form.is_valid(): cleaned_catering_items_and_formset = zip( catering_items, catering_formset.cleaned_data) cleaned_contact_form = contact_form.cleaned_data message_context = {} message_context['contact_form'] = cleaned_contact_form message_context['catering_items_and_formset'] = \ cleaned_catering_items_and_formset html_message = render_to_string( 'catering/email.html', message_context) message_context = {} message_context['catering_email_confirmation_copy'] = \ self.options.catering_email_confirmation_copy.strip() message = render_to_string( 'catering/email.txt', message_context) send_mail( from_email=getattr(settings, 'SERVER_EMAIL'), recipient_list=[self.options.catering_orders_email], subject='Pop\'s SeaBar Catering Order Received', message='', html_message=html_message) # TODO: move trimming to the model send_mail( from_email=getattr(settings, 'SERVER_EMAIL'), recipient_list=[cleaned_contact_form['email']], subject='Pop\'s SeaBar Catering Order Confirmation', message=message) return HttpResponseRedirect(self.get_success_url()) else: catering_items_and_formset = zip(catering_items, catering_formset) return self.render_to_response( self.get_context_data( catering_items=catering_items, catering_formset=catering_formset, catering_items_and_formset=catering_items_and_formset, contact_form=contact_form))
def consumable_formset(consumable_rt, data=None): ConsumableFormSet = formset_factory(form=ConsumableForm, extra=0) init = [] consumable_resources = EconomicResource.objects.filter(resource_type=consumable_rt) for res in consumable_resources: d = {"resource_id": res.id,} init.append(d) formset = ConsumableFormSet(initial=init, data=data) for form in formset: id = int(form["resource_id"].value()) resource = EconomicResource.objects.get(id=id) form.identifier = resource.identifier return formset
def test_as_crispy_errors_formset_without_non_form_errors(): template = get_template_from_string(""" {% load crispy_forms_tags %} {{ formset|as_crispy_errors }} """) TestFormset = formset_factory(TestForm, max_num=1, validate_max=True) formset = TestFormset() formset.is_valid() c = Context({'formset': formset}) html = template.render(c) assert not ("errorMsg" in html or "alert" in html)
def __call__(self, request, *args, **kwargs): context = {} if 'context' in kwargs: context = kwargs['context'] project_name = kwargs['project_name'] project = m.Project.objects.get(title=project_name) messagesFromProject = m.Messages_from_project_to_project.getMessagesFromProject(project) messagesToProject = m.Messages_from_project_to_project.getMessagesToProject(project) combinedMessages = [] for message in messagesFromProject: message.type = 1 #type 1 means the project is the sender combinedMessages.append(message) for message in messagesToProject: message.type = 2 #type 2 means the project is the receiver combinedMessages.append(message) combinedMessages = sorted(combinedMessages, key=attrgetter('timestamp'), reverse=True) #setup the relevant recipients for messaging uniqueRecipientProject = set() for message in combinedMessages: if message.type == 1: uniqueRecipientProject.add(message.project_id_to) else: uniqueRecipientProject.add(message.project_id_from) projects = [] #setup the messages per recipient of interest for recipientProject in uniqueRecipientProject: messageListForProject = [] projects.append( [ recipientProject, messageListForProject ] ) for message in combinedMessages: if message.type == 1 and message.project_id_to == recipientProject: messageListForProject.append(message) elif message.type == 2 and message.project_id_from == recipientProject: messageListForProject.append(message) #setup the message convo forms for each project messageFormSet = formset_factory(MessageConvoForm, extra=len(projects)) context['projectMessageFormSetFactory'] = messageFormSet projectMessageFormSet = messageFormSet(prefix='projects') for form, currProject in zip(projectMessageFormSet, projects): form.fields['recipient'].initial = currProject[0].title currProject.append(form) context['projectMessageFormSet'] = projectMessageFormSet context['projects'] = projects m.Messages_from_project_to_project.messagesRead(project) return self.orig_func(request, *args, **kwargs)
def get(self, *args, **kwargs): url_parents_ids = self.request.GET.getlist('select') self.selected_parents = self.Parent.objects.filter( pk__in=url_parents_ids, ) if not self.selected_parents.exists(): messages.warning(self.request, _("Nothing to edit.")) return HttpResponseRedirect(get_return_link(self.mode)) AttachmentFormset = formset_factory( form=AttachmentForm, extra=1, ) self.attachments_formset = AttachmentFormset() return super(AddAttachment, self).get(*args, **kwargs)
def uploadImg(request): returnForm, language = init(request) returnForm = setMsg(returnForm) ImageFormSet = formset_factory(form=ImgForm, extra = 3, max_num=10) if request.method == 'POST': formset = ImageFormSet(request.POST, request.FILES) if formset.is_valid(): for form in formset.cleaned_data: if form != {}: title = str(form['imgfile']) newImg = Img(imgfile = form['imgfile'], imgfile_m = form['imgfile'], imgfile_s = form['imgfile'], title=title) newImg.save() returnForm['formset'] = ImageFormSet return render(request,'admin/upload.html', returnForm)
self._errors = {} self.cls.full_clean() self._errors.update(self.cls._errors) return self._errors def is_valid(self): flag = super(ComputerClassForm, self).is_valid() return self.cls.is_valid() and flag def save(self, commit=True): cls = self.cls.save() obj = super(ComputerClassForm, self).save(commit=False) obj.class_bind_to = cls obj.client_number = self.cleaned_data['client_number'] if commit: obj.save() obj.computerclasslessonrange_set.all().delete() for u in self.lesson_range: models.ComputerClassLessonRange.objects.create( computerclass=obj, lessonname=u) return obj class Meta: model = models.ComputerClass fields = [ 'client_number', ] ComputerClassFormSet = formset_factory(ComputerClassForm)
import itertools from django import forms from django.forms.models import BaseFormSet, formset_factory from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django.utils.translation import ugettext as _ from .models import Dish, Ingredient from teams.models import Team # class DishForm(forms.Form): # blank_choice = [('',_('Chose a team'))] # TEAM_CHOICES = Team.objects.all() # name = forms.CharField() # team = forms.ChoiceField(widget=forms.Select(), # choices=(itertools.chain(blank_choice, ((x.name, x.name) for x in TEAM_CHOICES)))) class DishForm(forms.ModelForm): class Meta: model = Dish fields = '__all__' class IngredientForm(forms.Form): name = forms.CharField() qty_used = forms.IntegerField(label=_('Quantity Used')) IngrdientFormset = formset_factory(IngredientForm, extra=1)
def test_formset_layout(settings): TestFormSet = formset_factory(TestForm, extra=3) formset = TestFormSet() helper = FormHelper() helper.form_id = 'thisFormsetRocks' helper.form_class = 'formsets-that-rock' helper.form_method = 'POST' helper.form_action = 'simpleAction' helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", 'is_company', 'email', ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row('password1', 'password2'), Fieldset( "", 'first_name', 'last_name' ) ) html = render_crispy_form( form=formset, helper=helper, context={'csrf_token': _get_new_csrf_key()} ) # Check formset fields hidden_count = 4 # before Django 1.7 added MIN_NUM_FORM_COUNT if django.VERSION < (1, 5): assert html.count( 'type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS"' ) == 1 assert html.count( 'type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"' ) == 1 assert html.count( 'type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"' ) == 1 else: assert html.count( 'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"' ) == 1 assert html.count( 'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"' ) == 1 assert html.count( 'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"' ) == 1 if hasattr(forms.formsets, 'MIN_NUM_FORM_COUNT'): assert html.count( 'id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"' ) == 1 hidden_count += 1 assert html.count("hidden") == hidden_count # Check form structure assert html.count('<form') == 1 assert html.count("<input type='hidden' name='csrfmiddlewaretoken'") == 1 assert 'formsets-that-rock' in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse('simpleAction') in html # Check form layout assert 'Item 1' in html assert 'Item 2' in html assert 'Item 3' in html assert html.count('Note for first form only') == 1 if settings.CRISPY_TEMPLATE_PACK == 'uni_form': assert html.count('formRow') == 3 else: assert html.count('row') == 3
def get_page_context(page, user, resource_edit=False, extended_metadata_layout=None, request=None): """ :param page: which page to get the template context for :param user: the user who is viewing the page :param resource_edit: True if and only if the page should render in edit mode :param extended_metadata_layout: layout information used to build an ExtendedMetadataForm :param request: the Django request associated with the page load :return: the basic template context (a python dict) used to render a resource page. can and should be extended by page/resource-specific page_processors TODO: refactor to make it clear that there are two different modes = EDITABLE | READONLY - split into two functions: get_readonly_page_context(...) and get_editable_page_context(...) """ file_type_error = '' if request: file_type_error = request.session.get("file_type_error", None) if file_type_error: del request.session["file_type_error"] content_model = page.get_content_model() # whether the user has permission to view this resource can_view = content_model.can_view(request) if not can_view: raise PermissionDenied() discoverable = content_model.raccess.discoverable validation_error = None resource_is_mine = False if user.is_authenticated(): resource_is_mine = content_model.rlabels.is_mine(user) metadata_status = _get_metadata_status(content_model) belongs_to_collections = content_model.collections.all() relevant_tools = None tool_homepage_url = None if not resource_edit: # In view mode content_model_str = str(content_model.content_model).lower() if content_model_str.lower() == "toolresource": if content_model.metadata.homepage_url.exists(): tool_homepage_url = content_model.metadata.homepage_url.first( ).value relevant_tools = [] # loop through all SupportedResTypes objs (one webapp resources has one # SupportedResTypes obj) for res_type in SupportedResTypes.objects.all(): supported_flag = False for supported_type in res_type.supported_res_types.all(): if content_model_str == supported_type.description.lower(): supported_flag = True break if supported_flag: # reverse lookup: metadata obj --> res obj tool_res_obj = ToolResource.objects.get( object_id=res_type.object_id) if tool_res_obj: sharing_status_supported = False supported_sharing_status_obj = tool_res_obj.metadata.\ supported_sharing_status.first() if supported_sharing_status_obj is not None: suppored_sharing_status_str = supported_sharing_status_obj.\ get_sharing_status_str() if len(suppored_sharing_status_str) > 0: res_sharing_status = content_model.raccess.sharing_status if suppored_sharing_status_str.lower().\ find(res_sharing_status.lower()) != -1: sharing_status_supported = True else: # backward compatible: webapp without supported_sharing_status metadata # is considered to support all sharing status sharing_status_supported = True if sharing_status_supported: is_authorized = authorize( request, tool_res_obj.short_id, needed_permission=ACTION_TO_AUTHORIZE. VIEW_RESOURCE, raises_exception=False)[1] if is_authorized: tool_url = tool_res_obj.metadata.url_bases.first().value \ if tool_res_obj.metadata.url_bases.first() else None tool_icon_url = tool_res_obj.metadata.tool_icon.first().value \ if tool_res_obj.metadata.tool_icon.first() else "raise-img-error" hs_term_dict_user = {} hs_term_dict_user["HS_USR_NAME"] = request.user.username if \ request.user.is_authenticated() else "anonymous" tool_url_new = parse_app_url_template( tool_url, [ content_model.get_hs_term_dict(), hs_term_dict_user ]) if tool_url_new is not None: tl = { 'title': str(tool_res_obj.metadata.title.value), 'icon_url': tool_icon_url, 'url': tool_url_new } relevant_tools.append(tl) just_created = False just_copied = False create_resource_error = None just_published = False if request: validation_error = check_for_validation(request) just_created = request.session.get('just_created', False) if 'just_created' in request.session: del request.session['just_created'] just_copied = request.session.get('just_copied', False) if 'just_copied' in request.session: del request.session['just_copied'] create_resource_error = request.session.get('resource_creation_error', None) if 'resource_creation_error' in request.session: del request.session['resource_creation_error'] just_published = request.session.get('just_published', False) if 'just_published' in request.session: del request.session['just_published'] bag_url = AbstractResource.bag_url(content_model.short_id) if user.is_authenticated(): show_content_files = user.uaccess.can_view_resource(content_model) else: # if anonymous user getting access to a private resource (since resource is discoverable), # then don't show content files show_content_files = content_model.raccess.public allow_copy = can_user_copy_resource(content_model, user) # user requested the resource in READONLY mode if not resource_edit: temporal_coverages = content_model.metadata.coverages.all().filter( type='period') if len(temporal_coverages) > 0: temporal_coverage_data_dict = {} temporal_coverage = temporal_coverages[0] temporal_coverage_data_dict[ 'start_date'] = temporal_coverage.value['start'] temporal_coverage_data_dict['end_date'] = temporal_coverage.value[ 'end'] temporal_coverage_data_dict['name'] = temporal_coverage.value.get( 'name', '') else: temporal_coverage_data_dict = None spatial_coverages = content_model.metadata.coverages.all().exclude( type='period') if len(spatial_coverages) > 0: spatial_coverage_data_dict = {} spatial_coverage = spatial_coverages[0] spatial_coverage_data_dict['name'] = spatial_coverage.value.get( 'name', None) spatial_coverage_data_dict['units'] = spatial_coverage.value[ 'units'] spatial_coverage_data_dict['zunits'] = spatial_coverage.value.get( 'zunits', None) spatial_coverage_data_dict[ 'projection'] = spatial_coverage.value.get('projection', None) spatial_coverage_data_dict['type'] = spatial_coverage.type if spatial_coverage.type == 'point': spatial_coverage_data_dict['east'] = spatial_coverage.value[ 'east'] spatial_coverage_data_dict['north'] = spatial_coverage.value[ 'north'] spatial_coverage_data_dict[ 'elevation'] = spatial_coverage.value.get( 'elevation', None) else: spatial_coverage_data_dict[ 'northlimit'] = spatial_coverage.value['northlimit'] spatial_coverage_data_dict[ 'eastlimit'] = spatial_coverage.value['eastlimit'] spatial_coverage_data_dict[ 'southlimit'] = spatial_coverage.value['southlimit'] spatial_coverage_data_dict[ 'westlimit'] = spatial_coverage.value['westlimit'] spatial_coverage_data_dict[ 'uplimit'] = spatial_coverage.value.get('uplimit', None) spatial_coverage_data_dict[ 'downlimit'] = spatial_coverage.value.get( 'downlimit', None) else: spatial_coverage_data_dict = None keywords = ",".join( [sub.value for sub in content_model.metadata.subjects.all()]) languages_dict = dict(languages_iso.languages) language = languages_dict[content_model.metadata.language.code] if \ content_model.metadata.language else None title = content_model.metadata.title.value if content_model.metadata.title else None abstract = content_model.metadata.description.abstract if \ content_model.metadata.description else None missing_metadata_elements = content_model.metadata.get_required_missing_elements( ) context = { 'resource_edit_mode': resource_edit, 'metadata_form': None, 'citation': content_model.get_citation(), 'title': title, 'abstract': abstract, 'creators': content_model.metadata.creators.all(), 'contributors': content_model.metadata.contributors.all(), 'temporal_coverage': temporal_coverage_data_dict, 'spatial_coverage': spatial_coverage_data_dict, 'language': language, 'keywords': keywords, 'rights': content_model.metadata.rights, 'sources': content_model.metadata.sources.all(), 'relations': content_model.metadata.relations.all(), 'show_relations_section': show_relations_section(content_model), 'fundingagencies': content_model.metadata.funding_agencies.all(), 'metadata_status': metadata_status, 'missing_metadata_elements': missing_metadata_elements, 'validation_error': validation_error if validation_error else None, 'resource_creation_error': create_resource_error, 'relevant_tools': relevant_tools, 'tool_homepage_url': tool_homepage_url, 'file_type_error': file_type_error, 'just_created': just_created, 'just_copied': just_copied, 'just_published': just_published, 'bag_url': bag_url, 'show_content_files': show_content_files, 'discoverable': discoverable, 'resource_is_mine': resource_is_mine, 'allow_resource_copy': allow_copy, 'is_resource_specific_tab_active': False, 'belongs_to_collections': belongs_to_collections } if 'task_id' in request.session: task_id = request.session.get('task_id', None) if task_id: context['task_id'] = task_id del request.session['task_id'] if 'download_path' in request.session: download_path = request.session.get('download_path', None) if download_path: context['download_path'] = download_path del request.session['download_path'] return context # user requested the resource in EDIT MODE # whether the user has permission to change the model can_change = content_model.can_change(request) if not can_change: raise PermissionDenied() add_creator_modal_form = CreatorForm(allow_edit=can_change, res_short_id=content_model.short_id) add_contributor_modal_form = ContributorForm( allow_edit=can_change, res_short_id=content_model.short_id) add_relation_modal_form = RelationForm(allow_edit=can_change, res_short_id=content_model.short_id) add_source_modal_form = SourceForm(allow_edit=can_change, res_short_id=content_model.short_id) add_fundingagency_modal_form = FundingAgencyForm( allow_edit=can_change, res_short_id=content_model.short_id) keywords = ",".join( [sub.value for sub in content_model.metadata.subjects.all()]) subjects_form = SubjectsForm(initial={'value': keywords}, allow_edit=can_change, res_short_id=content_model.short_id, element_id=None) abstract_form = AbstractForm( instance=content_model.metadata.description, allow_edit=can_change, res_short_id=content_model.short_id, element_id=content_model.metadata.description.id if content_model.metadata.description else None) CreatorFormSetEdit = formset_factory(wraps(CreatorForm)(partial( CreatorForm, allow_edit=can_change)), formset=BaseCreatorFormSet, extra=0) creator_formset = CreatorFormSetEdit( initial=content_model.metadata.creators.all().values(), prefix='creator') index = 0 # TODO: dont track index manually. use enumerate, or zip for creator_form in creator_formset.forms: creator_form.action = "/hsapi/_internal/%s/creator/%s/update-metadata/" % \ (content_model.short_id, creator_form.initial['id']) creator_form.number = creator_form.initial['id'] index += 1 ContributorFormSetEdit = formset_factory(wraps(ContributorForm)(partial( ContributorForm, allow_edit=can_change)), formset=BaseContributorFormSet, extra=0) contributor_formset = ContributorFormSetEdit( initial=content_model.metadata.contributors.all().values(), prefix='contributor') index = 0 # TODO: dont track index manually. use enumerate, or zip for contributor_form in contributor_formset.forms: contributor_form.action = "/hsapi/_internal/%s/contributor/%s/update-metadata/" % \ (content_model.short_id, contributor_form.initial['id']) contributor_form.number = contributor_form.initial['id'] index += 1 RelationFormSetEdit = formset_factory(wraps(RelationForm)(partial( RelationForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) relation_formset = RelationFormSetEdit( initial=content_model.metadata.relations.all().values(), prefix='relation') for relation_form in relation_formset.forms: relation_form.action = "/hsapi/_internal/%s/relation/%s/update-metadata/" % \ (content_model.short_id, relation_form.initial['id']) relation_form.number = relation_form.initial['id'] SourceFormSetEdit = formset_factory(wraps(SourceForm)(partial( SourceForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) source_formset = SourceFormSetEdit( initial=content_model.metadata.sources.all().values(), prefix='source') for source_form in source_formset.forms: source_form.action = "/hsapi/_internal/%s/source/%s/update-metadata/" % \ (content_model.short_id, source_form.initial['id']) source_form.delete_modal_form = MetaDataElementDeleteForm( content_model.short_id, 'source', source_form.initial['id']) source_form.number = source_form.initial['id'] FundingAgencyFormSetEdit = formset_factory(wraps(FundingAgencyForm)( partial(FundingAgencyForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) fundingagency_formset = FundingAgencyFormSetEdit( initial=content_model.metadata.funding_agencies.all().values(), prefix='fundingagency') for fundingagency_form in fundingagency_formset.forms: action = "/hsapi/_internal/{}/fundingagnecy/{}/update-metadata/" action = action.format(content_model.short_id, fundingagency_form.initial['id']) fundingagency_form.action = action fundingagency_form.number = fundingagency_form.initial['id'] temporal_coverages = content_model.metadata.coverages.all().filter( type='period') temporal_coverage_data_dict = {} if len(temporal_coverages) > 0: temporal_coverage = temporal_coverages[0] temporal_coverage_data_dict['start'] = temporal_coverage.value['start'] temporal_coverage_data_dict['end'] = temporal_coverage.value['end'] temporal_coverage_data_dict['name'] = temporal_coverage.value.get( 'name', '') temporal_coverage_data_dict['id'] = temporal_coverage.id else: temporal_coverage = None coverage_temporal_form = CoverageTemporalForm( initial=temporal_coverage_data_dict, allow_edit=can_change, res_short_id=content_model.short_id, element_id=temporal_coverage.id if temporal_coverage else None) spatial_coverages = content_model.metadata.coverages.all().exclude( type='period') spatial_coverage_data_dict = {'type': 'point'} if len(spatial_coverages) > 0: spatial_coverage = spatial_coverages[0] spatial_coverage_data_dict['name'] = spatial_coverage.value.get( 'name', None) spatial_coverage_data_dict['units'] = spatial_coverage.value['units'] spatial_coverage_data_dict['zunits'] = spatial_coverage.value.get( 'zunits', None) spatial_coverage_data_dict['projection'] = spatial_coverage.value.get( 'projection', None) spatial_coverage_data_dict['type'] = spatial_coverage.type spatial_coverage_data_dict['id'] = spatial_coverage.id if spatial_coverage.type == 'point': spatial_coverage_data_dict['east'] = spatial_coverage.value['east'] spatial_coverage_data_dict['north'] = spatial_coverage.value[ 'north'] spatial_coverage_data_dict[ 'elevation'] = spatial_coverage.value.get('elevation', None) else: spatial_coverage_data_dict['northlimit'] = spatial_coverage.value[ 'northlimit'] spatial_coverage_data_dict['eastlimit'] = spatial_coverage.value[ 'eastlimit'] spatial_coverage_data_dict['southlimit'] = spatial_coverage.value[ 'southlimit'] spatial_coverage_data_dict['westlimit'] = spatial_coverage.value[ 'westlimit'] spatial_coverage_data_dict['uplimit'] = spatial_coverage.value.get( 'uplimit', None) spatial_coverage_data_dict[ 'downlimit'] = spatial_coverage.value.get('downlimit', None) else: spatial_coverage = None coverage_spatial_form = CoverageSpatialForm( initial=spatial_coverage_data_dict, allow_edit=can_change, res_short_id=content_model.short_id, element_id=spatial_coverage.id if spatial_coverage else None) metadata_form = ExtendedMetadataForm( resource_mode='edit' if can_change else 'view', extended_metadata_layout=extended_metadata_layout) context = { 'resource_edit_mode': resource_edit, 'metadata_form': metadata_form, 'creator_formset': creator_formset, 'add_creator_modal_form': add_creator_modal_form, 'creator_profilelink_formset': None, 'title': content_model.metadata.title, 'abstract_form': abstract_form, 'contributor_formset': contributor_formset, 'add_contributor_modal_form': add_contributor_modal_form, 'relation_formset': relation_formset, 'add_relation_modal_form': add_relation_modal_form, 'source_formset': source_formset, 'add_source_modal_form': add_source_modal_form, 'fundingagnency_formset': fundingagency_formset, 'add_fundinagency_modal_form': add_fundingagency_modal_form, 'coverage_temporal_form': coverage_temporal_form, 'coverage_spatial_form': coverage_spatial_form, 'spatial_coverage': spatial_coverage_data_dict, 'subjects_form': subjects_form, 'metadata_status': metadata_status, 'missing_metadata_elements': content_model.metadata.get_required_missing_elements(), 'citation': content_model.get_citation(), 'extended_metadata_layout': extended_metadata_layout, 'bag_url': bag_url, 'current_user': user, 'show_content_files': show_content_files, 'validation_error': validation_error if validation_error else None, 'discoverable': discoverable, 'resource_is_mine': resource_is_mine, 'relation_source_types': tuple((type_value, type_display) for type_value, type_display in Relation.SOURCE_TYPES if type_value != 'isReplacedBy' and type_value != 'isVersionOf' and type_value != 'hasPart'), 'is_resource_specific_tab_active': False, 'belongs_to_collections': belongs_to_collections } return context
def lead_add(request): """ Function for customer enquiry form """ customer_dict = dict([(cust.title, cust.id) for cust in Customer.objects.all()]) success_dict={} form = LeadForm(request=request) FollowupFormset = formset_factory(FollowupForm1, extra=1) if request.method == 'POST': form = LeadForm(request.POST or None, request=request) followup_formset_forms = FollowupFormset(request.POST or None, prefix='followups' ) for follow_form in followup_formset_forms.deleted_forms: followup_form_instance = follow_form.instance if followup_form_instance.pk: followup_form_instance.delete() if form.is_valid() and followup_formset_forms.is_valid(): enquiry_form = form.save(commit=False) enquiry_form.created_by = request.user is_converted_to_cust = form.cleaned_data['is_converted_to_customer'] all_services = form.cleaned_data['services'] if request.user.groups.filter(name='sales rep').exists(): enquiry_form.owner = form.cleaned_data.get('owner') enquiry_form.sales_rep = Employee.objects.get(user__username = request.user) elif request.user.groups.filter(name='sales manager').exists(): enquiry_form.owner = Employee.objects.get(user__username = request.user) #enquiry_form.sales_rep = form.cleaned_data.get('sales_rep') followup_status_list = [] converted_to_cust_list = [] for followup_formset_form in followup_formset_forms: if followup_formset_form not in [deleted_form for deleted_form in followup_formset_forms.deleted_forms]: followup_formset_instance = followup_formset_form.save(commit=False) next_followup = followup_formset_form.cleaned_data.get('next_followup') lead_status = followup_formset_form.cleaned_data.get('lead_status') converted_to_cust = followup_formset_form.cleaned_data.get('is_converted_to_customer') if converted_to_cust: enquiry_form.is_converted_to_customer = True if next_followup not in ['', None]: followup_status_list.append([next_followup, lead_status]) converted_to_cust_list.append(converted_to_cust) if followup_status_list: if followup_status_list[-1]: enquiry_form.latest_followup_date = followup_status_list[-1][0] enquiry_form.latest_lead_status = followup_status_list[-1][1] else: enquiry_form.latest_followup_date = None enquiry_form.latest_lead_status = None enquiry_form.save() enquiry_form.services = all_services for followup_formset_form in followup_formset_forms: followup_formset_instance = followup_formset_form.save(commit=False) followup_formset_instance.lead = enquiry_form if next_followup not in ['', None]: followup_formset_instance.save() add_to_cust = Customer(title = form.cleaned_data['title'], description = form.cleaned_data['description'], contact_name = form.cleaned_data['contact_name'], designation = form.cleaned_data['designation'], email = form.cleaned_data['email'], phone = form.cleaned_data['phone'], addressline1 = form.cleaned_data['addressline1'], addressline2 = form.cleaned_data['addressline2'], city = form.cleaned_data['city'], state = form.cleaned_data['state'], country = form.cleaned_data['country'], zip_code = form.cleaned_data['zip_code'], requirement = form.cleaned_data['requirement'], industry = form.cleaned_data['industry'], lead_source = form.cleaned_data['lead_source'], other_lead_source = form.cleaned_data['other_lead_source'], #created_by = form.cleaned_data['created_by'], sales_rep = enquiry_form.sales_rep, owner = enquiry_form.owner ) if is_converted_to_cust or True in converted_to_cust_list: if enquiry_form.title not in customer_dict: add_to_cust.save() add_to_cust.services = all_services else: country = Country.objects.get(name=form.cleaned_data.get('country')) existed_customer = Customer.objects.get(title__exact=enquiry_form.title) existed_customer.title = form.cleaned_data['title'] existed_customer.description = form.cleaned_data['description'] existed_customer.contact_name = form.cleaned_data['contact_name'] existed_customer.designation = form.cleaned_data['designation'] existed_customer.email = form.cleaned_data['email'] existed_customer.phone = form.cleaned_data['phone'] existed_customer.addressline1 = form.cleaned_data['addressline1'] existed_customer.addressline2 = form.cleaned_data['addressline2'] existed_customer.city = form.cleaned_data['city'] existed_customer.state = form.cleaned_data['state'] existed_customer.country = country existed_customer.zip_code = form.cleaned_data['zip_code'] existed_customer.requirement = form.cleaned_data['requirement'] existed_customer.industry = form.cleaned_data['industry'] existed_customer.lead_source = form.cleaned_data['lead_source'] existed_customer.other_lead_source = form.cleaned_data['other_lead_source'] existed_customer.sales_rep = enquiry_form.sales_rep existed_customer.owner = enquiry_form.owner existed_customer.save() existed_customer.services = all_services else: enquiry_form.save() enquiry_form.services = all_services success_dict['success_msg'] = "Successfully Created Lead" return HttpResponse(json.dumps(success_dict), content_type='application/json') else: error_dict = {} form_error_dict = {} formset_error_dict = {} for error in form.errors: e = form.errors[error] form_error_dict[error] = unicode(e) for f1 in followup_formset_forms: if f1.errors: for error in f1.errors: e = f1.errors[error] formset_error_dict[error] = unicode(e) error_dict['form_errors'] = form_error_dict error_dict['formset_errors'] = formset_error_dict return HttpResponseBadRequest(json.dumps(error_dict)) else: form = LeadForm(request=request) followup_formset_forms = FollowupFormset(prefix='followups') return render(request, 'customer/lead_add_partial.html', locals())
def test_formset_layout(settings): SampleFormSet = formset_factory(SampleForm, extra=3) formset = SampleFormSet() helper = FormHelper() helper.form_id = "thisFormsetRocks" helper.form_class = "formsets-that-rock" helper.form_method = "POST" helper.form_action = "simpleAction" helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", "is_company", "email", ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row("password1", "password2"), Fieldset("", "first_name", "last_name"), ) html = render_crispy_form(form=formset, helper=helper, context={"csrf_token": _get_new_csrf_string()}) # Check formset fields assert contains_partial( html, '<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"/>' ) assert contains_partial( html, '<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"/>' ) assert contains_partial( html, '<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"/>' ) assert contains_partial( html, '<input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"/>' ) assert html.count("hidden") == 5 # Check form structure assert html.count("<form") == 1 assert html.count("csrfmiddlewaretoken") == 1 assert "formsets-that-rock" in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse("simpleAction") in html # Check form layout assert "Item 1" in html assert "Item 2" in html assert "Item 3" in html assert html.count("Note for first form only") == 1 if settings.CRISPY_TEMPLATE_PACK == "uni_form": assert html.count("formRow") == 3 elif settings.CRISPY_TEMPLATE_PACK in ("bootstrap3", "bootstrap4"): assert html.count("row") == 3 if settings.CRISPY_TEMPLATE_PACK == "bootstrap4": assert html.count("form-group") == 18
def invoice_setup_add(request): success_dict = {} form = form1.InvoiceSetupForm(request.POST) PaymentTermsFormset = formset_factory(form1.PaymentTermsForm) wireform = form1.WireTransferInfoForm(request.POST) if request.method == 'POST': form = form1.InvoiceSetupForm(request.POST or None) wireform = form1.WireTransferInfoForm(request.POST) paymentterms_formset = PaymentTermsFormset(request.POST or None) for payment_term_form in paymentterms_formset.deleted_forms: payment_term_form_instance = payment_term_form.instance if payment_term_form_instance.pk: payment_term_form_instance.delete() if form.is_valid() and paymentterms_formset.is_valid( ) and wireform.is_valid(): invoice_setup = form.save(commit=False) invoice_setup.save() wireform_instance = wireform.save(commit=False) wireform_instance.invoice_setup = invoice_setup wireform_instance.save() for payment_term_form in paymentterms_formset: if payment_term_form not in [ deleted_form for deleted_form in paymentterms_formset.deleted_forms ]: payment_term_formInstance = payment_term_form.save( commit=False) payment_term_formInstance.invoice_setup = invoice_setup #payment_term_formInstance.save() terms = payment_term_form.cleaned_data.get('terms') if terms not in ['', None]: payment_term_formInstance.save() success_dict['success_msg'] = "Successfully Created InvoiceSetup" return HttpResponse(json.dumps(success_dict), content_type='application/json') else: error_dict = {} wiretransfer_info_form_error_dict = {} paymentterms_formset_error_dict = {} for error in form.errors: error_dict[error] = form.errors[error] for error in wireform.errors: error_dict[error] = wireform.errors[error] error_dict[ 'wiretransfer_info_form_error_dict'] = wiretransfer_info_form_error_dict error_dict[ 'paymentterms_formset_error_dict'] = paymentterms_formset_error_dict return HttpResponseBadRequest(json.dumps(error_dict)) else: form = form1.InvoiceSetupForm() wireform = form1.WireTransferInfoForm() paymentterms_formset = PaymentTermsFormset() return render(request, 'invoice/invoice_setup_add_partial.html', locals())
form.setup(data) form.app = self.app try: form.instance = ImageAsset.objects.get(addon=self.app, slug=form.slug) except ImageAsset.DoesNotExist: form.instance = None def save(self): for f in self.forms: f.save(self.app) ImageAssetFormSet = formset_factory(form=ImageAssetForm, formset=BaseImageAssetFormSet, can_delete=False, extra=0) class NewManifestForm(happyforms.Form): manifest = forms.URLField(verify_exists=False) def __init__(self, *args, **kwargs): self.is_standalone = kwargs.pop('is_standalone', False) super(NewManifestForm, self).__init__(*args, **kwargs) def clean_manifest(self): manifest = self.cleaned_data['manifest'] # Skip checking the domain for the standalone validator. if not self.is_standalone: verify_app_domain(manifest)
from django.forms import ModelForm from slam.models import Slam_session, Judges_scores, Poet from django.forms.models import formset_factory class SlamForm(ModelForm): class Meta: model = Slam_session fields = ['slam_name', 'number_of_rounds', 'number_of_judges'] class PoetForm(ModelForm): class Meta: model = Poet fields = ['poet_name'] exclude = ('slam_details', ) class JudgesForm(ModelForm): class Meta: model = Judges_scores fields = ['score_1', 'score_2', 'score_3', 'score_4', 'score_5'] PoetFormset = formset_factory(PoetForm, extra=3) # class ResponseForm(forms.Form): # response = forms.CharField(widget=forms.TextInput(attrs={'autofocus': 'autofocus'}), label='Slam Name', max_length=150, error_messages={'required': 'Hmm...that doesn\'t look quite right. Try a different answer.'})
def get_page_context(page, user, resource_edit=False, extended_metadata_layout=None, request=None): """Inject a crispy_form layout into the page to display extended metadata. :param page: which page to get the template context for :param user: the user who is viewing the page :param resource_edit: True if and only if the page should render in edit mode :param extended_metadata_layout: layout information used to build an ExtendedMetadataForm :param request: the Django request associated with the page load :return: the basic template context (a python dict) used to render a resource page. can and should be extended by page/resource-specific page_processors Resource type specific app needs to call this method to inject a crispy_form layout object for displaying metadata UI for the extended metadata for their resource TODO: refactor to make it clear that there are two different modes = EDITABLE | READONLY - split into two functions: get_readonly_page_context(...) and get_editable_page_context(...) """ file_type_error = '' if request: file_type_error = request.session.get("file_type_error", None) if file_type_error: del request.session["file_type_error"] content_model = page.get_content_model() # whether the user has permission to view this resource can_view = content_model.can_view(request) if not can_view: raise PermissionDenied() discoverable = content_model.raccess.discoverable validation_error = None resource_is_mine = False if user.is_authenticated(): resource_is_mine = content_model.rlabels.is_mine(user) metadata_status = _get_metadata_status(content_model) belongs_to_collections = content_model.collections.all() relevant_tools = None tool_homepage_url = None if not resource_edit: # In view mode landing_page_res_obj = content_model landing_page_res_type_str = landing_page_res_obj.resource_type if landing_page_res_type_str.lower() == "toolresource": if landing_page_res_obj.metadata.app_home_page_url: tool_homepage_url = content_model.metadata.app_home_page_url.value else: relevant_tools = resource_level_tool_urls(landing_page_res_obj, request) just_created = False just_copied = False create_resource_error = None just_published = False if request: validation_error = check_for_validation(request) just_created = request.session.get('just_created', False) if 'just_created' in request.session: del request.session['just_created'] just_copied = request.session.get('just_copied', False) if 'just_copied' in request.session: del request.session['just_copied'] create_resource_error = request.session.get('resource_creation_error', None) if 'resource_creation_error' in request.session: del request.session['resource_creation_error'] just_published = request.session.get('just_published', False) if 'just_published' in request.session: del request.session['just_published'] bag_url = content_model.bag_url if user.is_authenticated(): show_content_files = user.uaccess.can_view_resource(content_model) else: # if anonymous user getting access to a private resource (since resource is discoverable), # then don't show content files show_content_files = content_model.raccess.public allow_copy = can_user_copy_resource(content_model, user) qholder = content_model.get_quota_holder() has_web_ref = res_has_web_reference(content_model) # user requested the resource in READONLY mode if not resource_edit: temporal_coverages = content_model.metadata.coverages.all().filter( type='period') if len(temporal_coverages) > 0: temporal_coverage_data_dict = {} temporal_coverage = temporal_coverages[0] start_date = parser.parse(temporal_coverage.value['start']) end_date = parser.parse(temporal_coverage.value['end']) temporal_coverage_data_dict['start_date'] = start_date.strftime( '%Y-%m-%d') temporal_coverage_data_dict['end_date'] = end_date.strftime( '%Y-%m-%d') temporal_coverage_data_dict['name'] = temporal_coverage.value.get( 'name', '') else: temporal_coverage_data_dict = None spatial_coverages = content_model.metadata.coverages.all().exclude( type='period') if len(spatial_coverages) > 0: spatial_coverage_data_dict = {} spatial_coverage = spatial_coverages[0] spatial_coverage_data_dict['name'] = spatial_coverage.value.get( 'name', None) spatial_coverage_data_dict['units'] = spatial_coverage.value[ 'units'] spatial_coverage_data_dict['zunits'] = spatial_coverage.value.get( 'zunits', None) spatial_coverage_data_dict[ 'projection'] = spatial_coverage.value.get('projection', None) spatial_coverage_data_dict['type'] = spatial_coverage.type if spatial_coverage.type == 'point': spatial_coverage_data_dict['east'] = spatial_coverage.value[ 'east'] spatial_coverage_data_dict['north'] = spatial_coverage.value[ 'north'] spatial_coverage_data_dict[ 'elevation'] = spatial_coverage.value.get( 'elevation', None) else: spatial_coverage_data_dict[ 'northlimit'] = spatial_coverage.value['northlimit'] spatial_coverage_data_dict[ 'eastlimit'] = spatial_coverage.value['eastlimit'] spatial_coverage_data_dict[ 'southlimit'] = spatial_coverage.value['southlimit'] spatial_coverage_data_dict[ 'westlimit'] = spatial_coverage.value['westlimit'] spatial_coverage_data_dict[ 'uplimit'] = spatial_coverage.value.get('uplimit', None) spatial_coverage_data_dict[ 'downlimit'] = spatial_coverage.value.get( 'downlimit', None) else: spatial_coverage_data_dict = None keywords = ",".join( [sub.value for sub in content_model.metadata.subjects.all()]) languages_dict = dict(languages_iso.languages) language = languages_dict[content_model.metadata.language.code] if \ content_model.metadata.language else None title = content_model.metadata.title.value if content_model.metadata.title else None abstract = content_model.metadata.description.abstract if \ content_model.metadata.description else None missing_metadata_elements = content_model.metadata.get_required_missing_elements( ) maps_key = settings.MAPS_KEY if hasattr(settings, 'MAPS_KEY') else '' context = { 'resource_edit_mode': resource_edit, 'metadata_form': None, 'citation': content_model.get_citation(), 'title': title, 'abstract': abstract, 'creators': content_model.metadata.creators.all(), 'contributors': content_model.metadata.contributors.all(), 'temporal_coverage': temporal_coverage_data_dict, 'spatial_coverage': spatial_coverage_data_dict, 'language': language, 'keywords': keywords, 'rights': content_model.metadata.rights, 'sources': content_model.metadata.sources.all(), 'relations': content_model.metadata.relations.all(), 'show_relations_section': show_relations_section(content_model), 'fundingagencies': content_model.metadata.funding_agencies.all(), 'metadata_status': metadata_status, 'missing_metadata_elements': missing_metadata_elements, 'validation_error': validation_error if validation_error else None, 'resource_creation_error': create_resource_error, 'relevant_tools': relevant_tools, 'tool_homepage_url': tool_homepage_url, 'file_type_error': file_type_error, 'just_created': just_created, 'just_copied': just_copied, 'just_published': just_published, 'bag_url': bag_url, 'show_content_files': show_content_files, 'discoverable': discoverable, 'resource_is_mine': resource_is_mine, 'allow_resource_copy': allow_copy, 'is_resource_specific_tab_active': False, 'quota_holder': qholder, 'belongs_to_collections': belongs_to_collections, 'show_web_reference_note': has_web_ref, 'current_user': user, 'maps_key': maps_key } if 'task_id' in request.session: task_id = request.session.get('task_id', None) if task_id: context['task_id'] = task_id del request.session['task_id'] if 'download_path' in request.session: download_path = request.session.get('download_path', None) if download_path: context['download_path'] = download_path del request.session['download_path'] return context # user requested the resource in EDIT MODE # whether the user has permission to change the model can_change = content_model.can_change(request) if not can_change: raise PermissionDenied() add_creator_modal_form = CreatorForm(allow_edit=can_change, res_short_id=content_model.short_id) add_contributor_modal_form = ContributorForm( allow_edit=can_change, res_short_id=content_model.short_id) add_relation_modal_form = RelationForm(allow_edit=can_change, res_short_id=content_model.short_id) add_source_modal_form = SourceForm(allow_edit=can_change, res_short_id=content_model.short_id) add_fundingagency_modal_form = FundingAgencyForm( allow_edit=can_change, res_short_id=content_model.short_id) keywords = ",".join( [sub.value for sub in content_model.metadata.subjects.all()]) subjects_form = SubjectsForm(initial={'value': keywords}, allow_edit=can_change, res_short_id=content_model.short_id, element_id=None) abstract_form = AbstractForm( instance=content_model.metadata.description, allow_edit=can_change, res_short_id=content_model.short_id, element_id=content_model.metadata.description.id if content_model.metadata.description else None) CreatorFormSetEdit = formset_factory(wraps(CreatorForm)(partial( CreatorForm, allow_edit=can_change)), formset=BaseCreatorFormSet, extra=0) creator_formset = CreatorFormSetEdit( initial=content_model.metadata.creators.all().values(), prefix='creator') index = 0 # TODO: dont track index manually. use enumerate, or zip for creator_form in creator_formset.forms: creator_form.action = "/hsapi/_internal/%s/creator/%s/update-metadata/" % \ (content_model.short_id, creator_form.initial['id']) creator_form.number = creator_form.initial['id'] index += 1 ContributorFormSetEdit = formset_factory(wraps(ContributorForm)(partial( ContributorForm, allow_edit=can_change)), formset=BaseContributorFormSet, extra=0) contributor_formset = ContributorFormSetEdit( initial=content_model.metadata.contributors.all().values(), prefix='contributor') index = 0 # TODO: dont track index manually. use enumerate, or zip for contributor_form in contributor_formset.forms: contributor_form.action = "/hsapi/_internal/%s/contributor/%s/update-metadata/" % \ (content_model.short_id, contributor_form.initial['id']) contributor_form.number = contributor_form.initial['id'] index += 1 RelationFormSetEdit = formset_factory(wraps(RelationForm)(partial( RelationForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) relation_formset = RelationFormSetEdit( initial=content_model.metadata.relations.all().values(), prefix='relation') for relation_form in relation_formset.forms: relation_form.action = "/hsapi/_internal/%s/relation/%s/update-metadata/" % \ (content_model.short_id, relation_form.initial['id']) relation_form.number = relation_form.initial['id'] SourceFormSetEdit = formset_factory(wraps(SourceForm)(partial( SourceForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) source_formset = SourceFormSetEdit( initial=content_model.metadata.sources.all().values(), prefix='source') for source_form in source_formset.forms: source_form.action = "/hsapi/_internal/%s/source/%s/update-metadata/" % \ (content_model.short_id, source_form.initial['id']) source_form.delete_modal_form = MetaDataElementDeleteForm( content_model.short_id, 'source', source_form.initial['id']) source_form.number = source_form.initial['id'] FundingAgencyFormSetEdit = formset_factory(wraps(FundingAgencyForm)( partial(FundingAgencyForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) fundingagency_formset = FundingAgencyFormSetEdit( initial=content_model.metadata.funding_agencies.all().values(), prefix='fundingagency') for fundingagency_form in fundingagency_formset.forms: action = "/hsapi/_internal/{}/fundingagnecy/{}/update-metadata/" action = action.format(content_model.short_id, fundingagency_form.initial['id']) fundingagency_form.action = action fundingagency_form.number = fundingagency_form.initial['id'] temporal_coverages = content_model.metadata.coverages.all().filter( type='period') temporal_coverage_data_dict = {} if len(temporal_coverages) > 0: temporal_coverage = temporal_coverages[0] start_date = parser.parse(temporal_coverage.value['start']) end_date = parser.parse(temporal_coverage.value['end']) temporal_coverage_data_dict['start'] = start_date.strftime('%m-%d-%Y') temporal_coverage_data_dict['end'] = end_date.strftime('%m-%d-%Y') temporal_coverage_data_dict['name'] = temporal_coverage.value.get( 'name', '') temporal_coverage_data_dict['id'] = temporal_coverage.id else: temporal_coverage = None coverage_temporal_form = CoverageTemporalForm( initial=temporal_coverage_data_dict, allow_edit=can_change, res_short_id=content_model.short_id, element_id=temporal_coverage.id if temporal_coverage else None) spatial_coverages = content_model.metadata.coverages.all().exclude( type='period') spatial_coverage_data_dict = {'type': 'point'} if len(spatial_coverages) > 0: spatial_coverage = spatial_coverages[0] spatial_coverage_data_dict['name'] = spatial_coverage.value.get( 'name', None) spatial_coverage_data_dict['units'] = spatial_coverage.value['units'] spatial_coverage_data_dict['zunits'] = spatial_coverage.value.get( 'zunits', None) spatial_coverage_data_dict['projection'] = spatial_coverage.value.get( 'projection', None) spatial_coverage_data_dict['type'] = spatial_coverage.type spatial_coverage_data_dict['id'] = spatial_coverage.id if spatial_coverage.type == 'point': spatial_coverage_data_dict['east'] = spatial_coverage.value['east'] spatial_coverage_data_dict['north'] = spatial_coverage.value[ 'north'] spatial_coverage_data_dict[ 'elevation'] = spatial_coverage.value.get('elevation', None) else: spatial_coverage_data_dict['northlimit'] = spatial_coverage.value[ 'northlimit'] spatial_coverage_data_dict['eastlimit'] = spatial_coverage.value[ 'eastlimit'] spatial_coverage_data_dict['southlimit'] = spatial_coverage.value[ 'southlimit'] spatial_coverage_data_dict['westlimit'] = spatial_coverage.value[ 'westlimit'] spatial_coverage_data_dict['uplimit'] = spatial_coverage.value.get( 'uplimit', None) spatial_coverage_data_dict[ 'downlimit'] = spatial_coverage.value.get('downlimit', None) else: spatial_coverage = None coverage_spatial_form = CoverageSpatialForm( initial=spatial_coverage_data_dict, allow_edit=can_change, res_short_id=content_model.short_id, element_id=spatial_coverage.id if spatial_coverage else None) metadata_form = ExtendedMetadataForm( resource_mode='edit' if can_change else 'view', extended_metadata_layout=extended_metadata_layout) maps_key = settings.MAPS_KEY if hasattr(settings, 'MAPS_KEY') else '' context = { 'resource_edit_mode': resource_edit, 'metadata_form': metadata_form, 'creator_formset': creator_formset, 'add_creator_modal_form': add_creator_modal_form, 'creator_profilelink_formset': None, 'title': content_model.metadata.title, 'abstract_form': abstract_form, 'contributor_formset': contributor_formset, 'add_contributor_modal_form': add_contributor_modal_form, 'relation_formset': relation_formset, 'add_relation_modal_form': add_relation_modal_form, 'source_formset': source_formset, 'add_source_modal_form': add_source_modal_form, 'fundingagnency_formset': fundingagency_formset, 'add_fundinagency_modal_form': add_fundingagency_modal_form, 'coverage_temporal_form': coverage_temporal_form, 'coverage_spatial_form': coverage_spatial_form, 'spatial_coverage': spatial_coverage_data_dict, 'subjects_form': subjects_form, 'metadata_status': metadata_status, 'missing_metadata_elements': content_model.metadata.get_required_missing_elements(), 'citation': content_model.get_citation(), 'rights': content_model.metadata.rights, 'extended_metadata_layout': extended_metadata_layout, 'bag_url': bag_url, 'current_user': user, 'show_content_files': show_content_files, 'validation_error': validation_error if validation_error else None, 'discoverable': discoverable, 'resource_is_mine': resource_is_mine, 'quota_holder': qholder, 'relation_source_types': tuple((type_value, type_display) for type_value, type_display in Relation.SOURCE_TYPES if type_value != 'isReplacedBy' and type_value != 'isVersionOf' and type_value != 'hasPart'), 'is_resource_specific_tab_active': False, 'show_web_reference_note': has_web_ref, 'belongs_to_collections': belongs_to_collections, 'maps_key': maps_key } return context
def landing_page(request, page): content_model = page.get_content_model() edit_resource = page_processors.check_resource_mode(request) if content_model.metadata.is_dirty: messages.info( request, "NetCDF file is out of sync with resource metadata changes.") if not edit_resource: # not editing mode # get the context from hs_core context = page_processors.get_page_context( page, request.user, resource_edit=edit_resource, extended_metadata_layout=None, request=request) if isinstance(context, HttpResponseRedirect): # sending user to login page return context extended_metadata_exists = False if content_model.metadata.variables.all( ) or content_model.metadata.ori_coverage.all(): extended_metadata_exists = True elif content_model.files.all(): for f in content_model.files.all(): if '_header_info.txt' in f.resource_file.name: extended_metadata_exists = True context['extended_metadata_exists'] = extended_metadata_exists # add the variables context # the variables is the field name from NetCDFMetaData model context['variables'] = content_model.metadata.variables.all() # add the original coverage context ori_cov_dict = {} ori_cov_obj = content_model.metadata.ori_coverage.all().first() if ori_cov_obj: ori_cov_dict['name'] = ori_cov_obj.value.get('name', None) ori_cov_dict['units'] = ori_cov_obj.value['units'] ori_cov_dict['projection'] = ori_cov_obj.value.get( 'projection', None) ori_cov_dict['northlimit'] = ori_cov_obj.value['northlimit'] ori_cov_dict['eastlimit'] = ori_cov_obj.value['eastlimit'] ori_cov_dict['southlimit'] = ori_cov_obj.value['southlimit'] ori_cov_dict['westlimit'] = ori_cov_obj.value['westlimit'] ori_cov_dict[ 'projection_string_type'] = ori_cov_obj.projection_string_type ori_cov_dict[ 'projection_string_text'] = ori_cov_obj.projection_string_text ori_cov_dict['datum'] = ori_cov_obj.datum context['original_coverage'] = ori_cov_dict else: context['original_coverage'] = None else: # editing mode # Original Coverage in editing mode ori_cov_obj = content_model.metadata.ori_coverage.all().first() ori_cov_dict = {} if ori_cov_obj: ori_cov_dict['name'] = ori_cov_obj.value.get('name', None) ori_cov_dict['units'] = ori_cov_obj.value['units'] ori_cov_dict['projection'] = ori_cov_obj.value.get( 'projection', None) ori_cov_dict['northlimit'] = ori_cov_obj.value['northlimit'] ori_cov_dict['eastlimit'] = ori_cov_obj.value['eastlimit'] ori_cov_dict['southlimit'] = ori_cov_obj.value['southlimit'] ori_cov_dict['westlimit'] = ori_cov_obj.value['westlimit'] ori_cov_dict[ 'projection_string_type'] = ori_cov_obj.projection_string_type ori_cov_dict[ 'projection_string_text'] = ori_cov_obj.projection_string_text ori_cov_dict['datum'] = ori_cov_obj.datum else: ori_cov_obj = None ori_cov_form = OriginalCoverageForm( initial=ori_cov_dict, allow_edit=edit_resource, res_short_id=content_model.short_id, element_id=ori_cov_obj.id if ori_cov_obj else None) ori_cov_form.delete_modal_form = OriginalCoverageMetaDelete( content_model.short_id, 'originalcoverage', ori_cov_obj.id if ori_cov_obj else None) # Variable Forms in editing mode VariableFormSetEdit = formset_factory(wraps(VariableForm)(partial( VariableForm, allow_edit=edit_resource)), formset=BaseFormSet, extra=0) variable_formset = VariableFormSetEdit(initial=list( content_model.metadata.variables.all().values()), prefix='variable') add_variable_modal_form = VariableForm( allow_edit=edit_resource, res_short_id=content_model.short_id) for form in variable_formset.forms: if len(form.initial) > 0: form.delete_modal_form = MetaDataElementDeleteForm( content_model.short_id, 'variable', form.initial['id']) form.action = "/hsapi/_internal/%s/variable/%s/update-metadata/" % \ (content_model.short_id, form.initial['id']) form.number = form.initial['id'] else: form.action = "/hsapi/_internal/%s/variable/add-metadata/" % content_model.short_id # netcdf file update notification in editing mode UpdateNetcdfLayout = HTML( content_model.metadata.get_update_netcdf_file_html_form()) # get the context from hs_core ext_md_layout = Layout( UpdateNetcdfLayout, HTML(""" <div class="form-group col-xs-12" id="originalcoverage"> {% load crispy_forms_tags %} {% crispy original_coverage_form %} </div> """), VariableLayoutEdit, ModalDialogLayoutAddVariable, ) context = page_processors.get_page_context( page, request.user, resource_edit=edit_resource, extended_metadata_layout=ext_md_layout, request=request) context['variable_formset'] = variable_formset context['add_variable_modal_form'] = add_variable_modal_form context['original_coverage_form'] = ori_cov_form # get hs_core context hs_core_context = add_generic_context(request, page) context.update(hs_core_context) return context
if action == 2: if bidder is not None and not bidder: self._errors['bidder'] = self.error_class([msg1]) if not amount: self._errors['amount'] = self.error_class([msg1]) else: if bidder: self._errors['bidder'] = self.error_class([msg2]) del cleaned_data['bidder'] if amount: self._errors['amount'] = self.error_class([msg2]) del cleaned_data['amount'] return cleaned_data AuctionBidFormSet = formset_factory(AuctionBidForm, extra=0) @permission_required('artshow.is_artshow_staff') def auction_bids(request, adult): adult = adult == "y" pieces = Piece.objects.filter(voice_auction=True, status=Piece.StatusInShow, adult=adult).order_by( "order", "artist", "pieceid") initial_data = [{'piece': p} for p in pieces] if request.method == "POST": formset = AuctionBidFormSet(request.POST, initial=initial_data) if formset.is_valid():
class ProductPriceModelForm(ModelForm): class Meta: model = ProductPrice fields = [ 'price', ] shop = forms.ModelChoiceField(required=True, queryset=Shop.objects.order_by( 'name', 'name_fr')) def save(self, product, *args, **kwargs): if not self.cleaned_data: return product_price, _ = ProductPrice.objects.get_or_create( shop=self.cleaned_data['shop'], product=self.instance, price=self.cleaned_data['price'], quantity=self.cleaned_data['quantity'], unit_of_ingredient=product.unit_of_ingredient) def delete(self, tag, *args, **kwargs): self.cleaned_data['recipe'].tag.remove(tag) ProductPriceFormset = formset_factory(ProductPriceModelForm, extra=1, can_delete=True)
widgets = { 'sample_input': forms.Textarea(attrs={'rows': 5}), 'sample_output': forms.Textarea(attrs={'rows': 5}), } class UpdateProblemForm(ProblemForm): solution_source_file = forms.FileField(required=False) class TestCaseForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TestCaseForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-inline' self.helper.form_tag = False self.helper.layout = Layout( Field('input_data_file'), ) class Meta: model = TestCase exclude = ['problem', 'output'] class UpdateTestCaseForm(TestCaseForm): input_data_file = forms.FileField(required=False) TestCaseFormSet = formset_factory(TestCaseForm)
def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) self.object = None CourseFormSet = formset_factory(BulkCourseForm, extra=1, validate_max=True) offc_formset = CourseFormSet(request.POST, prefix=self.prefix) # save the uploaded course data author = self.request.user if offc_formset.is_valid(): for offc_form in offc_formset.forms: if offc_form.has_changed(): if offc_form.is_valid(): title = offc_form.cleaned_data["title"] url = offc_form.cleaned_data["url"] description = offc_form.cleaned_data["description"] difficulty = offc_form.cleaned_data["difficulty"] duration = offc_form.cleaned_data["duration"] instructor_name = offc_form.cleaned_data[ "instructor_name"] instructor_company = offc_form.cleaned_data[ "instructor_company"] instructor_web = offc_form.cleaned_data[ "instructor_web"] price = offc_form.cleaned_data["price"] max_students = offc_form.cleaned_data["max_students"] min_students = offc_form.cleaned_data["min_students"] session_count = offc_form.cleaned_data["session_count"] prerequisites = offc_form.cleaned_data["prerequisites"] course = Course() course.title = title course.url = url course.difficulty = difficulty course.status = 1 course.mode = 2 #offline course.description = description course.price = price course.duration = duration course.save() for instructor in instructor_name.split(','): newInstructor, created = Instructor.objects.get_or_create( name=instructor) if created: newInstructor.save() course.instructors.add(newInstructor) newProvider, p_created = CourseProvider.objects.get_or_create( name=instructor_company, url=instructor_web) if p_created: newProvider.save() course.provider = newProvider # AddCourseTags(course) course.extractor_version = OFFLINE_EXTRACTOR_VERSION course.save() liveTraining = LiveTraining( course=course, max_students=max_students, min_students=min_students, session_count=session_count, prerequisites=prerequisites) liveTraining.save() return redirect('learn:dashboard') else: # form invalid return self.render_to_response( self.get_context_data(uploadform=OfflineContentloadForm(), formset=offc_formset, error=True))
@classmethod def get_data(cls, activity, group=None, prefix=""): groups = activity.attributes.filter(fk_group__name__startswith=cls.Meta.name).values_list( 'fk_group__name', flat=True).order_by('fk_group__name').distinct() data = [] for i, group in enumerate(groups): form_data = DealSpatialForm.get_data(activity, group=group)#, prefix='%s-%i' % (cls.Meta.name, i)) if form_data: data.append(form_data) return data def get_attributes(self, request=None): return [form.get_attributes(request=request) for form in self.forms] @property def meta(self): # Required for template access to Meta class return hasattr(self, 'Meta') and self.Meta or None class Meta: name = 'location' DealSpatialFormSet = formset_factory( DealSpatialForm, min_num=1, validate_min=True, extra=0, formset=DealSpatialBaseFormSet) PublicViewDealSpatialFormSet = formset_factory( PublicDealSpatialForm, formset=DealSpatialBaseFormSet, extra=0)
# fields = ('motive','financed_by') class FinanceForm(forms.ModelForm): id_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), empty_label="Moneda", widget=forms.Select(attrs={'class':'form-control input-sm'})) amount = forms.IntegerField(min_value=0, widget=forms.NumberInput(attrs={'class':'form-control input-sm','placeholder': u' Ingrese un Monto...'})) financed_by = forms.CharField(required=False,widget=forms.TextInput(attrs={'class':"form-control", 'placeholder': u'Ej: "Conicyt - Fondecyt #1120207"'})) #financed_by_dcc = forms.BooleanField(required=False,widget=forms.CheckboxInput()) #id_finance_type = forms.ModelChoiceField(queryset=FinanceType.objects.all(),empty_label="tipo de financiamiento") class Meta: model = Finance exclude = {'id_application','id_finance_type'} FinanceFormSet = formset_factory(FinanceForm, max_num=3, extra=3) FinanceFormSet_Edit= formset_factory(FinanceForm,extra=0) class DestinationForm(forms.ModelForm): # Usando paises del javascript country = forms.CharField(widget=forms.Select(attrs={'class': 'form-control input-sm','onchange': "print_state('state',this.selectedIndex, this.id);"})) city = forms.CharField(required=False, widget=forms.Select(attrs={'class': 'city form-control input-sm'}, choices=([("", "Seleccione Ciudad")]))) other_city = forms.CharField(required=False, widget=forms.TextInput(attrs={'class':"form-control", 'placeholder': u'Otra Ciudad'})) # Usando paises de la base de datos # country = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="Seleccione País") # city = forms.ModelChoiceField(queryset=City.objects.all(), empty_label="Seleccione Ciudad") start_date = forms.DateField(input_formats=['%d/%m/%y', '%d/%m/%Y'], widget=forms.DateInput( attrs={'class': 'datepicker', 'data-date-format': "dd/mm/yyyy", 'onchange': "count_avaliable_days(this);"})) #
class BaseBandInfoFormSet(BaseFormSet): def add_fields(self, form, index): super(BaseBandInfoFormSet, self).add_fields(form, index) def get_metadata_dict(self): bands_data = [] for form in self.forms: band_data = {k: v for k, v in list(form.cleaned_data.items())} bands_data.append({'BandInformation': band_data}) return bands_data BandInfoFormSet = formset_factory(BandInfoForm, formset=BaseBandInfoFormSet, extra=0) BandInfoLayoutEdit = Layout( HTML(""" {% load crispy_forms_tags %} <div class="col-sm-12 pull-left"> <div id="variables" class="well"> <div class="row"> {% for form in bandinfo_formset.forms %} <div class="col-sm-6 col-xs-12"> <form id="{{form.form_id}}" action="{{ form.action }}" method="POST" enctype="multipart/form-data"> {% crispy form %} <div class="row" style="margin-top:10px"> <div class="col-md-offset-10 col-xs-offset-6 col-md-2 col-xs-6">
# coding=utf-8 from django import forms from django.conf import settings from django.forms.models import formset_factory from BanBanTong.db import models class UserPermittedGroupForm(forms.ModelForm): class Meta: model = models.UserPermittedGroup exclude = ['uuid', 'user'] UserPermittedGroupFormSet = formset_factory(UserPermittedGroupForm) class UserForm(forms.ModelForm): password_confirmation = forms.CharField(max_length=128, widget=forms.PasswordInput()) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['username'].error_messages = {'required': '请输入用户名!'} self.fields['role'].error_messages = { 'invalid_choice': '选择的角色是无效的!', } self.fields['password'].error_messages = {'required': '请输入密码!'} self.fields['password_confirmation'].error_messages = { 'required': '请输入确认密码!' }
a = q.filter(term=self.term, start_time__gte=start_time, end_time__lte=end_time) if a.exists(): raise forms.ValidationError(u'作息时间包含了其它作息时段!') return cleaned_data class Meta: model = models.LessonPeriod exclude = ['uuid', 'term'] LessonPeriodFormSet = formset_factory(LessonPeriodForm) class LessonPeriodUploadForm(forms.Form): excel = forms.FileField() _valid_extensions = ['.xls', '.xlsx'] _fields = ['sequence', 'start_time', 'end_time'] head = [u'节次', u'开始时间', u'结束时间'] def __init__(self, *args, **kwargs): super(LessonPeriodUploadForm, self).__init__(*args, **kwargs) self.fields['excel'].error_messages = {'required': u'请上传学校作息时间的xls文件!'} def clean(self): cleaned_data = super(LessonPeriodUploadForm, self).clean() excel = cleaned_data.get('excel')
def test_formset_layout(self): TestFormSet = formset_factory(TestForm, extra=3) formset = TestFormSet() helper = FormHelper() helper.form_id = 'thisFormsetRocks' helper.form_class = 'formsets-that-rock' helper.form_method = 'POST' helper.form_action = 'simpleAction' helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", 'is_company', 'email', ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row('password1', 'password2'), Fieldset("", 'first_name', 'last_name')) html = render_crispy_form(form=formset, helper=helper, context={'csrf_token': _get_new_csrf_key()}) # Check formset fields django_version = django.get_version() if django_version < '1.5': self.assertEqual( html.count( 'type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS"' ), 1) self.assertEqual( html.count( 'type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"' ), 1) if (django_version >= '1.4' and django_version < '1.4.4') or django_version < '1.3.6': self.assertEqual( html.count( 'type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS"' ), 1) else: self.assertEqual( html.count( 'type="hidden" name="form-MAX_NUM_FORMS" value="1000" id="id_form-MAX_NUM_FORMS"' ), 1) else: self.assertEqual( html.count( 'id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"' ), 1) self.assertEqual( html.count( 'id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"' ), 1) self.assertEqual( html.count( 'id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"' ), 1) self.assertEqual(html.count("hidden"), 4) # Check form structure self.assertEqual(html.count('<form'), 1) self.assertEqual( html.count("<input type='hidden' name='csrfmiddlewaretoken'"), 1) self.assertTrue('formsets-that-rock' in html) self.assertTrue('method="post"' in html) self.assertTrue('id="thisFormsetRocks"' in html) self.assertTrue('action="%s"' % reverse('simpleAction') in html) # Check form layout self.assertTrue('Item 1' in html) self.assertTrue('Item 2' in html) self.assertTrue('Item 3' in html) self.assertEqual(html.count('Note for first form only'), 1) if self.current_template_pack == 'uni_form': self.assertEqual(html.count('formRow'), 3) else: self.assertEqual(html.count('row'), 3)
def get_getparam(self): """ This is what needs to go into the GET parameters for the results Needs to be called after .full_clean() :return: <id> """ if not self.cleaned_data: return 'Run full clean on {}'.format(self) ret_val = '{}'.format(self.cleaned_data['property'].id) if not self.cleaned_data['property'].symmetric: ret_val += 'l' # Need sided parameter, so we just default to left return ret_val AsymmSearchFormSet = formset_factory(AsymmSearchForm, extra=2, max_num=5) SymmSearchFormSet = formset_factory(SymmSearchForm, extra=2, max_num=5) CommSearchFormSet = formset_factory(CommSearchForm, extra=2, max_num=5) class RingSelector(forms.Form): ring = forms.ModelChoiceField(queryset=Ring.objects.all().order_by('name')) class KeywordSearchForm(forms.Form): kwd = forms.ModelChoiceField( queryset=Keyword.objects.all().order_by('name'), widget=forms.SelectMultiple(attrs={'size': '15'}), empty_label=None)
def editsample(request): context = RequestContext(request) is_member = request.user.groups.filter(name='Consortium Super User') sample = None # get sample code from the session dictionary and retrieve sample object sample_code = request.session['sample'] try: sample = Sample.objects.get(sample_code=sample_code) except: pass # variables site_name = None transect = None retreat_zone = None sample_coordinates = None osl_data = None c14_data = None tcn_data = None bearings = None num_bearings = None sample_type = None photos = [] # determine sample type if sample is not None: try: tcn_data = TCN_Sample.objects.get(tcn_sample=sample) except: pass if tcn_data is None: try: osl_data = OSL_Sample.objects.get(osl_sample=sample) except: pass if tcn_data is None and osl_data is None: try: c14_data = Radiocarbon_Sample.objects.get(c14_sample=sample) except: pass # retrieve coordinates, transect and retreat zone instances if sample is not None: if sample.sample_site is not None: site_name = sample.sample_site.site_name sample_coordinates = sample.sample_coordinates transect = sample.transect retreat_zone = sample.retreat # for tcn samples retrieve bearings and inclination data and set sample type if tcn_data is not None: bearings = Sample_Bearing_Inclination.objects.filter(sample_with_bearing=tcn_data) sample_type = 'TCN' data = [] for item in bearings: values = item.bear_inc if values is not None: data.append({'bearing':values.bearing, 'inclination':values.inclination}) num_bearings = len(data) BearingsFormSet = formset_factory(EditBIForm, extra=40-num_bearings) # if OSL sample get core data and set type to OSL if osl_data is not None: core = osl_data.osl_core sample_type = 'OSL' # if C14 sample get core data and set type to C14 if c14_data is not None: core = c14_data.c14_core sample_type = 'C14' # get the photographs if sample is not None: photo_list = Photo_Of.objects.filter(sample_pictured=sample) if len(photo_list) != 0: for photo in photo_list: if photo.photo_idno.photo_filename is not None and photo.photo_idno.photo_filename != '': photos.append(photo.photo_idno) # form variable names oslForm = None c14Form = None tcnForm = None coreForm = None bearingsFormSet = None # A HTTP POST? if request.method == 'POST': sampleForm = EditSampleForm(request.POST, instance=sample) samplecoordForm = EditCoordinatesForm(request.POST, prefix='sample', instance=sample_coordinates) siteForm = EditSampleSiteForm(request.POST) sitecoordForm = EditCoordinatesForm(request.POST, prefix='site') tranForm = TransectForm(request.POST, instance=transect) retForm = RetreatForm(request.POST, instance=retreat_zone) sitechoicesForm = ExistingSitesForm(request.POST, prefix='main') hiddensiteForm = HiddenSiteForm(request.POST, prefix='hidden') # branch depending on sample type if tcn_data is not None: bearingsFormSet = BearingsFormSet(request.POST, request.FILES) tcnForm = EditTCNForm(request.POST, instance=tcn_data) elif osl_data is not None: oslForm = EditOSLSampleForm(request.POST, instance=osl_data) coreForm = CoreDetailsForm(request.POST, instance=core) elif c14_data is not None: c14Form = EditRadiocarbonForm(request.POST, instance=c14_data) coreForm = CoreDetailsForm(request.POST, instance=core) # Have we been provided with a complete set of valid forms? If yes save forms sequentially in order to supply # foreign key values where required if sampleForm.is_valid and samplecoordForm.is_valid() and tranForm.is_valid() and retForm.is_valid() and\ hiddensiteForm.is_valid(): sample = sampleForm.save(commit=False) sample_coordinates = samplecoordForm.save() site_name = hiddensiteForm.save() sample_site = None try: sample_site = Sample_Site.objects.get(site_name=site_name) except: pass transect = tranForm.save() retreat = retForm.save() # add the foreign keys to sample and write to database sample.transect = transect sample.retreat = retreat sample.sample_coordinates = sample_coordinates sample.sample_site = sample_site sample.save() # TCN specific actions, including updating the bearing and inclination values. if sample_type == 'TCN': tcn = tcnForm.save(commit=False) tcn.tcn_sample = sample tcn.save() tracker = 0 for form in bearingsFormSet.forms: bear_inc = form.save(commit=False) if bear_inc is not None: if tracker < len(bearings): bearings[tracker].bear_inc.bearing = bear_inc.bearing bearings[tracker].bear_inc.inclination = bear_inc.inclination bearings[tracker].bear_inc.save() tracker += 1 else: if bear_inc.bearing is not None and bear_inc.inclination is not None: bear_inc.save() Sample_Bearing_Inclination.objects.create(sample_with_bearing=tcn_data, bear_inc=bear_inc) # C14 sample type specific actions elif sample_type == 'C14': core = coreForm.save() c14 = c14Form.save(commit=False) c14.c14_sample = sample c14.c14_core = core c14.save() # OSL sample type specific actions elif sample_type == 'OSL': core = coreForm.save() osl = oslForm.save(commit=False) osl.osl_sample = sample osl.osl_core = core osl.save() # The user will be returned to the homepage. return HttpResponseRedirect(reverse('index')) else: # The supplied form contained errors - just print them to the terminal. print sampleForm.errors else: # create forms filled with instance data sampleForm = EditSampleForm(instance=sample) samplecoordForm = EditCoordinatesForm(prefix='sample', instance=sample_coordinates) siteForm = EditSampleSiteForm() sitecoordForm = EditCoordinatesForm(prefix='site') tranForm = TransectForm(instance=transect) retForm = RetreatForm(instance=retreat_zone) sitechoicesForm = ExistingSitesForm(prefix='main') hiddensiteForm = HiddenSiteForm(prefix='hidden') fillsiteForm = ExistingSitesForm(request.POST, prefix='fill') if tcn_data is not None: bearingsFormSet = BearingsFormSet(initial=data) tcnForm = EditTCNForm(instance=tcn_data) elif osl_data is not None: oslForm = EditOSLSampleForm(instance=osl_data) coreForm = CoreDetailsForm(instance=core) elif c14_data is not None: c14Form = EditRadiocarbonForm(instance=c14_data) coreForm = CoreDetailsForm(instance=core) # Bad form (or form details), no form supplied... # Render the form with error messages (if any). return render_to_response('mappingapp/editsample.html', {'num_bearings': num_bearings, 'sitecoordform': sitecoordForm, 'siteform': siteForm, 'samplecoordform': samplecoordForm,'sampform': sampleForm, 'tranform': tranForm, 'hiddensiteform': hiddensiteForm, 'sitechoices': sitechoicesForm, 'retform': retForm, 'fillsiteform': fillsiteForm,'is_member': is_member, 'bearingformset': bearingsFormSet, 'tcnform': tcnForm, 'site_name': site_name, 'oslform': oslForm, 'c14form': c14Form, 'coreform': coreForm, 'sample_type': sample_type, 'photos':photos}, context)
class ReadingForm(forms.Form): ships_head = forms.FloatField( required=False, min_value=0, max_value=359, widget=DegreeInput(attrs={'tabindex': 0}) ) deviation = forms.FloatField( required=False, min_value=-180, max_value=180, widget=DegreeInput(attrs={'tabindex': 1}) ) ReadingFormSet = formset_factory(form=ReadingForm) class EquationChoiceForm(forms.Form): def __init__(self, equation_choices, equation_initial, *args, **kwargs): super(EquationChoiceForm, self).__init__(*args, **kwargs) self.fields['equation'] = forms.ChoiceField(choices=equation_choices, initial=equation_initial) class StripeForm(forms.Form): stripeToken = forms.CharField() class RoseDownloadForm(forms.Form): from_variation = forms.IntegerField( initial=0,
def landing_page(request, page): content_model = page.get_content_model() edit_resource = page_processors.check_resource_mode(request) context = page_processors.get_page_context(page, request.user, resource_edit=edit_resource, extended_metadata_layout=None, request=request) if not edit_resource and isinstance(context, HttpResponseRedirect): # sending user to login page return context extended_metadata_exists = False if content_model.metadata.cellInformation or content_model.metadata.bandInformations: extended_metadata_exists = True context['extended_metadata_exists'] = extended_metadata_exists if not edit_resource: # get the context from content_model if content_model.metadata.originalCoverage: ori_coverage_data_dict = {} ori_coverage_data_dict['units'] = content_model.metadata.originalCoverage.value['units'] ori_coverage_data_dict['projection'] = content_model.metadata.originalCoverage.\ value.get('projection', None) ori_coverage_data_dict['northlimit'] = content_model.metadata.originalCoverage.\ value['northlimit'] ori_coverage_data_dict['eastlimit'] = content_model.metadata.originalCoverage.\ value['eastlimit'] ori_coverage_data_dict['southlimit'] = content_model.metadata.originalCoverage.\ value['southlimit'] ori_coverage_data_dict['westlimit'] = content_model.metadata.originalCoverage.\ value['westlimit'] ori_coverage_data_dict['projection_string'] = content_model.metadata.originalCoverage.\ value.get('projection_string', None) ori_coverage_data_dict['datum'] = content_model.metadata.originalCoverage.\ value.get('datum', None) context['originalCoverage'] = ori_coverage_data_dict context['cellInformation'] = content_model.metadata.cellInformation context['bandInformation'] = content_model.metadata.bandInformations else: # cellinfo_form cellinfo_form = CellInfoForm(instance=content_model.metadata.cellInformation, res_short_id=content_model.short_id, allow_edit=True, element_id=content_model.metadata.cellInformation.id if content_model.metadata.cellInformation else None) cellinfo_layout = HTML("<div class='form-group col-lg-6 col-xs-12' id='CellInformation'> " '{% load crispy_forms_tags %} ' '{% crispy cellinfo_form %} ' '</div>') # bandinfo_formset BandInfoFormSetEdit = formset_factory(wraps(BandInfoForm) (partial(BandInfoForm, allow_edit=edit_resource)), formset=BaseBandInfoFormSet, extra=0) bandinfo_formset = BandInfoFormSetEdit( initial=list(content_model.metadata.bandInformations.values()), prefix='BandInformation') for form in bandinfo_formset.forms: if len(form.initial) > 0: form.action = "/hsapi/_internal/%s/bandinformation/%s/update-metadata/" % \ (content_model.short_id, form.initial['id']) form.number = form.initial['id'] # original coverage_form ori_cov_obj = content_model.metadata.originalCoverage ori_coverage_data_dict = {} if ori_cov_obj: ori_coverage_data_dict['units'] = ori_cov_obj.value['units'] ori_coverage_data_dict['projection'] = ori_cov_obj.value.get('projection', None) ori_coverage_data_dict['northlimit'] = ori_cov_obj.value['northlimit'] ori_coverage_data_dict['eastlimit'] = ori_cov_obj.value['eastlimit'] ori_coverage_data_dict['southlimit'] = ori_cov_obj.value['southlimit'] ori_coverage_data_dict['westlimit'] = ori_cov_obj.value['westlimit'] ori_coverage_data_dict['projection_string'] = ori_cov_obj.value.\ get('projection_string', None) ori_coverage_data_dict['datum'] = ori_cov_obj.value.get('datum', None) else: ori_cov_obj = None ori_coverage_form = OriginalCoverageSpatialForm(initial=ori_coverage_data_dict, res_short_id=content_model.short_id, allow_edit=edit_resource, element_id=ori_cov_obj.id if ori_cov_obj else None) ori_coverage_layout = HTML(""" <div class="form-group col-lg-6 col-xs-12" id="originalcoverage"> {% load crispy_forms_tags %} {% crispy ori_coverage_form %} </div> """) # update context ext_md_layout = Layout(HTML("<div>"), ori_coverage_layout, cellinfo_layout, BandInfoLayoutEdit, HTML("</div>") ) context = page_processors.get_page_context(page, request.user, resource_edit=edit_resource, extended_metadata_layout=ext_md_layout, request=request) context['ori_coverage_form'] = ori_coverage_form context['cellinfo_form'] = cellinfo_form context['bandinfo_formset'] = bandinfo_formset hs_core_context = add_generic_context(request, page) context.update(hs_core_context) return context
def __init__(self, *args, **kwargs) -> None: super(WhosWhoForm, self).__init__(*args, **kwargs) self.fields['ssf_person'].queryset = SSFPerson.objects.all().order_by( 'contributor__last_name', 'contributor__first_name' ) self.fields['ssf_knowledge'].queryset = SSFKnowledge.objects.all().order_by('level2_title', 'level1_title') class Meta: model = WhoFeature fields = '__all__' labels = { 'ssf_person': 'Who\'s Who Page', 'ssf_knowledge': 'Select Publication' } widgets = { 'ssf_knowledge': Select(attrs={'id': 'sota-select'}), 'ssf_person': Select(attrs={'id': 'who-select'}) } class GeoJSONUploadForm(forms.Form): """ Form for uploading a new GeoJSON file. """ file = forms.FileField(required=False) SelectedAttributesFormSet = formset_factory(SelectedAttributeForm, extra=1) SelectedThemesIssuesFormSet = formset_factory(SelectedThemeIssueForm, extra=6)
def test_formset_with_errors(self): SampleFormSet = formset_factory(ShortCharFieldForm, extra=1, max_num=2, validate_max=True) data = { "name-0-name": "test", "name-INITIAL_FORMS": "0", "name-MIN_NUM_FORMS": "0", "name-MAX_NUM_FORMS": "0", "name-TOTAL_FORMS": "3", } formset = SampleFormSet(data=data, prefix="name") formset.helper = FormHelper() formset.helper.formset_error_title = "Non Form Errors" formset.helper.form_tag = False formset.helper.layout = Layout("email") html = render_crispy_form(formset) expected_html = """ <div> <input type="hidden" name="name-TOTAL_FORMS" value="3" id="id_name-TOTAL_FORMS" /> <input type="hidden" name="name-INITIAL_FORMS" value="0" id="id_name-INITIAL_FORMS" /> <input type="hidden" name="name-MIN_NUM_FORMS" value="0" id="id_name-MIN_NUM_FORMS" /> <input type="hidden" name="name-MAX_NUM_FORMS" value="0" id="id_name-MAX_NUM_FORMS" /> </div> <div class="alert mb-4"> <div class="bg-red-500 text-white font-bold rounded-t px-4 py-2"> Non Form Errors </div> <div class="border border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700"> <ul> <li>Please submit 2 or fewer forms.</li> </ul> </div> </div> <div id="div_id_name-0-name" class="mb-3"> <label for="id_name-0-name" class="block text-gray-700 text-sm font-bold mb-2"> Name<span class="asteriskField">*</span> </label> <input type="text" name="name-0-name" value="test" maxlength="3" class="textinput textInput inputtext leading-normal bg-white w-full focus:outline-none text-gray-700 py-2 appearance-none rounded-lg px-4 block border border-red-500" id="id_name-0-name" /> <p id="error_1_id_name-0-name" class="text-red-500 text-xs italic"><strong>Ensure this value has at most 3 characters (it has 4).</strong></p> </div> <div id="div_id_name-1-name" class="mb-3"> <label for="id_name-1-name" class="block text-gray-700 text-sm font-bold mb-2"> Name<span class="asteriskField">*</span> </label> <input type="text" name="name-1-name" maxlength="3" class="textinput textInput inputtext leading-normal bg-white w-full focus:outline-none text-gray-700 py-2 appearance-none rounded-lg px-4 block border border-gray-300" id="id_name-1-name" /> </div> <div id="div_id_name-2-name" class="mb-3"> <label for="id_name-2-name" class="block text-gray-700 text-sm font-bold mb-2"> Name<span class="asteriskField">*</span> </label> <input type="text" name="name-2-name" maxlength="3" class="textinput textInput inputtext leading-normal bg-white w-full focus:outline-none text-gray-700 py-2 appearance-none rounded-lg px-4 block border border-gray-300" id="id_name-2-name" /> </div> """ self.assertHTMLEqual(html, expected_html)
from app.models.account import * class UserProfileForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'phone_num', 'pickup_arrangements', 'send_reminders'] class UserAddressForm(forms.ModelForm): class Meta: model = Address exclude = ['country'] UserProfileFormSet = formset_factory(UserProfileForm, UserAddressForm) class ChangePasswordForm(forms.ModelForm): id = forms.CharField(widget=forms.HiddenInput()) old_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}), label='Old password', required=True) new_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}), label='New password', required=True) confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}), label='Confirm New password', required=True) class Meta: model = User fields = ['id', 'old_password', 'new_password', 'confirm_password']
def test_formset_layout(settings): SampleFormSet = formset_factory(SampleForm, extra=3) formset = SampleFormSet() helper = FormHelper() helper.form_id = 'thisFormsetRocks' helper.form_class = 'formsets-that-rock' helper.form_method = 'POST' helper.form_action = 'simpleAction' helper.layout = Layout( Fieldset( "Item {{ forloop.counter }}", 'is_company', 'email', ), HTML("{% if forloop.first %}Note for first form only{% endif %}"), Row('password1', 'password2'), Fieldset( "", 'first_name', 'last_name' ) ) html = render_crispy_form( form=formset, helper=helper, context={'csrf_token': _get_new_csrf_string()} ) # Check formset fields assert contains_partial(html, '<input id="id_form-TOTAL_FORMS" name="form-TOTAL_FORMS" type="hidden" value="3"/>' ) assert contains_partial(html, '<input id="id_form-INITIAL_FORMS" name="form-INITIAL_FORMS" type="hidden" value="0"/>' ) assert contains_partial(html, '<input id="id_form-MAX_NUM_FORMS" name="form-MAX_NUM_FORMS" type="hidden" value="1000"/>' ) assert contains_partial(html, '<input id="id_form-MIN_NUM_FORMS" name="form-MIN_NUM_FORMS" type="hidden" value="0"/>' ) assert html.count("hidden") == 5 # Check form structure assert html.count('<form') == 1 assert html.count('csrfmiddlewaretoken') == 1 assert 'formsets-that-rock' in html assert 'method="post"' in html assert 'id="thisFormsetRocks"' in html assert 'action="%s"' % reverse('simpleAction') in html # Check form layout assert 'Item 1' in html assert 'Item 2' in html assert 'Item 3' in html assert html.count('Note for first form only') == 1 if settings.CRISPY_TEMPLATE_PACK == 'uni_form': assert html.count('formRow') == 3 elif settings.CRISPY_TEMPLATE_PACK in ('bootstrap3', 'bootstrap4'): assert html.count('row') == 3 if settings.CRISPY_TEMPLATE_PACK == 'bootstrap4': assert html.count('form-group') == 18
def __init__(self, *args, **kwargs): super(RoleForm, self).__init__(*args, **kwargs) self.fields['name'].error_messages = {'required': u'请输入角色名!'} def clean(self): cleaned_data = super(RoleForm, self).clean() name = cleaned_data.get('name') # 判断角色名是否重复 if name: existing = False if self.instance._state.adding: if models.Role.objects.filter(name=name).count() > 0: existing = True else: if models.Role.objects.filter(~Q(uuid=self.instance.uuid), name=name).count() > 0: existing = True if existing: self._errors['name'] = self.error_class([u'角色名已存在!']) return cleaned_data class Meta: model = models.Role exclude = ['uuid'] RolePrivilegesFormSet = formset_factory(RolePrivilegesForm)