def CameraSelectionView(request, id=None): CamForm = modelform_factory( Camera, fields= '__all__', widgets={ 'project': forms.HiddenInput(), 'name': forms.TextInput(attrs={'class':'form-control',}), 'device': forms.Select(attrs={'class':'form-control',}), 'installed': forms.CheckboxInput(attrs={'class':'form-control',}), 'serial': forms.TextInput(attrs={'class':'form-control',}), 'network': forms.TextInput(), 'description': forms.TextInput(attrs={'class':'form-control',}), 'notes': forms.Textarea(attrs={'class':'form-control',}), } ) NetForm = modelform_factory( NetworkInfo, fields=('__all__'), widgets={ 'ip': forms.TextInput(attrs={'class':'form-control'}), 'subnet': forms.TextInput(attrs={'class':'form-control'}), 'gateway': forms.TextInput(attrs={'class':'form-control'}), 'MAC': forms.TextInput(attrs={'class':'form-control'}), 'vlan': forms.TextInput(attrs={'class':'form-control'}), } ) # exsisting Camera try: cObj = Camera.objects.get(pk=id) cForm = CamForm(instance=cObj) try: nObj = cObj.network nForm = NetForm(instance=nObj) except: nObj = None nForm = NetForm() # new Camera except Camera.DoesNotExist: cObj = None cForm = CamForm() nObj = None nForm = NetForm() print(cForm) if request.method == 'POST': camform = CamForm(request.POST, instance=cObj) netform = NetForm(request.POST, instance=nObj) if camform.is_valid(): tmpCam = camform.save(commit=False) if netform.is_valid(): tmpForm = netform.save() tmpNet = NetworkInfo.objects.get(pk=tmpForm.id) tmpCam.serial = tmpNet.MAC tmpCam.network = tmpNet tmpCam.save() return render(request, 'cameras/details.html', {'form': cForm, 'netform': nForm})
def form_class_from_model(self): if self.model_name in self.model_form_fields: Form = modelform_factory( self.model, fields=self.model_form_fields[self.model_name], widgets={"user": widgets.TextInput} ) else: Form = modelform_factory(self.model, exclude=self.excluded_fields, widgets={"user": widgets.TextInput}) return Form
def addmateria(request, materia_id=None): if(request.user.perfil.tipus.nom == 'professor' or request.user.perfil.tipus.nom == 'admin'): esModificacio=(materia_id!=None) addmateriaForm=modelform_factory(Materia,exclude=(),) if esModificacio: materia=get_object_or_404(Materia,pk=materia_id) else: materia=Materia() if request.method=='POST': form=addmateriaForm(request.POST, request.FILES, instance=materia) if form.is_valid(): materia=form.save() messages.success(request,'materia desat!') return HttpResponseRedirect(reverse('exercicisapp:addmateria')) else: messages.error(request, 'Revisa els errors del formulari') else: form=addmateriaForm(instance=materia); form.helper = FormHelper() form.helper.form_class = 'blueForms' form.helper.label_class = 'col-lg-2' form.helper.field_class = 'col-lg-10' form.helper.add_input(Submit('submit', 'Afegir')) return render(request, 'form.html', {'form':form, 'actual':"Afegir Matèria"}) else: return HttpResponseRedirect(reverse('exercicisapp:repartir'))
def get_form_class(self): return forms.modelform_factory( get_application_model(), fields=( "name", "redirect_uris" ) )
def addresposta_possible(request, resposta_possible_id=None): if(request.user.perfil.tipus.nom == 'professor' or request.user.perfil.tipus.nom == 'admin'): esModificacio=(resposta_possible_id!=None) addresposta_possibleForm=modelform_factory(Resposta_possible,exclude=(),) if esModificacio: resposta_possible=get_object_or_404(Resposta_possible,pk=resposta_possible_id) else: resposta_possible=Resposta_possible() if request.method=='POST': form=addresposta_possibleForm(request.POST, request.FILES, instance=resposta_possible) if form.is_valid(): resposta_possible=form.save() messages.success(request,'resposta_possible desat!') return HttpResponseRedirect(reverse('exercicisapp:addresposta_possible')) else: messages.error(request, 'Revisa els errors del formulari') else: form=addresposta_possibleForm(instance=resposta_possible); form.helper = FormHelper() form.helper.form_class = 'blueForms' form.helper.label_class = 'col-lg-2' form.helper.field_class = 'col-lg-10' form.helper.add_input(Submit('submit', 'Afegir')) return render(request, 'form.html', {'form':form}) else: return HttpResponseRedirect(reverse('exercicisapp:repartir'))
def update_field(request, pk, field): """ This is function and not a CreateView/Update as it points to a template with less fields :param request: :param pk: primary key of Canvas :param field: which field to update :return: """ widgets = {} if field=='logo': widgets[field] = ClearableFileInput() else: widgets[field] = Textarea(attrs={'rows':4, 'cols':150}) CanvasForm = modelform_factory(Canvas, fields=(field,), widgets=widgets) if request.method == 'POST': form = CanvasForm(request.POST) if form.is_valid(): obj = Canvas.objects.get(id=pk) if obj.originalauthor == request.user: # more maintainable than dfunckt/django-rules if 'logo' in request.FILES: data = ContentFile(request.FILES['logo'].file.read()) filename = request.FILES['logo'].name form.cleaned_data['logo'] = filename default_storage.save(filename, data) setattr(obj, field, form.cleaned_data[field]) obj.save() return HttpResponseRedirect('/canvas/'+pk) else: return HttpResponseRedirect('/login/') else: form = CanvasForm(instance = Canvas.objects.get(id=pk)) return render(request, 'app/canvas_form.html', {'formfield': form})
def intro_edit_tipus(request, id_tipus=None): if (request.user.username != "admin"): messages.add_message(request, messages.ERROR, 'No tens permisos per fer aquesta acció') return HttpResponseRedirect(reverse('producte:veure_productes')) else: es_modificacio =(id_tipus!=None) tipusForm =modelform_factory(Tipus_Producte, exclude=()) if es_modificacio: tipus = get_object_or_404(Tipus_Producte, id=id_tipus) else: tipus=Tipus_Producte() if request.method == 'POST': form = tipusForm(request.POST,instance=tipus) if form.is_valid(): tipus = form.save() if(es_modificacio): messages.add_message(request, messages.SUCCESS, 'El tipu ha sigut modificat correctament') else: messages.add_message(request, messages.SUCCESS, 'El nou tipu ha sigut creat correctament') return HttpResponseRedirect(reverse('producte:veure_tipus')) else: if(es_modificacio): messages.add_message(request, messages.ERROR, 'Error en modificar el tipu') else: messages.add_message(request, messages.ERROR, 'Error en crear el tipu nou') else: form = tipusForm(instance=tipus) form.helper = FormHelper() form.helper.form_class = 'form-horizontal col-md-8 col-md-offset-2' form.helper.label_class = 'col-lg-3' form.helper.field_class = 'col-lg-9' form.helper.add_input(Submit('submit', 'Enviar')) return render(request, 'formulari.html', {'form': form, 'tipu': tipus})
def delete_photo(request): """ A view specifically for deleting the photo attached to a profile so that we can do that via ajax and a nicer UI, rather than using Django's clearable file input (which is a bit clunky). """ if request.method == 'POST' and request.is_ajax(): # Delete the photo attendee = request.user.conference_attendee_profile sorl.thumbnail.delete(attendee.photo, delete_file=False) attendee.photo.delete() # Saves the model automatically # Build a new form form_class = modelform_factory(Attendee, fields=['photo']) form = form_class(instance=attendee) form.fields['photo'].widget = forms.FileInput() # Render a response with the form and updated attendee html = render_to_string( 'conference/_profile_photo.html', {'attendee': attendee, 'form': form} ) return HttpResponse(html) else: return HttpResponseBadRequest("This endpoint is only available to AJAX POST requests")
def _get_tacc_user_for_xsede_username(request): context = {} form_class = modelform_factory( TACCUserForXSEDEUsername, fields=['xsede_username'], widgets={'xsede_username': TextInput} ) if request.method == 'POST': request.POST = request.POST.copy() form = form_class(request.POST) form.is_valid() xsede_username = form.cleaned_data['xsede_username'] info, header, rows = _execute_tas_api_query( TACC_USERNAME_FOR_XSEDE_USERNAME, xsede_username ) context['info'] = info context['header'] = header context['rows'] = rows else: form = form_class() context['form'] = form context['title'] = TACCUserForXSEDEUsername._meta.verbose_name return render(request, 'tas_api_query.html', context)
def _get_projects_for_user(request): context = {} form_class = modelform_factory( ProjectsForUser, fields=['tacc_username'], widgets={'tacc_username': TextInput} ) if request.method == 'POST': request.POST = request.POST.copy() form = form_class(request.POST) form.is_valid() tacc_username = form.cleaned_data['tacc_username'] info, header, rows = _execute_tas_api_query( PROJECTS_FOR_USER, tacc_username ) context['info'] = info context['header'] = header context['rows'] = rows else: form = form_class() context['form'] = form context['title'] = ProjectsForUser._meta.verbose_name return render(request, 'tas_api_query.html', context)
def add_staff_member(request): if request.method == "POST": new_service_user = StaffMember(title=request.POST["title"],first_name=request.POST["first_name"],second_name=request.POST["second_name"],full_name=request.POST["full_name"],contact_phone=request.POST["contact_phone"]) new_service_user.save() staff_member = modelform_factory(StaffMember, fields=("title","first_name","second_name","full_name","contact_phone",),) context_var = RequestContext(request,{"title":"Weekly Progress Report","brand":"Add Staff Member","form":staff_member}) return render_to_response(template_name="ArchForms/addstaffmember.html",context=context_var)
def access_request(request): """Ask for access to restricted datasets""" AccessRequestForm = modelform_factory(AccessRequest, fields=('justification',)) current_site = get_current_site(request) profile_url = reverse('account-user-profile') if request.user.username == "guest": return redirect(profile_url) active_request = AccessRequest.objects.for_user(request.user) if active_request: if active_request.approved is None: messages.add_message(request, messages.INFO, 'You already have a pending access request. You will receive a notification when it is processed.') return redirect(profile_url) if request.method == 'POST': form = AccessRequestForm(request.POST) if form.is_valid(): user_request = form.save(commit=False) user_request.user = request.user user_request.save() dashboard.email.email_admin_on_access_request(current_site, request.user, user_request.justification) messages.add_message(request, messages.INFO, 'Your access request has been received. You will receive a notification when it is processed.') return redirect(profile_url) else: form = AccessRequestForm() ret = { 'today': datetime.datetime.now().strftime('%Y-%m-%d'), 'form': form } return render(request, 'account/access_request.html', ret)
def proposal_create(request, *, slug): cfp = get_object_or_404(Cfp, slug=slug) context = RequestContext(request, {'cfp': cfp}) right_now = now() if cfp.date_start > right_now: return TemplateResponse(request, 'cfp/proposal_before.html', context) elif cfp.date_end < right_now: return TemplateResponse(request, 'cfp/proposal_after.html', context) ProposalForm = modelform_factory(Proposal, exclude=['cfp', 'date']) if request.method.lower() == 'post': form = ProposalForm(request.POST) form.instance.cfp = cfp if form.is_valid(): form.save() return redirect(to='cfp_success', slug=slug) else: form = ProposalForm() context['form'] = form return TemplateResponse(request, 'cfp/proposal_form.html', context)
def _get_users_for_project(request): context = {} form_class = modelform_factory( UsersForProject, fields=['project_charge_code'], widgets={'project_charge_code': TextInput} ) if request.method == 'POST': request.POST = request.POST.copy() form = form_class(request.POST) form.is_valid() project_charge_code = form.cleaned_data['project_charge_code'] info, header, rows = _execute_tas_api_query( USERS_FOR_PROJECT, project_charge_code ) context['info'] = info context['header'] = header context['rows'] = rows else: form = form_class() context['form'] = form context['title'] = UsersForProject._meta.verbose_name return render(request, 'tas_api_query.html', context)
def _get_active_allocations(request): context = {} form_class = modelform_factory( ActiveAllocations, fields=['resource'], widgets={'resource': TextInput} ) if request.method == 'POST': request.POST = request.POST.copy() form = form_class(request.POST) form.is_valid() resource = form.cleaned_data['resource'] info, header, rows = _execute_tas_api_query( ACTIVE_ALLOCATIONS, resource ) context['info'] = info context['header'] = header context['rows'] = rows else: form = form_class() context['form'] = form context['title'] = ActiveAllocations._meta.verbose_name return render(request, 'tas_api_query.html', context)
def intro_edit_marca(request, id_marca=None): if (request.user.username != "admin"): messages.add_message(request, messages.ERROR, 'No tens permisos per fer aquesta acció') return HttpResponseRedirect(reverse('producte:veure_productes')) else: es_modificacio =(id_marca!=None) marcaForm =modelform_factory(Marca_Producte, exclude=()) if es_modificacio: marca = get_object_or_404(Marca_Producte, id=id_marca) else: marca=Marca_Producte() if request.method == 'POST': form = marcaForm(request.POST,instance=marca) if form.is_valid(): marca = form.save() if(es_modificacio): messages.add_message(request, messages.SUCCESS, 'La marca ha sigut modificada correctament') else: messages.add_message(request, messages.SUCCESS, 'La nova marca ha sigut creada correctament') return HttpResponseRedirect(reverse('producte:veure_marcas')) else: if(es_modificacio): messages.add_message(request, messages.ERROR, 'Error en modificar la marca') else: messages.add_message(request, messages.ERROR, 'Error en crear la marca nova') else: form = marcaForm(instance=marca) form.helper = FormHelper() form.helper.form_class = 'form-horizontal col-md-8 col-md-offset-2' form.helper.label_class = 'col-lg-3' form.helper.field_class = 'col-lg-9' form.helper.add_input(Submit('submit', 'Enviar')) return render(request, 'formulari.html', {'form': form, 'marca': marca})
def proposal_create(request, *, key): try: config = proposals.get_config(key) except KeyError: raise Http404 context = {'proposal_config': config} is_public = not request.user.is_superuser right_now = now() if is_public and config.date_start > right_now: return TemplateResponse(request, 'proposals/proposal_before.html', context) elif is_public and config.date_end < right_now: return TemplateResponse(request, 'proposals/proposal_after.html', context) ProposalForm = modelform_factory(config.model, exclude=['note', 'date']) if request.method.lower() == 'post': form = ProposalForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(to='proposal_success', key=key) else: form = ProposalForm() context['form'] = form return TemplateResponse(request, 'proposals/proposal_form.html', context)
def test_action_admin_form_in_use(): """Actions that are in-use can be edited.""" action = RecipeFactory(enabled=True).action FormClass = modelform_factory(Action, fields=['name']) form = FormClass({'name': 'foo'}, instance=action) assert form.is_valid()
def get_form_class(self, obj, fields=None): if not fields: fields = '__all__' if not isinstance(obj, Model): raise PatchException( 'get_model_form: obj should be an ' 'instance of django.db.models.Model. Instead found {0}'.format(type(obj))) return modelform_factory(obj.__class__, fields=fields)
def __init__( self, model, bsct_view_prefix = None, form_class=None ): """ Internalize the model and set the view prefix. """ self.model = model self.bsct_view_prefix = bsct_view_prefix or model.__name__.lower() self.form_class = form_class if form_class is not None else modelform_factory( model=self.model, fields='__all__')
def get_result(request): validation_form = modelform_factory(Results, fields='__all__') form = validation_form(request.POST or None) if form.is_valid(): form.save() return HttpResponse(status=200) return HttpResponse(status=404)
def create_feature_form(self): feature = FeatureRegistry.objects.get(key_name=self.key_name) self.feature_form['name'] = feature.key_name self.feature_form['default_ui_rank'] = feature.default_ui_rank if self.customization_class: feature_form = eval(self.customization_class)().form else: feature_form = forms.modelform_factory(apps.get_model('features', feature.model_class), fields="__all__") self.feature_form['form'] = feature_form
def get_name(request): TeamForm = modelform_factory(Team, fields='__all__') if request.method == 'POST': team_form = Team(request.POST, request.FILES) if team_form.is_valid(): team_form.save() return render(request, 'confirmation.html', {'team_form': team_form, }) else: team_form = TeamForm() return render(request, 'team_info.html', {'team_form': team_form})
def get_page_form(model_ct, form=HelpBasePageForm): model = model_ct.model_class() assert issubclass(model, models.HelpBasePage) and model != models.HelpBasePage, \ "Model must be a subclass of HelpBasePage, but not HelpBasePage itself." assert model in PAGE_TYPES, "Not a supported model" form = forms.modelform_factory(model, form=form, fields=model.admin_fields) form.model_ct = model_ct return form
def post(self,request,modelName,id): context = request.session session_id = context['IndexInput']['id'] _model = self.class_map[modelName][0] exclude = self.class_map[modelName][1] _form = modelform_factory(_model,exclude=exclude) item = _model.objects.get(session_id=session_id,id=id) form = _form(request.POST, instance=item) status = form.save() return render(request, 'updateItem.html', { 'modelName':modelName, 'form':form, 'status':status })
def get_update_kwargs(self): kwargs = self.get_default_view_kwargs() form_class = (self.update_form_class if self.update_form_class else self.form_class) if form_class is None: form_class = modelform_factory(self.model, fields='__all__') kwargs.update({ 'inlines': self.inlines, 'form_class': form_class, }) return kwargs
def create_league(request): LeagueForm = modelform_factory(FantasyLeague, fields=('__all__')) if request.method == 'POST': form = LeagueForm(request.POST) if form.is_valid(): league = form.save() _init_players_for_league(league) return HttpResponseRedirect('league_homepage/%s' % league.id) else: form = LeagueForm() return render(request, 'nba_fantasy/create_league.html', {'form':form})
def get_context_data(self, **kwargs): context = super(ServiceReportCreate, self).get_context_data(**kwargs) lines = self.object.lines.all().prefetch_related('damaged_area', 'damage_type').select_related('variant__product__vendor') formset = modelformset_factory(ServiceReportLine, exclude=['report'], extra=lines.count()) formset = formset(queryset=ServiceReportLine.objects.none()) for idx, frm in enumerate(formset): frm.initial['line'] = lines[idx] context['formset'] = formset context['lines'] = lines context['form'] = modelform_factory(ServiceReport, exclude=['service']) return context
def get_form_class(self): """ Method for generating a form class for the view :return: ModelForm class """ return modelform_factory( self.model, exclude=self.exclude, form=self.form_class, widgets=self._get_form_widgets() )
def get_form_class(self): """ Method for generating a form class from the data contained within the model :return: ModelForm class """ return modelform_factory( self.content_type.model_class(), form=self._get_base_form_class(), fields=self.used_field_names, formfield_callback=self.formfield_callback )
from django import forms from django.contrib import messages from django.db import models from django.shortcuts import redirect from django.urls import reverse from django.utils.timezone import now from django.utils.translation import ugettext_lazy as _ from django.views.generic import DetailView, FormView, ListView from byro.bookkeeping.models import Account, AccountCategory, Transaction FORM_CLASS = forms.modelform_factory(Account, fields=["name", "account_category"]) ACCOUNT_COLUMN_HEADERS = { # FIXME Check this with an accountant who is a native english speaker AccountCategory.INCOME: (_("Charge"), _("Revenue")), AccountCategory.ASSET: (_("Increase"), _("Decrease")), AccountCategory.EQUITY: (_("Decrease"), _("Increase")), AccountCategory.LIABILITY: (_("Decrease"), _("Increase")), AccountCategory.EXPENSE: (_("Expense"), _("Rebate")), } class AccountListView(ListView): template_name = "office/account/list.html" context_object_name = "accounts" model = Account class AccountCreateView(FormView):
def get_form_class(self): return modelform_factory(self.model, fields=['description'])
def get_form_class(self): return modelform_factory(self.model, form=self.form_class, fields=self.fields)
def test_form_valid(self): data = self.data form = modelform_factory(qa_models.TestList, form=qa_admin.TestListAdminForm, exclude=['tests'])(data=data) self.assertTrue(form.is_valid())
def recruitment_application_interview( request, year, recruitment_period_pk, pk, template_name='recruitment/recruitment_application_interview.html'): fair = get_object_or_404(Fair, year=year) application = get_object_or_404(RecruitmentApplication, pk=pk) user = request.user if not user_can_access_recruitment_period(user, application.recruitment_period): return HttpResponseForbidden() InterviewPlanningForm = modelform_factory( RecruitmentApplication, fields=('interviewer', 'interviewer2', 'slot', 'recommended_role', 'scorecard', 'drive_document', 'rating'), widgets={ 'rating': forms.Select(choices=[('', '-------'), (1, 1), (2, 2), (3, 3), (5, 5)]), 'scorecard': forms.TextInput( attrs={'placeholder': 'Link to existing document'}), 'drive_document': forms.TextInput( attrs={'placeholder': 'Link to existing document'}), }, labels={ 'drive_document': _('Interview document'), }, help_texts={ 'slot': '<strong>Note:</strong> If you select a slot with <strong>Other</strong> as the location you must book a location separately and communicate this location to the participants of the interview.' }, ) profile_pic_form = None profile = Profile.objects.get(user=application.user) if Profile.objects.filter(user=application.user).first(): profile_pic_form = ProfilePictureForm(request.POST or None, request.FILES or None, instance=profile) interviewers = application.recruitment_period.interviewers() interview_planning_form = InterviewPlanningForm(request.POST or None, instance=application) interview_planning_form.fields[ 'recommended_role'].queryset = application.recruitment_period.recruitable_roles used_slots = [] for a in RecruitmentApplication.objects.select_related('slot').exclude( slot=None).exclude(pk=application.pk): used_slots.append(a.slot) slots_by_day = [('', '---------')] all_slots = Slot.objects.filter( recruitment_period=application.recruitment_period) local_tz = pytz.timezone('Europe/Stockholm') for slot in all_slots: found = False slot_yyyymmdd = local_tz.localize(slot.start, is_dst=None) slot_yyyymmdd = slot_yyyymmdd.strftime('%Y-%m-%d') for slot_by_day in slots_by_day: if slot_by_day[0] == slot_yyyymmdd: found = True break if not found: slots_by_day.append((slot_yyyymmdd, [])) for slot in all_slots: if slot in used_slots and slot.location.name != 'Other': continue slot_start = local_tz.localize(slot.start, is_dst=None) slot_yyyymmdd = slot_start.strftime('%Y-%m-%d') for slot_by_day in slots_by_day: if slot_by_day[0] == slot_yyyymmdd: slot_hhmm_start = slot_start.strftime('%H:%M') slot_hhmm_end = slot_start + datetime.timedelta( minutes=slot.length) slot_hhmm_end = slot_hhmm_end.strftime('%H:%M') slot_by_day[1].append( (slot.pk, slot_hhmm_start + '-' + slot_hhmm_end + ' | ' + str(slot.location))) break interview_planning_form.fields['slot'].choices = slots_by_day languages = Language.objects.all() interviewers_by_language = [(None, [])] for language in languages: interviewers_by_language.insert(0, (language, [])) for interviewer in interviewers: p = Profile.objects.filter(user=interviewer).first() for language in interviewers_by_language: if language[0] == p.preferred_language: language[1].append( (interviewer.pk, interviewer.get_full_name())) break interviewers_by_language[len(interviewers_by_language) - 1] = ( 'No preferred language', interviewers_by_language[len(interviewers_by_language) - 1][1]) interviewers_by_language = [ x for x in interviewers_by_language if len(x[1]) > 0 ] interviewers_by_language.insert(0, ('', '---------')) if 'interviewer' in interview_planning_form.fields: interview_planning_form.fields[ 'interviewer'].choices = interviewers_by_language if 'interviewer2' in interview_planning_form.fields: interview_planning_form.fields[ 'interviewer2'].choices = interviewers_by_language RoleDelegationForm = modelform_factory( RecruitmentApplication, fields=['delegated_role', 'superior_user', 'status']) role_delegation_form = RoleDelegationForm(request.POST or None, instance=application) role_delegation_form.fields[ 'delegated_role'].queryset = application.recruitment_period.recruitable_roles role_delegation_form.fields['superior_user'].choices = [ ('', '---------') ] + [(interviewer.pk, interviewer.get_full_name()) for interviewer in interviewers] if request.POST: application.recruitment_period.interview_questions.handle_answers_from_request( request, application.user) if interview_planning_form.is_valid(): interview_planning_form.save() if role_delegation_form: if role_delegation_form.is_valid(): role_delegation_form.save() return redirect('recruitment_period', fair.year, application.recruitment_period.pk) else: return redirect('recruitment_period', fair.year, application.recruitment_period.pk) if application.slot and application.interviewer and application.interviewer2 and ( request.user == application.interviewer or request.user == application.interviewer2): other = application.interviewer if application.interviewer != request.user else application.interviewer2 nicetime = local_tz.localize(slot.start, is_dst=None) nicetime = nicetime.strftime("%Y-%m-%d %H:%M") sms_english = "Hello! Thank you for applying to THS Armada. This is a confirmation of our interview arrangement. The interview is scheduled to take place on " + nicetime + " in " + str( slot.location ) + ". If you have any questions or if you would like to change the date and time, don't hesitate to contact me. " + other.first_name + " " + other.last_name + " and I are looking forward to meet you. /" + request.user.first_name + " " + request.user.last_name sms_swedish = "Hej! Tack för att du har sökt till THS Armada. Detta är en bekräftelse på vår överenskommelse. Intervjun är planerad till " + nicetime + " i " + str( slot.location ) + ". Tveka inte att kontakta mig om du har några frågor eller om du vill ändra datum eller tid. " + other.first_name + " " + other.last_name + " och jag själv ser fram emot att få träffa dig. /" + request.user.first_name + " " + request.user.last_name elif application.slot and application.interviewer and request.user == application.interviewer: nicetime = local_tz.localize(slot.start, is_dst=None) nicetime = nicetime.strftime("%Y-%m-%d %H:%M") sms_english = "Hello! Thank you for applying to THS Armada. This is a confirmation of our interview arrangement. The interview is scheduled to take place on " + nicetime + " in " + str( slot.location ) + ". If you have any questions or if you would like to change the date and time, don't hesitate to contact me. I am looking forward to meet you. /" + request.user.first_name + " " + request.user.last_name sms_swedish = "Hej! Tack för att du har sökt till THS Armada. Detta är en bekräftelse på vår överenskommelse. Intervjun är planerad till " + nicetime + " i " + str( slot.location ) + ". Tveka inte att kontakta mig om du har några frågor eller om du vill ändra datum eller tid. Jag ser fram emot att få träffa dig. /" + request.user.first_name + " " + request.user.last_name else: sms_english = None sms_swedish = None return render( request, template_name, { "profile_pic_form": profile_pic_form, "application": application, "application_questions_with_answers": application.recruitment_period.application_questions. questions_with_answers_for_user(application.user), "interview_questions_with_answers": application.recruitment_period.interview_questions. questions_with_answers_for_user(application.user), "interview_planning_form": interview_planning_form, "role_delegation_form": role_delegation_form, "profile": profile, "sms_english": sms_english, "sms_swedish": sms_swedish, "fair": fair, })
meeting = get_object_or_404(Meeting, pk=id) return render(request, "meeting/details.html", {'meeting': meeting, 'message': "Created By Pradhyum Vyas", 'date': (datetime.today().date())}) def all_meeting(request): all_meeting = Meeting.objects.all() return render(request, {'all_meeting': all_meeting}) def remove(request): return render(request, "meeting/remove.html", {'message': "Created By Pradhyum Vyas", 'meeting_count': Meeting.objects.count(), 'meeting': Meeting.objects.all(), 'clear':Meeting.delete()}) def rooms(request): return render(request, "meeting/rooms.html", {'room':Room.objects.all(), 'message': "Created By Pradhyum Vyas", 'date': (datetime.today().date())}) NewMeeting = modelform_factory(Meeting, exclude=[]) def form(request): if request.method == "POST": form = NewMeeting(request.POST) if form.is_valid(): form.save() return redirect('welcome') else: form = NewMeeting return render(request, 'meeting/new.html', {'form': form})
def test_clean_slug(self): data = self.data data['slug'] = self.tl_1.slug form = modelform_factory(qa_models.TestList, form=qa_admin.TestListAdminForm, exclude=['tests'])(data=data) self.assertFalse(form.is_valid())
def widget_for_object_field(obj, field_name): FieldForm = modelform_factory(obj.source_dynmodel().get_model(), fields=(field_name, )) widget = FieldForm().fields[field_name].widget return widget
def test_modelform_empty(self): Form = modelform_factory(TestModelOptional, fields=('name', 'phone')) f = Form({'name': 'Ted', 'phone_0': '', 'phone_1': ''}) self.assertTrue(f.is_valid()) obj = f.save() self.assertEqual(obj.phone, '')
template_name = 'office/mails/templates.html' context_object_name = 'templates' class RestrictedLanguagesI18nModelForm(I18nModelForm): def __init__(self, *args, **kwargs): if 'locales' not in kwargs: from byro.common.models import Configuration config = Configuration.get_solo() kwargs['locales'] = [config.language or settings.LANGUAGE_CODE] return super().__init__(*args, **kwargs) MAIL_TEMPLATE_FORM_CLASS = forms.modelform_factory( MailTemplate, form=RestrictedLanguagesI18nModelForm, fields=['subject', 'text', 'reply_to', 'bcc'], ) class TemplateDetail(UpdateView): queryset = MailTemplate.objects.all() template_name = 'office/mails/template_detail.html' context_object_name = 'template' success_url = '/mails/templates' form_class = MAIL_TEMPLATE_FORM_CLASS class TemplateCreate(CreateView): model = MailTemplate template_name = 'office/mails/template_detail.html'
from dateutil.relativedelta import relativedelta from django import forms from django.test import TestCase from testapp.models import Interval, IntervalWithChoice IntervalForm = forms.modelform_factory(model=IntervalWithChoice, fields=forms.ALL_FIELDS) class RelativeDeltaFormFieldTest(TestCase): def setUp(self): self.obj = Interval.objects.create(value=relativedelta(years=1)) def test_unbound_form_rendering(self): form = IntervalForm() self.assertHTMLEqual( str(form['value']), ''' <select name="value" id="id_value"> <option value="" selected>---------</option> <option value="P1M">1 month</option> <option value="P3M">3 months</option> <option value="P6M">6 months</option> </select> ''') def test_bound_form_rendering(self): self.obj = Interval.objects.create(value=relativedelta(months=3)) form = IntervalForm(instance=self.obj) self.assertHTMLEqual(
from django import forms from .models import ( AccessoryItem, AmmoItem, Category, GearItem, GunItem, ) class ItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Restricts display of non-belonging categories for Item category = self.instance.category_parent if ('category' in self.fields and Category.objects.filter(name=category).exists()): cqs = Category.objects.get(name=category).get_children() self.fields['category'].queryset = cqs class Meta: exclude = ('added', 'quantity_sold') GunItemForm = forms.modelform_factory(GunItem, form=ItemForm) GearItemForm = forms.modelform_factory(GearItem, form=ItemForm) AmmoItemForm = forms.modelform_factory(AmmoItem, form=ItemForm) AccessoryItemForm = forms.modelform_factory(AccessoryItem, form=ItemForm)
def get_form(self): return modelform_factory(self.model, fields=(self.field_name, ))
def get_form(self): if not self.form: return modelform_factory(self.model, fields=self.get_fields()) else: return self.form
class EmailUserAdmin(UserAdmin): change_list_template = "ledger/accounts/change_emailuser_list.html" add_fieldsets = ((None, { 'classes': ('wide', ), 'fields': ('email', ), }), ) fieldsets = ( (None, { 'fields': ('email', ) }), ('Personal info', { 'fields': ('first_name', 'last_name', 'dob', 'identification', 'position_title', 'character_flagged', 'character_comments') }), ('Permissions', { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups') }), ('Important dates', { 'fields': ('last_login', 'date_joined') }), ) add_fieldsets_for_dummy_user = ((None, { 'classes': ('wide', ), 'fields': ('first_name', 'last_name'), }), ) fieldsets_for_dummy_user = ( (None, { 'fields': ( 'dummy_email', 'email', ) }), ('Personal info', { 'fields': ('first_name', 'last_name', 'dob', 'identification', 'character_flagged', 'character_comments') }), ('Permissions', { 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups') }), ('Important dates', { 'fields': ('last_login', 'date_joined') }), ) # need to override add_form/form because the UserAdmin uses custom forms requiring passwords add_form = modelform_factory(EmailUser, fields=[]) form = add_form list_display = ('email', 'first_name', 'last_name', 'is_staff', 'is_dummy') ordering = ('email', ) search_fields = ('email', 'first_name', 'last_name', 'email') readonly_fields = ('dummy_email', ) def is_dummy(self, o): return o.is_dummy_user is_dummy.boolean = True def get_fieldsets(self, request, obj=None): if not obj: if request.GET.get('dummy', False): return self.add_fieldsets_for_dummy_user else: return self.add_fieldsets elif obj.is_dummy_user: return self.fieldsets_for_dummy_user else: return self.fieldsets def save_model(self, request, obj, form, change): if not obj.pk: # new user is_dummy = request.GET.get("dummy", False) if is_dummy: obj.email = obj.get_dummy_email() obj.save() def formfield_for_manytomany(self, db_field, request=None, **kwargs): if settings.SYSTEM_GROUPS and db_field.name == "groups" and not request.user.is_superuser: kwargs["queryset"] = Group.objects.filter( name__in=settings.SYSTEM_GROUPS) return super(EmailUserAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
import csv, datetime from django.shortcuts import render, redirect from django.forms import modelform_factory from django.forms.models import model_to_dict from django.http import JsonResponse, HttpResponse from django.contrib import messages from .models import Company, JobApp, JobAppStep, Contact ### FORM CLASSES ### from .models import JobAppStepForm CompanyForm = modelform_factory(Company, fields='__all__') JobAppForm = modelform_factory(JobApp, fields='__all__') ContactForm = modelform_factory(Contact, fields='__all__') ### VIEWS FOR AJAX ### def get_company_info(request, company): if company: info = model_to_dict(Company.objects.get(id=company)) # now, to wrangle a potentially multiline about field into a json object... info["about"] = info["about"].splitlines() return JsonResponse(info) def get_contacts(request, company): if company: contacts = list(Contact.objects.filter(company=company).values()) if len(contacts) == 0: contacts = "No contacts" return JsonResponse({'contacts': contacts})
from django.forms import modelform_factory from ghostpost.models import Post AddPostForm = modelform_factory( Post, exclude=['up_vote', 'down_vote', 'sub_time', 'score'])
def get_form_class(self): return modelform_factory(self.model, fields=['name', 'description', 'is_public'])
def get_form_class(self): return modelform_factory(self.model, fields=[self.kwargs['column']], widgets=self.widgets)
def details(requests, id): meeting = Meeting.objects.get(pk=id) return render(requests, "meetings/details.html", {"meeting": meeting}) def meeting_list(requests): meetings = Meeting.objects.all() return render(requests, "meetings/meeting_list.html", {"meeting_list": meetings}) def room_list(requests): rooms = Room.objects.all() return render(requests, "meetings/room_list.html", {"room_list": rooms}) MeetingForm = modelform_factory(Meeting, exclude=[]) def add_meeting(request): if request.method == "POST": form = MeetingForm(request.POST) if form.is_valid(): form.save() meetings = Meeting.objects.all() return render(request, "meetings/meeting_list.html", {"meeting_list": meetings}) else: form = MeetingForm() return render(request, "meetings/add_meeting.html", {"form": form})
from django.forms import modelform_factory from .models import Article """ https://docs.djangoproject.com/en/dev/ref/forms/models/#modelform-factory modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None) """ Form = modelform_factory(Article, fields=("pub_date", "headline", "content"))
from django.forms import PasswordInput, modelform_factory, ModelForm from django.contrib.auth.models import User from .models import Account # Automatically creates a registration form from the User model RegisterForm = modelform_factory( User, fields=("first_name", "last_name", "username", "password", "email"), widgets={"password": PasswordInput()} ) """ Form for user to update account settings """ class AccountSettingsForm(ModelForm): class Meta: model = Account fields = "__all__" exclude = [ "username", "user", "date_created", ]
def test_too_many_tests(self): data = self.data form = modelform_factory(qa_models.TestList, form=qa_admin.TestListAdminForm, exclude=['tests'])(data=data) assert not form.is_valid() assert any("the maximum number allowed is 0" in err for err in form.errors['__all__'])
def ascus_account_presentation(request, introvideo=False): form = None if introvideo: info = get_object_or_404(Webpage, slug="/ascus/account/introvideo/") my_documents = LibraryItem.objects_include_private \ .filter(child_list__record_parent=request.user.people) \ .filter(parent_list__record_child__id=PAGE_ID["ascus"]) \ .filter(tags__id=769) ModelForm = modelform_factory( Video, fields=("file", ), ) form = ModelForm(request.POST or None, request.FILES or None) html_page = "ascus/account.introvideo.html" else: info = get_object_or_404(Webpage, slug="/ascus/account/presentation/") my_documents = LibraryItem.objects_include_private \ .filter(child_list__record_parent=request.user.people) \ .filter(parent_list__record_child__id=PAGE_ID["ascus"]) \ .filter(tags__id=771) html_page = "ascus/account.presentation.html" type = None if "type" in request.GET: type = request.GET.get("type") if type == "video": ModelForm = modelform_factory( Video, fields=("name", "description", "author_list", "url", "is_public"), labels={ "description": "Abstract", "name": "Title", "url": "URL", "author_list": "Author(s)", "is_public": "After the unconference, make my contribution publicly available through the Metabolism of Cities digital library." }) elif type == "poster" or type == "paper": ModelForm = modelform_factory( LibraryItem, fields=("name", "file", "description", "author_list", "is_public"), labels={ "description": "Abstract", "name": "Title", "author_list": "Author(s)", "is_public": "After the unconference, make my contribution publicly available through the Metabolism of Cities digital library." }) elif type == "other": ModelForm = modelform_factory( LibraryItem, fields=("name", "file", "type", "description", "author_list", "is_public"), labels={ "description": "Abstract", "name": "Title", "author_list": "Author(s)", "is_public": "After the unconference, make my contribution publicly available through the Metabolism of Cities digital library." }) form = ModelForm(request.POST or None, request.FILES or None) if request.method == "POST": if form.is_valid(): info = form.save(commit=False) info.status = "active" info.year = 2020 if type == "video": info.type = LibraryItemType.objects.get(name="Video Recording") elif type == "poster": info.type = LibraryItemType.objects.get(name="Poster") elif type == "paper": info.type = LibraryItemType.objects.get( name="Conference Paper") elif introvideo: info.type = LibraryItemType.objects.get(name="Video Recording") info.name = "Introduction video: " + str(request.user.people) info.is_public = False info.save() if introvideo: # Adding the tag "Personal introduction video" info.tags.add(Tag.objects.get(pk=769)) messages.success( request, "Thanks, we have received your introduction video!") review_title = "Review and upload personal video" else: # Adding the tag "Abstract presentation" info.tags.add(Tag.objects.get(pk=771)) messages.success( request, "Thanks, we have received your work! Our team will review your submission and if there are any questions we will get in touch." ) review_title = "Review uploaded presentation" RecordRelationship.objects.create( record_parent=info, record_child_id=PAGE_ID["ascus"], relationship=Relationship.objects.get(name="Presentation"), ) RecordRelationship.objects.create( record_parent=request.user.people, record_child=info, relationship=Relationship.objects.get(name="Author"), ) Work.objects.create( name=review_title, description= "Please check to see if this looks good. If it's a video, audio schould be of decent quality. Make sure there are no glaring problems with this submission. If there are, contact the submitter and discuss. If all looks good, then please look at the co-authors and connect this (create new relationships) to the other authors as well.", part_of_project_id=8, related_to=info, workactivity_id=14, ) return redirect("ascus:account") else: messages.error( request, "We could not save your form, please fill out all fields") context = { "header_title": "My Presentation", "header_subtitle": "Actionable Science for Urban Sustainability · 3-5 June 2020", "edit_link": "/admin/core/webpage/" + str(info.id) + "/change/", "info": info, "form": form, "list": my_documents, } return render(request, html_page, context)
def test_unique(self): self.client.post(self.url_add, data=self.data) form = modelform_factory(qa_models.Tolerance, form=qa_admin.ToleranceForm, fields='__all__')(data=self.data) self.assertFalse(form.is_valid())
#def welcome(request): # return HttpResponse("Hello!!!Welcome to my first project") def welcome(request): all_todoitems = ToDoItem.objects.all() return render(request, 'To_Do/base.html', {'items': all_todoitems}) #def add_item(request): # a=request.POST['content'] # new_item1=ToDoItem(content=a) # new_item1.save() # return render(request,'To_Do/base.html') new_item = modelform_factory(ToDoItem, exclude=[]) def add_item(request): if request.method == "POST": form = new_item(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('welcome') else: form = new_item() return render(request, 'To_Do/base.html', {'form': form}) def delete_item(request, todo_id): item_to_delete = ToDoItem.objects.get(id=todo_id)
if commercial is not None: commercial.locality.is_commercial = False commercial.locality.save() obj = super(CommercialAccountForm, self).save(commit=False) obj.locality.is_public = True obj.locality.is_commercial = True obj.locality.save() if commit: obj.save() return obj class CommercialForm(forms.ModelForm): class Meta: model = Commercial exclude = [ 'locality', ] class OfferForm(forms.ModelForm): class Meta: model = Offer fields = '__all__' widgets = {'commercial': forms.HiddenInput} SubscriberForm = forms.modelform_factory(Subscriber, fields='__all__')
def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form(*args, **kwargs)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # set extra required fields for field, required in self.Meta.extra_required.items(): self.fields[field].required = required self.helper = FormHelper() self.helper.layout = Layout( Row( Column('cpf', css_class='form-group col-md-4 mb-0'), Column('nome_razao_social', css_class='form-group col-md-8 mb-0'), ), Row( Column('sexo', css_class='form-group col-md-4 mb-0'), Column('estado_civil', css_class='form-group col-md-5 mb-0'), Column('tipo_sanguineo', css_class='form-group col-md-3 mb-0'), ), Row( Column('nacionalidade', css_class='form-group col-md-3 mb-0'), Column('natural_cidade', css_class='form-group col-md-6 mb-0'), Column('natural_uf', css_class='form-group col-md-3 mb-0'), ), 'falecido', Submit('submit', 'Salvar'), ) PessoaFisicaForm = modelform_factory(bm.PessoaFisica, form=_PessoaFisicaForm)
class ContactRoleAdmin(admin.ModelAdmin): model = ContactRole list_display_links = ('id', ) list_display = ('id', 'contact', 'resource', 'role') list_editable = ('contact', 'resource', 'role') form = forms.modelform_factory(ContactRole, fields='__all__')