def index(request): user = request.user if not(user.is_authenticated()) or user.is_staff or esProveedor(request) : menu = getCurrentMenu() if menu is None: return render(request,'inicio/home.html',{'menu':None}) #Panic? menu = list(map(expandir,menu)) return render(request,'inicio/home.html',{'menu':menu}) if request.method == "POST": platos = getCurrentMenu() if platos is None: return render(request,'inicio/home.html',{'menu':None}) #Panic? platosResena = list(map(expandir,platos)) formSetPlatos = modelformset_factory(item, form = formMostrarPlato,extra = 0) formSet = formSetPlatos(request.POST,request.FILES) if formSet.is_valid(): for form in formSet: form.save(request) return HttpResponseRedirect('/ordenes/actual/') else: return render(request,'inicio/home.html',{'formMenu': formSet, 'platos': platosResena}) else: platos = getCurrentMenu() if (platos is None): return render(request,'inicio/home.html') else: platosResena = list(map(expandir,platos)) formSetPlatos = modelformset_factory(item, form = formMostrarPlato,extra = 0) formSet = formSetPlatos(queryset = platos) return render(request,'inicio/home.html',{'formMenu': formSet, 'platos': platosResena})
def electee_submission_approval(request, approved=0): # get all unapproved socials and service hours social_list = Social.objects.filter(approved='0') service_hour_list = Service_Hours.objects.filter(approved='0') SocialFormSet = modelformset_factory(Social, fields=('approved',), extra=0) social_formset = SocialFormSet(queryset=Social.objects.filter(approved='0').order_by('timestamp')) ServiceFormSet = modelformset_factory(Service_Hours, fields=('approved',), extra=0) service_formset = ServiceFormSet(queryset=Service_Hours.objects.filter(approved='0').order_by('timestamp')) context = { 'social_list' : social_list, 'service_hour_list' : service_hour_list, 'social_formset' : social_formset, 'service_formset' : service_formset, 'approved': approved } if request.POST: formset = SocialFormSet(request.POST) if formset.is_valid(): formset.save() update_approved_hours() formset = ServiceFormSet(request.POST) if formset.is_valid(): formset.save() update_approved_hours() return redirect('electee_submission_approval', approved=1) return render(request, "electee_submission_approval.html", context)
def add_transmitter(request, project_id): return render_project_formset( request=request, project_id=project_id, post_formset=modelformset_factory(Tx, form=AddTransmitterForm)(data=request.POST), get_formset=modelformset_factory(Tx, form=AddTransmitterForm, extra=2)(queryset=Tx.objects.none()), template_path="project/create-transmitter.html", success_url="%s?new_element=True" % reverse( "project:manage-transmitters", args=(project_id,)))
def add_location(request, project_id): return render_project_formset( request=request, project_id=project_id, post_formset=modelformset_factory(Location, form=AddLocationForm)(data=request.POST), get_formset=modelformset_factory(Location, form=AddLocationForm, extra=2)(queryset=Location.objects.none()), template_path="project/create-location.html", success_url="%s?new_element=True" % reverse( "project:manage-locations", args=(project_id,)))
def see_courses(request): user = get_current_user(request) user_is_admin = request.user.groups.filter(name='admin').exists() can_delete = True if user_is_admin else False used_form = AdminEditCourseForm if user_is_admin else TeacherEditCourseForm if user_is_admin: CourseFormSet = modelformset_factory(Course, fields=('name', 'subject', 'teacher', 'assistants', 'students'), can_delete=can_delete, form=used_form, max_num=1) else: CourseFormSet = modelformset_factory(Course, fields=('name', 'subject', 'assistants', 'students'), can_delete=can_delete, form=used_form, max_num=1) if request.method == 'POST': formset = CourseFormSet(request.POST, request.FILES) if user_is_admin: if formset.is_valid(): for form in formset: course = form.save(commit=False) # TODO get rid of this UGLY WAY Enrollment.objects.filter(course=course).delete() for student in form.clean_students(): Enrollment.objects.create(user=student, course=course) AssistantCourse.objects.filter(course=course).delete() for assistant in form.clean_assistants(): AssistantCourse.objects.create(user=assistant, course=course) course.save() messages.success(request, "Courses successfully edited.") else: messages.error(request, str(formset.errors)) return redirect('index') else: if formset.is_valid(): for form in formset: course = form.save(commit=False) course.teacher = user Enrollment.objects.filter(course=course).delete() for student in form.clean_students(): Enrollment.objects.create(user=student, course=course) AssistantCourse.objects.filter(course=course).delete() for assistant in form.clean_assistants(): AssistantCourse.objects.create(user=assistant, course=course) course.save() messages.success(request, "Courses successfully edited.") else: messages.error(request, str(formset.errors)) return redirect('index') else: if user_is_admin: formset = CourseFormSet(queryset=Course.objects.all()) else: formset = CourseFormSet(queryset=Course.objects.filter(teacher=user)) return render(request, 'course/see_courses.html', {'formset': formset})
def edit_center(request, slug=None): center = Center.objects.get(slug=slug) ImageFormSet = modelformset_factory(CenterPhoto, form=ImageForm) if request.user.is_merchant: if request.method == 'POST': form = CenterForm(request.POST, instance=center) formset = ImageFormSet(request.POST, request.FILES, queryset=CenterPhoto.objects.filter(center=center)) if form.is_valid() and formset.is_valid(): form.save() for form in formset: try: image = form.cleaned_data['image'] photo = CenterPhoto(center=center, image=image) photo.user_id = request.user.id photo.save() except: messages.error(request, 'Technical error') return render(request, "updated_center.html", locals()) else: form = CenterForm(instance=center) formset = ImageFormSet(queryset=CenterPhoto.objects.filter(center=center)) return render(request, 'center_edit.html', {'form': form, 'formset': formset}) else: messages.add_message( request, messages.ERROR, 'You are not allowed to edit this center. Contact an eventdiary admin' ) return redirect(reverse('center_listing'))
def store_edit(request, pk): store = get_object_or_404(Store, pk=pk) if request.user != store.owner: return redirect('/') ImageFormSet = modelformset_factory(StoreImage, form=StoreImageForm, extra=3, max_num=6, can_delete=True) if request.method == 'POST': storeForm = StoreForm(request.POST, instance=store) formset = ImageFormSet(request.POST, request.FILES, queryset=store.storeimage_set.all()) if storeForm.is_valid() and formset.is_valid(): store.save() store_images = formset.save(commit=False) for store_image in store_images: store_image.store = store store_image.save() messages.success(request, "업체가 성공적으로 수정되었습니다.") return redirect("/") else: storeForm = StoreForm(instance=store) formset = ImageFormSet(queryset=store.storeimage_set.all()) return render(request, 'hof/store_form.html', { 'storeForm': storeForm, 'formset': formset, })
def store_new(request): if not request.user.is_staff and not request.user.profile.is_store_owner: return redirect('index') ImageFormSet = modelformset_factory(StoreImage, form=StoreImageForm, extra=6, max_num=6) if request.method == 'POST': storeForm = StoreForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=StoreImage.objects.none()) print(formset) if storeForm.is_valid() and formset.is_valid(): store = storeForm.save(commit=False) store.owner = request.user store.save() print('herer') store_images = formset.save(commit=False) for store_image in store_images: store_image.store = store print('here in') store_image.save() messages.success(request, "업체가 성공적으로 등록되었습니다. 관리자의 승인 후에 실제로 홈페이지에 게시됩니다.") return redirect("/") else: storeForm = StoreForm() formset = ImageFormSet(queryset=StoreImage.objects.none()) return render(request, 'hof/store_form.html', { 'storeForm': storeForm, 'formset': formset, })
def create(request): # validate user is authenticated if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) CandidateFormSet = modelformset_factory(Candidate, can_delete=True, fields=('first_name','last_name','photo','secure_photo')) helper = CandidateFormSetHelper() #helper.add_input(Submit("submit", "Save")) title = "Upload candidate picture" if request.method == 'POST': formset = CandidateFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return HttpResponseRedirect(reverse('candidate-create')) else: formset = CandidateFormSet() context = { "title": title, "formset": formset, "helper": helper, } #return render_to_response("candidate.html", context) return render(request, 'candidate.html', context)
def result_list(context, view, object_list, form_action): """ Displays the headers and data list together """ obj = object_list[0] app_label = obj.__class__.__dict__['__module__'].split('.')[0] from django.forms import modelformset_factory from importlib import import_module try: form = getattr(import_module(app_label + '.forms'), 'Wagtail' + obj.__class__.__name__ + 'Form') except (AttributeError, ImportError): form = None if form: ObjectFormSet = modelformset_factory(obj.__class__, form=form, extra=0) formset = ObjectFormSet(queryset=object_list) context.update({ 'formset': formset, 'zipped': zip(list(results(view, object_list)), formset), }) headers = list(result_headers(view)) num_sorted_fields = 0 for h in headers: if h['sortable'] and h['sorted']: num_sorted_fields += 1 context.update({ 'result_headers': headers, 'num_sorted_fields': num_sorted_fields, 'results': list(results(view, object_list)), 'form_action': form_action, }) return context
def playMFS(request): SuaFormSet = modelformset_factory( Sua, fields=('student', 'team', 'suahours'), extra=1, widgets={ 'student': forms.Select(attrs={ 'class': 'form-control' }), 'team': forms.TextInput(attrs={ 'class': 'form-control' }), 'suahours': forms.TextInput(attrs={ 'class': 'form-control' }) } ) if request.method == 'POST': formset = SuaFormSet(request.POST, request.FILES) if formset.is_valid(): for form in formset: if form.cleaned_data != {}: print(form.cleaned_data) sua = form.save(commit=False) sua.group = SuaGroup.objects.all()[0] sua.title = '批量测试' sua.date = timezone.now() sua.last_time_suahours = 0 sua.is_valid = False sua.save() else: formset = SuaFormSet(queryset=Sua.objects.none()) return render(request, 'sua/playMFS.html', {'formset': formset})
def get_context_data(self, **kwargs): context = super(GSuaPublicityCreate, self).get_context_data(**kwargs) SuaFormSet = modelformset_factory( Sua, fields=('student', 'team', 'suahours'), extra=1, widgets={ 'student': forms.Select(attrs={ 'class': 'form-control' }), 'team': forms.TextInput(attrs={ 'class': 'form-control' }), 'suahours': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': '请输入公益时数', }) } ) date = timezone.now() year = date.year month = date.month if month < 9: year_before = year - 1 year_after = year else: year_before = year year_after = year + 1 if self.request.method == 'POST': formset = SuaFormSet(self.request.POST, self.request.FILES) else: formset = SuaFormSet(queryset=Sua.objects.none()) context['formset'] = formset context['apply_year_before'] = year_before context['apply_year_after'] = year_after return context
def create_pronos_gmds(request, room_id, player_id): room = get_object_or_404(Room, pk=room_id) player = get_object_or_404(Player, id=player_id) query_fixture_played = Pronos.objects.filter(player=player) fixtures = Fixture.objects.filter(roomseason__room__id=room_id).exclude(player__id=player.id) #* EXCEPTIONS *# if request.user.id != room.gmds.id: raise PermissionDenied #* Creations Formset/Form *# pronosFormset = modelformset_factory(Pronos, form=PronosForm, extra=len(fixtures)) if request.method == 'POST': formset = pronosFormset(request.POST, queryset=query_fixture_played) for form in formset.extra_forms: curr_fixture = list(fixtures).pop() form.instance.fixture = curr_fixture form.instance.player = player if formset.is_valid(): if room.gmds == request.user: formset.save() else : formset = pronosFormset(queryset=query_fixture_played) for form in formset.extra_forms: curr_fixture = list(fixtures).pop() form.instance.fixture = curr_fixture return render_to_response('pronos/addPronos.html', {'formset': formset, 'player': player, 'room': room, 'gmds_active': 'active'}, context_instance=RequestContext(request))
def manage_products(request): ProductFormSet = modelformset_factory(Product, fields = ("stock",), extra = 0) if request.method == 'POST': formset = ProductFormSet(request.POST, request.FILES) operations = ManageOperation.objects.filter(date_closed__isnull = True) if operations.exists(): operation = operations[0] if formset.is_valid(): formset.save() operation.closed_by = request.user operation.date_closed = timezone.now() operation.save() product_stocks = ProductStock.objects.filter(operation = operation) for product_stock in product_stocks: product_stock.stock_closed = product_stock.product.stock product_stock.save() return redirect('..') else: return render(request, 'manage_products.html', {'formset': formset , "products": Product.objects.all()}) else: if formset.is_valid(): products = formset.save() operation = ManageOperation.objects.create(opened_by = request.user) for product in products: ProductStock.objects.create( product = product, operation = operation, stock_opened = product.stock, ) return redirect('..') else: return render(request, 'manage_products.html', {'formset': formset , "products": Product.objects.all()}) else: formset = ProductFormSet() return render(request, 'manage_products.html', {'formset': formset , "products": Product.objects.all()})
def see_assignments(request, id): user = get_current_user(request) course = Course.objects.get(id=id) can_delete = True if user == course.teacher or user in course.assistants.all() else False AssignmentFormSet = modelformset_factory(Assignment, fields=('id', 'name', 'description', 'deadline', 'type', 'group'), can_delete=can_delete, form=AssignmentForm, max_num=0) if request.method == 'POST': formset = AssignmentFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() messages.success(request, "Assignments successfully saved.") return redirect('index') else: if user.is_in_group("student"): AssignmentFormSet.form = ReadOnlyAssignmentForm formset = AssignmentFormSet(queryset=Assignment.objects.filter(Q(students__user=request.user) and Q(course=course)).all()) else: formset = AssignmentFormSet(queryset=Assignment.objects.filter(course=course).all()) if len(formset) == 0: messages.info(request, "There are no assignments for this course") return redirect('index') else: return render(request, 'course/see_assignments.html', {'formset': formset, 'course': course, 'user_elearning': user})
def edit_question(request, course_id, question_id): question = Question.objects.get(id=question_id) if request.user.username == question.owner: ChoiceFormSet = modelformset_factory(Choice, ChoiceForm, extra=0) course = Course.objects.get(id=course_id) choices = Choice.objects.filter(question=question) question_form = QuestionForm(instance=question) choice_formset = ChoiceFormSet(queryset=Choice.objects .filter(question=question)) if request.method == 'POST' and 'update' in request.POST: question_form = QuestionForm(instance=question, data=request.POST) choice_formset = ChoiceFormSet(data=request.POST) if question_form.is_valid() and choice_formset.is_valid(): Choice.objects.filter(question=question).delete() update(question_form, question, choice_formset) messages.success(request, 'Question updated successfully!') return redirect('/courses/' + course_id + '/questions/') if request.method == 'POST' and 'delete' in request.POST: question.delete() Choice.objects.filter(question=question).delete() messages.success(request, 'Question deleted successfully!') return redirect('/courses/' + course_id + '/questions/') return render(request, 'edit_question.html', {'form': question_form, 'choice_formset': choice_formset,'course': course, 'question': question, 'choices': choices }) return redirect('/courses/' + course_id)
def substitutions_formset_factory_builder(score_sheet_id, away_home): s = ScoreSheet.objects.get(id=score_sheet_id) already_used_players = [] # first exclude players already in the lineup, but not the player in tiebreaker position for x in getattr(s, '{}_lineup'.format(away_home)).filter(position__tiebreaker=False): if x.player is not None: already_used_players.append(x.player.id) score_sheet_team = getattr(s.match, '{}_team'.format(away_home)) substitution_players_queryset = score_sheet_team.players.all().exclude(id__in=already_used_players) substitution_model = AwaySubstitution if away_home == 'away' else HomeSubstitution class SubstitutionForm(django.forms.ModelForm): player = django.forms.ModelChoiceField( queryset=substitution_players_queryset, required=False, ) return modelformset_factory( model=substitution_model, form=SubstitutionForm, formset=SubstitutionFormSet, fields=['game_order', 'player'], # this may not work for leagues where the game group size is for some reason not the # same as the number of players in a lineup max_num=len(score_sheet_team.players.all()) - settings.LEAGUE['game_group_size'], can_delete=True, )
def form_valid(self, form): formset = modelformset_factory(Stock, form=POStockForm) formset = formset(self.request.POST) if formset.is_valid(): # check if at least one line of quantity is filled filled = False for f in formset: if f.cleaned_data['quantity'] > 0: filled = True break if filled: po = get_object_or_404(PurchaseOrder, pk=self.kwargs.get('pk')) form.instance.location = po.ship_to form.instance.content_object = po form.instance.reason = 'new' stock_adjustment = form.save() for f in formset: if f.cleaned_data['quantity'] > 0: f.instance.adjustment = stock_adjustment f.save() po.update_status() return redirect(po) form.add_error(None, "Please add at least one item.") context = self.get_context_data() context['form'] = form context['formset'] = formset return self.render_to_response(context)
def post(self, request, *args, **kwargs): CommitteeFormSet = modelformset_factory(Committee, form=CommitteeCreateForm) if 'form-TOTAL_FORMS' in request.POST: # It had a management form, so it was a formset; use formset logic. formset = CommitteeFormSet(request.POST) if formset.is_valid(): formset.save() messages.add_message(request, messages.SUCCESS, 'Committee(s) created. You should reimport your data files' 'if you were trying to import potential appointments to ' 'those committees.') return HttpResponseRedirect(reverse_lazy('data_ingest')) else: return self.render_to_response( self.get_context_data(formset=formset)) else: form = CommitteeCreateForm(request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, 'Committee created. You should reimport your data files' 'if you were trying to import potential appointments to ' 'those committees.') return HttpResponseRedirect(reverse_lazy('data_ingest')) else: return self.render_to_response( self.get_context_data(form=form))
def generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False): """ Return a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively. """ opts = model._meta # if there is no field called `ct_field` let the exception propagate ct_field = opts.get_field(ct_field) if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType: raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) fk_field = opts.get_field(fk_field) # let the exception propagate exclude = [*(exclude or []), ct_field.name, fk_field.name] FormSet = modelformset_factory( model, form=form, formfield_callback=formfield_callback, formset=formset, extra=extra, can_delete=can_delete, can_order=can_order, fields=fields, exclude=exclude, max_num=max_num, validate_max=validate_max, min_num=min_num, validate_min=validate_min, ) FormSet.ct_field = ct_field FormSet.ct_fk_field = fk_field FormSet.for_concrete_model = for_concrete_model return FormSet
def common_startup(self, request, *args, **kwargs): try: self.widget = WidgetDefinition.objects.get(family__url=kwargs["widget_url"], label=kwargs["label"]) except WidgetDefinition.DoesNotExist: raise Http404("This Widget Definition does not exist") if not user_has_edit_permission(request.user, self.widget): raise PermissionDenied("You do not have permission to edit the data for this widget") try: self.graph = GraphDefinition.objects.get(tile__widget=self.widget, tile__url=kwargs["tile_url"]) except GraphDefinition.DoesNotExist: raise Http404("This Graph does not exist") if not self.widget.parametisation: self.pval = None else: try: self.pval = ParametisationValue.objects.get(pk=kwargs["pval_id"]) except ParametisationValue.DoesNotExist: raise PermissionDenied("This parameter value set does not exist") self.form_class = get_form_class_for_graph(self.graph, pval=self.pval) self.form_class = forms.formsets.formset_factory(self.form_class, can_delete=True, extra=10) self.overrides_form_class = get_override_form_class_for_graph(self.graph) if self.graph.dynamic_clusters: self.dyncluster_form_class = forms.modelformset_factory(DynamicGraphCluster, form=DynamicGraphClusterForm, can_delete=True, extra=3) else: self.dyncluster_form_class = None self.overrides_form = None self.dyncluster_form = None self.return_redirect = False
def create_team(request, pk): form_set_cls = modelformset_factory(Team, form=CreateTeamForm, extra=2, max_num=2) form_set_cls.form = staticmethod(curry(CreateTeamForm, tour_id=pk)) t = Tournament.objects.get(pk=pk) if t.mode != 1: if request.POST: if request.user.is_superuser: form_set = form_set_cls(request.POST, request.FILES) for form in form_set: if form.is_valid(): new_teams = form_set.save(commit=False) for team in new_teams: team_exist = check_team_exist(team.first_user, team.second_user) if team_exist[0]: team.name = team_exist[1] team.save() t.team_set.add(team) t.save() return HttpResponseRedirect(reverse_lazy('teams:teams')) else: return render(request, 'teams/create_team.html', context={ 'form_set': form_set}) else: form_set = form_set_cls(queryset=Team.objects.none()) return render(request, 'teams/create_team.html', context={ 'form_set': form_set})
def get_context_data(self, **kwargs): context = super(CommitteeCreateView, self).get_context_data(**kwargs) privileged_units = get_privileged_units(self.request.user) unit_choices = [(unit.id, unit) for unit in privileged_units] if self.new_committees: CommitteeFormSet = modelformset_factory(Committee, form=CommitteeCreateForm, widgets={'short_code': TextInput(attrs={'readonly': True}), 'unit': Select(choices=unit_choices) }, extra=len(self.new_committees)) initial_data = [{'short_code': short_code} for short_code in self.new_committees] formset = CommitteeFormSet( initial=initial_data, queryset=Committee.objects.none()) form_count = formset.total_form_count() context['formset'] = formset else: form = CommitteeCreateForm() form_count = 1 context['form'] = form context['form_count'] = form_count # Used to pluralize header. return context
def ta_view(request): reports = SubmitReport.objects.query_pending_reports() reports = reports.filter(courses__in=request.user.staff.courses.all()).distinct() ApproveReportFormSet = modelformset_factory(SubmitReport, form=ReportApproveForm, extra=0) if request.method == 'POST': form = ReportSearchForm(request.POST, user_type=request.user.staff) courses = request.user.staff.courses.all() course_choices = [] for course in courses: course_choices += [[course.pk, course]] form.fields['courses'].choices = course_choices if form.is_valid(): reports = form.filter_queryset(reports) import pickle request.session['search_results'] = pickle.dumps(reports.query) return HttpResponseRedirect('/accounts/ta_search_results/') else: form = ReportSearchForm(request.POST, user_type=request.user.staff) courses = request.user.staff.courses.all() course_choices = [] for course in courses: course_choices += [[course.pk, course]] form.fields['courses'].choices = course_choices report_forms = ApproveReportFormSet(queryset=reports) return render(request, "ta_view.html", {'form': form, 'report_forms': report_forms, })
def add_results(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ResultsForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: form = ResultsForm(request.POST) form.save() return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: ResultsFormSet = modelformset_factory(Results, form=ResultsForm) form = ResultsFormSet(queryset=Results.objects.none()) #form = modelformset_factory(Results, fields=("athlete", "tournament", "category")) #form = modelform_factory(Results, fields=("athlete", "tournament", "category")) #form = ResultsForm() return render(request, 'app/forms/add_results.html', {'form': form})
def update_payment_method(request): user = request.user payment_methods = user.payment_method.all() PaymentMethodFormSet = modelformset_factory(PaymentMethod, form=UpdatePaymentMethodForm, extra=0) formset = PaymentMethodFormSet(queryset=payment_methods) if request.method == "POST": formset = PaymentMethodFormSet(request.POST, queryset=payment_methods) if formset.is_valid(): formset.save() serializer = PaymentMethodSerializer(payment_methods, many=True) data = serializer.data print 'formset is saved' # return Response(data, template_name='accounts/user/dashboard/subscription.html') return HttpResponseRedirect('%s'%(reverse('accounts:payment'))) else: print 'formset is invalid' return HttpResponseRedirect('%s'%(reverse('accounts:payment'))) else: print 'request is not POST' return HttpResponseRedirect('%s'%(reverse('accounts:payment')))
def edit_event(request, event_slug): event = Event.objects.filter(slug__iexact=event_slug).first() if not event: return handler404(request) event_form = EventForm(request.POST or None, prefix='event', instance=event) ContactsFormSet = modelformset_factory(Contact, form=ContactForm, can_delete=True) contacts_formset = ContactsFormSet(request.POST or None, prefix='contacts-form', queryset=event.contacts.all()) if request.POST: if event_form.is_valid() and contacts_formset.is_valid(): try: the_event = event_form.save() contacts = contacts_formset.save(commit=False) for a_contact in contacts: a_contact.event = the_event contacts_formset.save() return HttpResponseRedirect('/event/' + the_event.slug) except Exception: pass messages.error(request, _("There is a problem with your event. Please check the form for errors.")) return render(request, 'event/create.html', update_event_info(event_slug, request, {'form': event_form, 'domain': request.get_host(), 'protocol': request.scheme, 'contacts_formset': contacts_formset}), context_instance=RequestContext(request))
def sentence_review(request): words = Words.objects.filter(jlpt_level = 5, id__lte=400) form_objects = [] for word in words: full_form = type('', (), {})() word_form = WordsForm(instance=word) word_form.id = word.id full_form.word_form = word_form meaningset = inlineformset_factory(Words, WordMeanings, fields=('meaning',), form=MeaningsForm) meaningset = meaningset(instance=word) full_form.meaningset = meaningset sentence_formset = modelformset_factory(Sentence, form=SentenceForm) no_sentence_owner_object = SentenceOwner.objects.get(name=" ") sentence_ids = Sentence.objects.filter(words=word).exclude(sentence_owner=no_sentence_owner_object).values_list('id', flat=True)[:5] sentence_query = Sentence.objects.filter(id__in=sentence_ids) sentence_formset = sentence_formset(queryset=sentence_query) full_form.sentence_formset = sentence_formset form_objects.append(full_form) # sentence_formset = modelformset_factory(Sentence, form=SentenceForm) # return render(request, 'admin_data_collection/word_def_sentence_review.html', {"forms":form_objects, "word_form": word_form, "meanings_form": meaningset, "sentence_formset": sentence_formset} ) return render(request, 'admin_data_collection/word_def_sentence_review.html', {"forms":form_objects})
def form_valid(self, form): formset = modelformset_factory(InvoiceLine, fields=['variant', 'quantity', 'price']) formset = formset(self.request.POST) if formset.is_valid(): # check if at least one line of quantity is filled filled = False for f in formset: if f.cleaned_data['quantity'] > 0: filled = True break if filled: po = get_object_or_404(PurchaseOrder, pk=self.kwargs.get('pk')) form.instance.purchase_order = po invoice = form.save() for f in formset: if f.cleaned_data['quantity'] > 0: f.instance.invoice = invoice f.save() po.update_reconciled() return redirect(po) form.add_error(None, "Please add at least one item.") context = self.get_context_data() context['form'] = form context['formset'] = formset return self.render_to_response(context)
def permisos(request): PermisosFormSet = modelformset_factory(Permisos, form = PermisosForm, max_num=1) if request.method == 'POST': formset = PermisosFormSet(request.POST) if formset.is_valid(): instancies = formset.save(commit=False) for index,instancie in enumerate(instancies): entidades = formset[index].cleaned_data['entidades'].replace('[','').replace(']','').split(',') instancie.entidad = int(entidades[0]) instancie.tipo = int(entidades[1]) try: formset.save() messages.success(request, "Permisos editados correctamente.") return redirect('permisos') except Exception as e: print(e) messages.error(request,"Ha ocurrido un error al actualizar los permisos. Revise que la entidad no está repetida") return redirect('permisos') else: form_errors = formset.errors messages.error(request, "El formulario no es válido.") return render(request, 'entidad_permisos.html',{ 'forms': formset, 'form_errors': form_errors }) else: formset = PermisosFormSet(queryset=Permisos.objects.all()) return render(request, 'entidad_permisos.html',{ 'forms': formset })
from django import forms from django.forms import modelformset_factory from django.conf import settings from .step_period import StepPeriodForm from .step_stream import StepStreamForm from ..models import StepStream, Step class StepForm(forms.ModelForm): name = forms.CharField(required=True) class Meta: model = Step fields = ['name', 'start', 'end'] StepStreamFactory = modelformset_factory(StepStream, form=StepStreamForm, extra=0) StepPeriodStreamFactory = modelformset_factory(StepStream, form=StepPeriodForm, extra=0) class StepImportYml(forms.Form): streams = forms.MultipleChoiceField( required=True, choices=settings.PROJECT_STREAM_CH_TYPE) file = forms.FileField(required=True)
from django import forms from django.forms import modelformset_factory from .models import Hobby class HobbyForms(forms.ModelForm): class Meta: model = Hobby fields = ["name"] name = forms.CharField( label="Hobby Name", widget=forms.TextInput(attrs={"placeholder": "Football"})) HobbyFormSet = modelformset_factory(Hobby, form=HobbyForms, fields=("name", ), extra=1)
"class": "inline", "required": "required" }), ) class Meta: model = Answer fields = ("answer", ) class StudentFeedbackAnswerForm(forms.ModelForm): choices = StudentAnswer.ANSWER_CHOICES answer = forms.ChoiceField( label="", choices=choices, widget=forms.RadioSelect(attrs={ "class": "inline", "required": "required" }), ) class Meta: model = StudentAnswer fields = ("answer", ) AnswerFormSet = modelformset_factory(Answer, form=FeedbackAnswerForm) StudentAnswerFormSet = modelformset_factory(StudentAnswer, form=StudentFeedbackAnswerForm)
for field in self.fields.values(): field.error_message = { 'required': "{fieldname} is required".format(fieldname=field.label), } RewardModelFormset = modelformset_factory( Reward, fields=( 'amount', 'perks', 'quantity', ), extra=1, widgets={ 'perks': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Describe the reward that you\'d like to offer to supporters' }) }) class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User
last_name = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder': 'Last name', 'class': '' })) bio = forms.CharField(widget=forms.Textarea( attrs={ 'placeholder': 'Tell us about yourself...', 'class': '' })) avatar = forms.ImageField(label='Avatar', required=False, widget=forms.FileInput(attrs={'class': ''})) class Meta: model = models.UserProfile fields = ['first_name', 'last_name', 'bio', 'avatar', 'skills'] SkillInlineFormSet = forms.modelformset_factory(models.Skill, form=SkillForm, fields=('name', ), extra=1, min_num=0, max_num=10) UserProjectInlineFormSet = forms.modelformset_factory(models.UserProject, form=UserProjectForm, extra=1, min_num=0, max_num=10)
def ticket_types_worker(request, **kwargs): if 'data' in request.session: taken = request.session.get('taken') data = request.session.get('data') showtime_id = data['showtime_id'] paid = data['paid'] if data.get('paid') else '' confirmed = data['confirmed'] if data.get('confirmed') else '' confirmation_email = data['confirmation_email'] if data.get('confirmation_email') else '' reservation_initial = {'showtime_id': data['showtime_id'], 'confirmed': confirmed, 'paid': paid, 'confirmation_email': confirmation_email} client_initial = {'first_name': data['first_name'], 'last_name': data['last_name'], 'email': data['email'], 'phone_number': data['phone_number']} showtime = models.Showtime.objects.get(showtime_id=showtime_id) r_form = forms.ReservationModelForm(initial=reservation_initial) r_form.fields['showtime_id'].widget = r_form.fields['showtime_id'].hidden_widget() client_form = forms.ClientModelForm(initial=client_initial) client_form.fields['first_name'].widget = client_form.fields['first_name'].hidden_widget() client_form.fields['last_name'].widget = client_form.fields['last_name'].hidden_widget() client_form.fields['email'].widget = client_form.fields['email'].hidden_widget() client_form.fields['phone_number'].widget = client_form.fields['phone_number'].hidden_widget() r_form.fields['confirmed'].widget = r_form.fields['confirmed'].hidden_widget() r_form.fields['paid'].widget = r_form.fields['paid'].hidden_widget() r_form.fields['confirmation_email'].widget = r_form.fields['confirmation_email'].hidden_widget() ticket_formset = modelformset_factory(models.Ticket, fields=('seat_id', 'tickettype_id'), labels={'seat_id': '', 'tickettype_id': 'Typ Biletu'}, extra=len(taken), widgets={'seat_id': django.forms.Select(attrs={'hidden': ''})}, max_num=60) # pracownik moze zarezerwowac cala sale ticket_form = ticket_formset(queryset=models.Ticket.objects.none(), initial=[{'seat_id': z} for z in taken]) seats = [] # pokazuje tylko typy biletów, które nie są usunięte # https://simpleisbetterthancomplex.com/questions/2017/03/22/how-to-dynamically-filter-modelchoices-queryset-in-a-modelform.html for form in ticket_form: form.fields['tickettype_id'].queryset = models.TicketType.objects.filter(deleted=False) seats.append(models.Seat.objects.get(seat_id=form.initial['seat_id'])) if request.POST: r_form = forms.ReservationModelForm(request.POST) client_form = forms.ClientModelForm(request.POST) ticket_form = ticket_formset(request.POST) # pokazuje tylko typy biletów, które nie są usunięte for form in ticket_form: form.fields['tickettype_id'].queryset = models.TicketType.objects.filter(deleted=False) if ticket_form.is_valid() and (client_form.is_valid() and r_form.is_valid()): request.session['formset_data'] = ticket_form.data return redirect('summary-worker') client_form.fields['first_name'].widget = client_form.fields['first_name'].hidden_widget() client_form.fields['last_name'].widget = client_form.fields['last_name'].hidden_widget() client_form.fields['email'].widget = client_form.fields['email'].hidden_widget() client_form.fields['phone_number'].widget = client_form.fields['phone_number'].hidden_widget() r_form.fields['showtime_id'].widget = r_form.fields['showtime_id'].hidden_widget() r_form.fields['confirmed'].widget = r_form.fields['confirmed'].hidden_widget() r_form.fields['paid'].widget = r_form.fields['paid'].hidden_widget() r_form.fields['confirmation_email'].widget = r_form.fields['confirmation_email'].hidden_widget() return render(request, 'worker/rezerwacje/wybierz_typy_biletow.html', context={'taken': taken, 'ticket_form': ticket_form, 'reservation_form': r_form, 'client_form': client_form, 'client_initial': client_initial, 'reservation_initial': reservation_initial, 'showtime': showtime, 'seats': seats}) else: taken = '' ticket_form = '' r_form = '' client_form = '' reservation_initial = '' client_initial = '' showtime = '' seats = '' return render(request, 'worker/rezerwacje/wybierz_typy_biletow.html', context={'taken': taken, 'ticket_form': ticket_form, 'reservation_form': r_form, 'client_form': client_form, 'client_initial': client_initial, 'reservation_initial': reservation_initial, 'showtime': showtime, 'seats': seats})
from django import forms from django.forms import ModelForm, modelformset_factory from .models import Answer class AnswerForm(forms.ModelForm): class Meta: model = Answer fields = ['answer'] labels = { 'answer': 'выберите вариант ответа:', } AnswerFormSet = modelformset_factory(Answer, form=AnswerForm, extra=6)
form.instance.pk for form in self if form.instance.pk and not form.cleaned_data.get('has_custom_translators')) if not without_translators: return ProjectLocale.objects.filter(pk__in=without_translators).update( has_custom_translators=False) User.groups.through.objects.filter( group__projectlocales__pk__in=without_translators).delete() ProjectLocalePermsFormsSet = forms.modelformset_factory( ProjectLocale, ProjectLocalePermsForm, formset=ProjectLocaleFormSet, ) class UserProfileForm(forms.ModelForm): """ Form is responsible for saving user's name. """ first_name = forms.RegexField( label='Name', regex='^[^<>"\'&]+$', max_length=30, strip=True, ) email = forms.EmailField(
def main_page(request): ar = {} if request.method == 'POST': search_form = SearchForm(request.POST) if search_form.is_valid(): ar['search_form'] = search_form experiment_type = search_form.cleaned_data['experiment_type'] exclude = get_exclusions(experiment_type) headings = get_headings(experiment_type, exclude) headings = [h.replace('_', ' ') for h in headings] MetadataEditForm = modelformset_factory( ValidMetadata, formset=BaseMetadataCorrectionFormSet, exclude=exclude, widgets={ 'date': forms.SelectDateWidget( empty_label="Nothing", years=range(2000, datetime.date.today().year + 1)), 'charID': forms.TextInput(attrs={'size': 5}) }) ExperimentTypeEditForm = modelformset_factory( ValidMetadata, formset=BaseExperimentTypeCorrectionFormSet, exclude=get_exclusions() + ["experiment_type", 'date', 'charID'], ) ValidMetadataForm = modelformset_factory( ValidMetadata, exclude=get_exclusions(experiment_type) + ["experiment_type"], widgets={ 'date': forms.SelectDateWidget( empty_label="Nothing", years=range(2000, datetime.date.today().year + 1)), 'charID': forms.TextInput(attrs={'size': 5}) }, extra=1) ar['search_form'] = search_form if 'change_exp_type' in request.POST: valid_metadata_formset = ValidMetadataForm() ar['metadata_edit_formset'] = valid_metadata_formset ar['make_changes'] = 'show_filename' headings = get_headings(experiment_type, get_exclusions(experiment_type), has_file_linked=False) headings = [h.replace('_', ' ') for h in headings] print(headings) ar['headings'] = headings elif 'search_and_fix_metadata' in request.POST: q = Q() if search_form.cleaned_data[ 'show_valid'] and not search_form.cleaned_data[ 'show_invalid']: q = Q(is_valid=True) elif not search_form.cleaned_data[ 'show_valid'] and search_form.cleaned_data[ 'show_invalid']: q = Q(is_valid=False) if search_form.cleaned_data[ 'show_deprecated'] and not search_form.cleaned_data[ 'show_nondeprecated']: q = q & Q(deprecated=True) elif not search_form.cleaned_data[ 'show_deprecated'] and search_form.cleaned_data[ 'show_nondeprecated']: q = q & Q(deprecated=False) if search_form.cleaned_data['filename1_search']: q = q & Q(filename__icontains=search_form. cleaned_data['filename1']) if search_form.cleaned_data['filename2_search']: q = q & Q(filename__icontains=search_form. cleaned_data['filename2']) if search_form.cleaned_data['filename3_search']: q = q & Q(filename__icontains=search_form. cleaned_data['filename3']) if search_form.cleaned_data['root1_search']: q = q & Q( root__icontains=search_form.cleaned_data['root1']) if search_form.cleaned_data['root2_search']: q = q & Q( root__icontains=search_form.cleaned_data['root2']) if search_form.cleaned_data['root3_search']: q = q & Q( root__icontains=search_form.cleaned_data['root3']) if search_form.cleaned_data['show_wrong_experiment_type']: q = q & ~Q(valid_metadata__experiment_type=experiment_type) total_query = DatabaseFile.objects.filter(q) else: q = q & Q(valid_metadata__experiment_type=experiment_type) total_query = DatabaseFile.objects.filter(q) initial = [] pn = search_form.cleaned_data['page_number'] if pn is None: pn = 1 search_form.set_page_number(pn) n = total_query.count() max_page = int(n / 15) if (n % 15) != 0: max_page += 1 if pn > max_page: pn = max_page search_form.set_page_number(pn) if pn < 1: pn = 1 search_form.set_page_number(pn) if search_form.cleaned_data['show_wrong_experiment_type']: for db_filename in total_query[(pn - 1) * 15:min(n, (pn) * 15)]: my_initial = { "filename": db_filename.filename, "filename_id": db_filename.id, "exclude": True, 'deprecate': db_filename.deprecated, "reparse": True, "last_modified": db_filename.last_modified, "filesize": '{}'.format(int(db_filename.filesize / 1024)) } if db_filename.valid_metadata is None: my_initial["old_experiment_type"] = '' else: my_initial[ "old_experiment_type"] = db_filename.valid_metadata.experiment_type.__str__( ) print(my_initial) initial.append(my_initial) ExperimentTypeEditForm = modelformset_factory( ValidMetadata, formset=BaseExperimentTypeCorrectionFormSet, exclude=get_exclusions() + ["experiment_type", 'date', 'charID'], extra=len(initial)) experiment_type_edit_formset = ExperimentTypeEditForm( queryset=DatabaseFile.objects.none(), initial=initial) ar['metadata_edit_formset'] = experiment_type_edit_formset ar['make_changes'] = 'make_changes_to_experiment_type' headings = get_headings( None, get_exclusions() + ['date', 'charID']) headings = [h.replace('_', ' ') for h in headings ] + ['old_experiment_type', 'reparse'] ar['headings'] = headings else: for db_filename in total_query[(pn - 1) * 15:min(n, (pn) * 15)]: my_initial = { "filename": db_filename.filename, "filename_id": db_filename.id, "exclude": True, 'deprecate': db_filename.deprecated, "experiment_type": experiment_type, "charID": db_filename.valid_metadata.charID, "cell_id": db_filename.valid_metadata.cell_id, "start_cycle": db_filename.valid_metadata.start_cycle, "voltage": db_filename.valid_metadata.voltage, "temperature": db_filename.valid_metadata.temperature, "AC": db_filename.valid_metadata.AC, "AC_increment": db_filename.valid_metadata.AC_increment, "version_number": db_filename.valid_metadata.version_number, "date": db_filename.valid_metadata.date, "last_modified": db_filename.last_modified, "filesize": '{}'.format(int(db_filename.filesize / 1024)) } initial.append(my_initial) # Defining it again so that 'extra' works MetadataEditForm = modelformset_factory( ValidMetadata, formset=BaseMetadataCorrectionFormSet, exclude=exclude, extra=len(initial), widgets={ 'date': forms.SelectDateWidget( empty_label="Nothing", years=range(2000, datetime.date.today().year + 1)), 'charID': forms.TextInput(attrs={'size': 5}), 'cell_id': forms.NumberInput(attrs={'style': 'width:8ch'}), 'start_cycle': forms.NumberInput(attrs={'style': 'width:8ch'}), 'temperature': forms.NumberInput(attrs={'style': 'width:8ch'}), 'voltage': forms.NumberInput(attrs={'style': 'width:6ch'}), }) metadata_edit_formset = MetadataEditForm( queryset=DatabaseFile.objects.none(), initial=initial) ar['metadata_edit_formset'] = metadata_edit_formset ar['make_changes'] = 'make_changes_to_metadata' ar['headings'] = headings ar['search_form'] = search_form ar['page_number'] = pn ar['max_page_number'] = max_page elif 'make_changes_to_metadata' in request.POST or 'make_changes_to_experiment_type' in request.POST: if 'make_changes_to_metadata' in request.POST: metadata_edit_formset = MetadataEditForm(request.POST) elif 'make_changes_to_experiment_type' in request.POST: metadata_edit_formset = ExperimentTypeEditForm( request.POST) for form in metadata_edit_formset: validation_step = form.is_valid() if not DatabaseFile.objects.filter( id=form.cleaned_data['filename_id']).exists(): print('invalid id', form.cleaned_data['filename_id']) continue file = DatabaseFile.objects.get( id=form.cleaned_data['filename_id']) to_be_excluded = form.cleaned_data['exclude'] to_be_deprecated = form.cleaned_data['deprecate'] if to_be_excluded: print('exclude') continue if to_be_deprecated: file.deprecated = True file.save() print('deprecated') continue if validation_step: if not to_be_deprecated: file.deprecated = False if 'make_changes_to_metadata' in request.POST: charID = None cell_id = None voltage = None temperature = None AC = None AC_increment = None version_number = None date = None if 'charID' in form.cleaned_data.keys(): charID = form.cleaned_data['charID'] if 'cell_id' in form.cleaned_data.keys(): cell_id = form.cleaned_data['cell_id'] if 'start_cycle' in form.cleaned_data.keys(): start_cycle = form.cleaned_data['start_cycle'] if 'voltage' in form.cleaned_data.keys(): voltage = form.cleaned_data['voltage'] if 'temperature' in form.cleaned_data.keys(): temperature = form.cleaned_data['temperature'] if 'AC' in form.cleaned_data.keys(): AC = form.cleaned_data['AC'] if 'AC_increment' in form.cleaned_data.keys(): AC_increment = form.cleaned_data[ 'AC_increment'] if 'version_number' in form.cleaned_data.keys(): version_number = form.cleaned_data[ 'version_number'] if 'date' in form.cleaned_data.keys(): date = form.cleaned_data['date'] file.set_valid_metadata( experiment_type=experiment_type, charID=charID, cell_id=cell_id, start_cycle=start_cycle, voltage=voltage, temperature=temperature, AC=AC, AC_increment=AC_increment, version_number=version_number, date=date) file.save() elif 'make_changes_to_experiment_type' in request.POST: to_be_reparsed = form.cleaned_data['reparse'] to_be_reparsed = to_be_reparsed or file.valid_metadata is None if not to_be_reparsed: file.set_valid_metadata( experiment_type=experiment_type) file.save() else: meta, valid = deterministic_parser( file.filename, experiment_type) file.set_valid_metadata(valid_metadata=meta) file.save() elif 'show_filename' in request.POST: metadata_edit_formset = ValidMetadataForm(request.POST) filenames = [] for form in metadata_edit_formset: if form.is_valid(): charID = None cell_id = None voltage = None temperature = None AC = None AC_increment = None version_number = None date = None if 'charID' in form.cleaned_data.keys(): charID = form.cleaned_data['charID'] if 'cell_id' in form.cleaned_data.keys(): cell_id = form.cleaned_data['cell_id'] if 'start_cycle' in form.cleaned_data.keys(): start_cycle = form.cleaned_data['start_cycle'] if 'voltage' in form.cleaned_data.keys(): voltage = form.cleaned_data['voltage'] if 'temperature' in form.cleaned_data.keys(): temperature = form.cleaned_data['temperature'] if 'AC' in form.cleaned_data.keys(): AC = form.cleaned_data['AC'] if 'AC_increment' in form.cleaned_data.keys(): AC_increment = form.cleaned_data['AC_increment'] if 'version_number' in form.cleaned_data.keys(): version_number = form.cleaned_data[ 'version_number'] if 'date' in form.cleaned_data.keys(): date = form.cleaned_data['date'] filenames.append( ValidMetadata(experiment_type=experiment_type, charID=charID, cell_id=cell_id, start_cycle=start_cycle, voltage=voltage, temperature=temperature, AC=AC, AC_increment=AC_increment, version_number=version_number, date=date).get_filename) if len(filenames) != 0: ar['filename_to_show'] = filenames ar['search_form'] = search_form else: ar['search_form'] = SearchForm() return render(request, 'filename_database/form_interface.html', ar)
def student_attendance_manager(request): """ this function is responsible for querying the attendance parameters and present the student multiple attendance form """ if request.method == "POST": # get the class name , the attendance date and present the attendance form class_name = get_object_or_404( ClassRoom, pk=request.POST['class_name']) # class name attendance_date = request.POST['date_field'] # date # get the students in the class which is current active students = StudentClass.objects.filter(classroom=class_name) # modelform creation # noinspection PyPep8Naming AttendanceFormset = modelformset_factory(StudentAttendance, form=StudentsAttendanceForm, extra=students.count()) msg = "" # initiate the form and pass in the required parameters ie: classroom_id, attendance_date initial = [] enroll_notes = [] for student in students: student.marked = False initial.append({ 'student': student.id, 'status': None, 'notes': None, 'attendance_date': attendance_date }) enroll_notes.append("") formset = AttendanceFormset(initial=initial, queryset=StudentAttendance.objects.none()) # add notes to each form i = 0 form_students = students for form in formset.forms: form.enroll_note = enroll_notes[i] form.student_display = form_students[i] i += 1 # add form to each student, so we can use for student in students in the template i = 0 forms = formset.forms for student in students: if not student.marked: student.form = forms[i] i += 1 template = 'attendance/students_attendance_form.html' context = { 'class_name': class_name, 'msg': msg, 'formset': formset, 'students': students, } return JsonResponse({ 'html_form': render_to_string(template, context, request=request) }) else: # send in the selection form template = 'attendance/students_attendance_manager.html' class_date_selector_form = ClassroomDateQueryForm(request.GET or None) context = {'choice_form': class_date_selector_form} return render(request, template, context)
def teacher_attendance(request, course=None): """ Take attendance. show course selection if there is more than one course """ today = datetime.date.today() students = StudentClass.objects.filter(main_class=1) readonly = False msg = "" AttendanceFormset = modelformset_factory(StudentAttendance, form=StudentAttendanceForm, extra=students.count()) if request.method == 'POST': formset = AttendanceFormset(request.POST) if formset.is_valid(): for form in formset.forms: object = form.save() # don't log first messages.success(request, 'Attendance recorded') return HttpResponse('saved') else: msg = "\nDuplicate entry detected! It's possible someone else is entering " \ "attendance for these students at the same time. Please confirm attendance." \ " If problems persist contact an administrator." return HttpResponse(formset.errors) initial = [] enroll_notes = [] for student in students: student.marked = False initial.append({ 'student': student.id, 'status': None, 'notes': None, 'attendance_date': datetime.date.today() }) #note = student.courseenrollment_set.filter(course=course)[0].attendance_note enroll_notes.append("") formset = AttendanceFormset(initial=initial, queryset=StudentAttendance.objects.none()) # add notes to each form i = 0 form_students = students for form in formset.forms: form.enroll_note = enroll_notes[i] form.student_display = form_students[i] i += 1 # add form to each student, so we can use for student in students in the template i = 0 forms = formset.forms for student in students: if not student.marked: student.form = forms[i] i += 1 return render( request, 'attendance/test.html', { 'request': request, #'readonly': readonly, 'msg': msg, 'formset': formset, 'students': students, })
class Meta: model = ChallengeFile fields = ['currently', 'file', 'note'] def __init__(self, *args, **kwargs): super(ChallengeFileForm, self).__init__(*args, **kwargs) if self.instance.id: self.fields['currently'].widget = forms.TextInput( attrs={ 'readonly': True, 'value': self.instance.file.name }) self.fields['file'].disabled = True self.fields['note'].widget.attrs['readonly'] = True FilesFormsetEmpty = modelformset_factory(ChallengeFile, form=ChallengeFileForm, extra=0) FilesFormset = modelformset_factory(ChallengeFile, form=ChallengeFileForm, extra=1) CurrentFilesFormset = inlineformset_factory(Challenge, ChallengeFile, formset=CurrentFilesFormSet, form=ChallengeFileForm, extra=0, can_delete=True)
from django.forms import ModelForm, TextInput, Form, modelformset_factory, formset_factory from .models import Survey, Question class SurveyForm(ModelForm): class Meta: model = Survey fields = ['title', 'description'] class QuestionForm(ModelForm): class Meta: model = Question fields = ['question_text'] QuestionFormSet = formset_factory(QuestionForm, extra=1) QuestionModelFormSet = modelformset_factory(Question, fields=('question_text',))
def reservation_update(request, **kwargs): reservation_id = kwargs['reservation_id'] reservation = models.Reservation.objects.get(reservation_id=reservation_id) # bilety przekazywane jako initial do formset factory tickets_initial = reservation.ticket_id.values('seat_id', 'tickettype_id') showtime_id = reservation.showtime_id.showtime_id reservation_initial = {'showtime_id': reservation.showtime_id.showtime_id, 'confirmed': reservation.confirmed, 'paid': reservation.paid} r_form = forms.ReservationModelForm(initial=reservation_initial) client_initial = {'first_name': reservation.client_id.first_name, 'last_name': reservation.client_id.last_name, 'email': reservation.client_id.email, 'phone_number': reservation.client_id.phone_number} client_form = forms.ClientModelForm(initial=client_initial) ticket_formset = modelformset_factory(models.Ticket, fields=('seat_id', 'tickettype_id'), labels={'seat_id': 'Miejsce', 'tickettype_id': 'Typ Biletu', }, extra=len(reservation.ticket_id.values()), max_num=10) ticket_form = ticket_formset(queryset=models.Ticket.objects.none(), initial=tickets_initial) taken_seats = models.Ticket.objects.filter(showtime_id=showtime_id).values('seat_id') free_seats = models.Seat.objects.exclude(seat_id__in=taken_seats) # pokazuje tylko typy biletów, które nie są usunięte, oraz wolne miejsca for form in ticket_form: form.fields['tickettype_id'].queryset = models.TicketType.objects.filter(deleted=False) form.fields['seat_id'].queryset = free_seats if request.POST: if 'ticket_num' in request.POST: ticket_formset = modelformset_factory(models.Ticket, fields=('seat_id', 'tickettype_id'), labels={'seat_id': 'Miejsce', 'tickettype_id': 'Typ Biletu', }, extra=int(request.POST['ticket_select']), max_num=60) ticket_form = ticket_formset(queryset=models.Ticket.objects.none(), initial=tickets_initial) # pokazuje tylko typy biletów, które nie są usunięte, oraz wolne miejsca for form in ticket_form: form.fields['tickettype_id'].queryset = models.TicketType.objects.filter(deleted=False) form.fields['seat_id'].queryset = free_seats else: # current objects reservation_object = get_object_or_404(models.Reservation, reservation_id=reservation_id) client_object = get_object_or_404(models.Client, client_id=reservation.client_id.client_id) r_form = forms.ReservationModelForm(request.POST, instance=reservation_object) r_form.fields['showtime_id'].widget = r_form.fields['showtime_id'].hidden_widget() ticket_form = ticket_formset(request.POST) client_form = forms.ClientModelForm(request.POST, instance=client_object) # pokazuje tylko typy biletów, które nie są usunięte, oraz wolne miejsca for form in ticket_form: form.fields['tickettype_id'].queryset = models.TicketType.objects.filter(deleted=False) form.fields['seat_id'].queryset = free_seats if ticket_form.is_valid() and (client_form.is_valid() and r_form.is_valid()): showtime = models.Showtime.objects.get(showtime_id=showtime_id) # obiekt seansu client = client_form.save() reservation = r_form.save(commit=False) reservation.client_id = client # https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/#many-to-many-relationships instances = ticket_form.save(commit=False) # get total price # zapisuje cene biletu, aby w przy zmiane cennika ceny juz zakupionych biletow pozostaly takie same total_price = 0 for instance in instances: price = models.TicketType.objects.get(ticket_id=instance.tickettype_id_id).price total_price += price instance.price = price reservation.cost = total_price reservation.save() tickets = models.Ticket.objects.filter(reservation__reservation_id=reservation_id) # usuwa wszytkie bilety powiązane z rezerwacją, oraz rezerwację for t in tickets.iterator(): t.delete() taken_seats = models.Ticket.objects.filter(showtime_id=showtime_id).values_list('seat_id', flat=True) for instance in instances: if instance.seat_id.seat_id not in taken_seats: instance.client_id = client instance.showtime_id = showtime instance.save() reservation.ticket_id.add(instance) else: try: raise ValueError('seats taken') except Exception: messages.add_message(request, messages.ERROR, 'Wybrane miejsca zostały zarezerwowane przez ' 'innego klienta. Spróbuj ponownie. Miejsce ' + str(instance.seat_id.seat_number) + ' Rząd: ' + str(instance.seat_id.row_number)) return redirect( reverse('movie-details-client', kwargs={'pk': str(showtime.movie_id.movie_id)})) r_form.save_m2m() # https://simpleisbetterthancomplex.com/tutorial/2016/06/13/how-to-send-email.html # https://stackoverflow.com/questions/29466796/sending-a-html-email-in-django if reservation.confirmation_email and not reservation.confirmed: html_mail = loader.render_to_string(template_name='client/rezerwacja/email.html', context={'first_name': client.first_name, 'last_name': client.last_name, 'reservation': reservation, 'domain': request.META['HTTP_HOST']}) mail = send_mail(subject='Potwierdzenie rezerwacji na seans ' + showtime.movie_id.title, message='', from_email=EMAIL_HOST_USER, recipient_list=[client.email, ], fail_silently=True, html_message=html_mail) if mail: messages.add_message(request, messages.SUCCESS, 'Rezerwacja została pomyślnie zaktualizowana, na adres' 'mailowy klienta została wysłana wiadomość z potwierdzeniem.' 'Jeśli klient nie potwierdzi rezerwacji w ciągu 30 minut, ' 'to zostanie ona usunięta z systemu') else: messages.add_message(request, messages.ERROR, 'Wystąpił problem z wysłaniem wiadomości. Skontaktuj się z klientem w celu ' 'potwierdzenia lub odrzucenia rezerwacji.') else: messages.add_message(request, messages.SUCCESS, 'Rezerwacja została pomyślnie zaktualizowana.\n ' 'Nie została zaznaczona opcja wysyłki wiadomości email do klienta.') return redirect(reverse('showtime-details-worker', kwargs={'pk': str(showtime.showtime_id)})) return render(request, 'worker/rezerwacje/edytuj-rezerwacje.html', context={'reservation': reservation, 'r_form': r_form, 'client_form': client_form, 'ticket_form': ticket_form, 'ticket_number': [x for x in range(1, 61)], })
'onChange'] = 'actualitza_grups()' else: self.fields['gols1'].widget.attrs[ 'onChange'] = 'actualitza_eliminatoria()' self.fields['gols2'].widget.attrs[ 'onChange'] = 'actualitza_eliminatoria()' self.fields['empat'].widget.attrs[ 'onChange'] = 'actualitza_eliminatoria()' class Meta: model = PronosticPartit fields = ('gols1', 'gols2', 'empat') GrupForm = forms.modelformset_factory(PronosticPartit, form=PartitForm, extra=0) @login_required def pronostic(request): jugador = Jugador.objects.get(usuari=request.user) nom_grup = request.GET.get('grup', 'A') # Si és un POST, guardem els valors del formulari if request.method == 'POST': grup_form = GrupForm(request.POST) if grup_form.is_valid(): grup_form.save()
user_model=self.USER_MODEL) unit_qs = EntityUnitModel.objects.for_entity( entity_slug=self.ENTITY_SLUG, user_model=self.USER_MODEL) for form in self.forms: form.fields['item_model'].queryset = items_qs form.fields['entity_unit'].queryset = unit_qs if not self.CUSTOMER_JOB_MODEL.can_update_items(): form.fields['item_model'].disabled = True form.fields['quantity'].disabled = True form.fields['unit_cost'].disabled = True form.fields['entity_unit'].disabled = True # todo: add instance where can_delete = False CustomerEstimateItemFormset = modelformset_factory( model=ItemThroughModel, form=CustomerEstimateItemForm, formset=BaseCustomerEstimateItemFormset, can_delete=True, extra=5) CustomerEstimateItemFormsetReadOnly = modelformset_factory( model=ItemThroughModel, form=CustomerEstimateItemForm, formset=BaseCustomerEstimateItemFormset, can_delete=False, extra=0)
class Meta: model = models.NPC fields = [ 'name', ] class SRDMonsterForm(forms.ModelForm): class Meta: model = models.Monster fields = ['name'] class SRDNPCForm(forms.ModelForm): class Meta: model = models.NPC fields = ['name'] MonsterFormSet = forms.modelformset_factory( models.Monster, form=MonsterForm, extra=0, ) NPCFormSet = forms.modelformset_factory( models.NPC, form=NPCForm, extra=0, )
def summary(request, **kwargs): if 'formset_data' in request.session: formset_data = request.session['formset_data'] # wyliczanie koncowej ceny do wyswietlenia userowi total_price = 0 for k, v in formset_data.items(): if k.endswith('tickettype_id'): total_price += models.TicketType.objects.get(ticket_id=v).price taken = request.session.get('taken') data = request.session.get('data') showtime_id = data['showtime_id'] # paid = data['paid'] if data.get('paid') else '' # confirmed = data['confirmed'] if data.get('confirmed') else '' # confirmation_email = data['confirmation_email'] if data.get('confirmation_email') else '' reservation_initial = {'showtime_id': data['showtime_id'], 'confirmed': False, 'paid': False, 'confirmation_email': False} client_initial = {'first_name': data['first_name'], 'last_name': data['last_name'], 'email': data['email'], 'phone_number': data['phone_number']} showtime = models.Showtime.objects.get(showtime_id=showtime_id) r_form = forms.ReservationModelForm(initial=reservation_initial) r_form.fields['showtime_id'].widget = r_form.fields['showtime_id'].hidden_widget() client_form = forms.ClientModelForm(initial=client_initial) client_form.fields['first_name'].widget = client_form.fields['first_name'].hidden_widget() client_form.fields['last_name'].widget = client_form.fields['last_name'].hidden_widget() client_form.fields['email'].widget = client_form.fields['email'].hidden_widget() client_form.fields['phone_number'].widget = client_form.fields['phone_number'].hidden_widget() # r_form.fields['confirmed'].widget = r_form.fields['confirmed'].hidden_widget() # r_form.fields['paid'].widget = r_form.fields['paid'].hidden_widget() # r_form.fields['confirmation_email'].widget = r_form.fields['confirmation_email'].hidden_widget() ticket_formset = modelformset_factory(models.Ticket, fields=('seat_id', 'tickettype_id'), labels={'seat_id': '', 'tickettype_id': ''}, extra=len(taken), widgets={'seat_id': django.forms.Select(attrs={'hidden': '', }), 'tickettype_id': django.forms.Select(attrs={'hidden': '', })}, max_num=60) # pracownik moze zarezerwowac cala sale ticket_form = ticket_formset(queryset=models.Ticket.objects.none(), data=formset_data) db_ticket_types = models.TicketType.objects.all() seats = [] for form in ticket_form: seats.append(models.Seat.objects.get(seat_id=form['seat_id'].value())) if request.POST: r_form = forms.ReservationModelForm(request.POST) client_form = forms.ClientModelForm(request.POST) ticket_form = ticket_formset(request.POST) if ticket_form.is_valid() and (client_form.is_valid() and r_form.is_valid()): showtime = models.Showtime.objects.get(showtime_id=showtime_id) # obiekt seansu client = client_form.save() reservation = r_form.save(commit=False) reservation.client_id = client # https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/#many-to-many-relationships instances = ticket_form.save(commit=False) # get total price # zapisuje cene biletu, aby w przy zmiane cennika ceny juz zakupionych biletow pozostaly takie same total_price = 0 for instance in instances: price = models.TicketType.objects.get(ticket_id=instance.tickettype_id_id).price total_price += price instance.price = price reservation.cost = total_price reservation.save() taken_seats = models.Ticket.objects.filter(showtime_id=showtime_id).values_list('seat_id', flat=True) for instance in instances: if instance.seat_id.seat_id not in taken_seats: instance.client_id = client instance.showtime_id = showtime instance.save() reservation.ticket_id.add(instance) else: try: raise ValueError('seats taken') except Exception: messages.add_message(request, messages.ERROR, 'Wybrane miejsca zostały zarezerwowane przez ' 'innego klienta. Spróbuj ponownie. Miejsce ' + str(instance.seat_id.seat_number) + ' Rząd: ' + str(instance.seat_id.row_number)) return redirect( reverse('movie-details-client', kwargs={'pk': str(showtime.movie_id.movie_id)})) finally: request.session.pop('taken') request.session.pop('data') request.session.pop('formset_data') r_form.save_m2m() # https://simpleisbetterthancomplex.com/tutorial/2016/06/13/how-to-send-email.html # https://stackoverflow.com/questions/29466796/sending-a-html-email-in-django if reservation.confirmation_email and not reservation.confirmed: html_mail = loader.render_to_string(template_name='client/rezerwacja/email.html', context={'first_name': client.first_name, 'last_name': client.last_name, 'reservation': reservation, 'domain': request.META['HTTP_HOST']}) mail = send_mail(subject='Potwierdzenie rezerwacji na seans ' + showtime.movie_id.title, message='', from_email=EMAIL_HOST_USER, recipient_list=[client.email, ], fail_silently=True, html_message=html_mail) if mail: messages.add_message(request, messages.SUCCESS, 'Rezerwacja została pomyślnie utworzona, na adres ' 'mailowy klienta została wysłana wiadomość z potwierdzeniem. ' 'Jeśli klient nie potwierdzi rezerwacji w ciągu 30 minut, ' 'to zostanie ona usunięta z systemu') else: messages.add_message(request, messages.ERROR, 'Wystąpił problem z wysłaniem wiadomości. Skontaktuj się z klientem w celu ' 'potwierdzenia lub odrzucenia rezerwacji.') else: messages.add_message(request, messages.SUCCESS, 'Rezerwacja została pomyślnie utworzona.\n ' 'Nie została zaznaczona opcja wysyłki wiadomości email do klienta.') request.session.pop('taken') request.session.pop('data') request.session.pop('formset_data') return redirect(reverse('showtime-details-worker', kwargs={'pk': showtime_id})) return render(request, 'worker/rezerwacje/podsumowanie.html', context={'taken': taken, 'ticket_form': ticket_form, 'reservation_form': r_form, 'client_form': client_form, 'client_initial': client_initial, 'reservation_initial': reservation_initial, 'showtime': showtime, 'total': total_price, 'db_ticket_types': db_ticket_types, 'seats': seats}) else: taken = '' ticket_form = '' r_form = '' client_form = '' reservation_initial = '' client_initial = '' showtime = '' total_price = '' seats = '' return render(request, 'worker/rezerwacje/podsumowanie.html', context={'taken': taken, 'ticket_form': ticket_form, 'reservation_form': r_form, 'client_form': client_form, 'client_initial': client_initial, 'reservation_initial': reservation_initial, 'showtime': showtime, 'total': total_price, 'seats': seats})
class OrganizationRequestDetail(LoginRequiredMixin, TitleMixin, DetailView): model = OrganizationRequest template_name = 'organization/requests/detail.html' title = gettext_lazy('Join request detail') pk_url_kwarg = 'rpk' def get_object(self, queryset=None): object = super(OrganizationRequestDetail, self).get_object(queryset) profile = self.request.profile if object.user_id != profile.id and not object.organization.admins.filter(id=profile.id).exists(): raise PermissionDenied() return object OrganizationRequestFormSet = modelformset_factory(OrganizationRequest, extra=0, fields=('state',), can_delete=True) class OrganizationRequestBaseView(TitleMixin, LoginRequiredMixin, SingleObjectTemplateResponseMixin, SingleObjectMixin, View): model = Organization slug_field = 'key' slug_url_kwarg = 'key' tab = None def get_object(self, queryset=None): organization = super(OrganizationRequestBaseView, self).get_object(queryset) if not (organization.admins.filter(id=self.request.profile.id).exists() or organization.registrant_id == self.request.profile.id): raise PermissionDenied() return organization
from django.forms import modelformset_factory, BaseModelFormSet from .models import Image class BaseMultiImageFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = Image.objects.none() MultiImageForm = modelformset_factory(Image, fields=('file',), formset=BaseMultiImageFormSet)
class ProposalForm5(forms.Form): title = "Invite Team Members" member = modelformset_factory(Member,extra=1, exclude=('proposal',)) members = member(queryset=Member.objects.order_by('camipro'))
class ProposalForm6(forms.Form): title = "Define the Delivrables" mem = modelformset_factory(MembersPosition,extra=1, exclude=('proposal',)) members = mem(queryset=MembersPosition.objects.order_by('camipro'))
def VDNA_views(context, request): '''### VDNA CONTROL PANEL ##################################################''' ### Paramter Forms ############################################################ vdnaParameterFormSet = modelformset_factory(VDNA, exclude=['Geometry']) if (request.method == 'POST' and 'parameter_form' in request.POST): formset = vdnaParameterFormSet(request.POST, queryset=VDNA.objects.all()) if (formset.is_valid()): instances = formset.save(commit=False) for instance in instances: instance.save() VDNA.objects.validate() else: formset = vdnaParameterFormSet(queryset=VDNA.objects.none()) ### Preset Buttons ############################################################ if (request.method == 'POST' and 'Reset_All' in request.POST): VDNA.objects.Default() if (request.method == 'POST' and 'Straight' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Straight" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Bend(Roll)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Bend(Roll)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Bend(Tilt)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Bend(Tilt)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Tilt-a-gon' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Tilt-a-gon" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Roll-a-gon' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Roll-a-gon" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'RollTilt-a-gon' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "RollTilt-a-gon" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Shear(Shift)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Shear(Shift)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Shear(Slide)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Shear(Slide)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Twist(DNA)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Twist(DNA)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Untwisted DNA' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Untwisted DNA" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Circle(Roll)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Circle(Roll)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Circle(Tilt)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Circle(Tilt)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Circular DNA' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Circular DNA" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Torsion Helix(+)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Torsion Helix(+)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Torsion Helix(-)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Torsion Helix(-)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Shear Helix(+)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Shear Helix(+)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Shear Helix(-)' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Shear Helix(-)" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Thermal' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Thermal" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Trajectory' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Trajectory" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Chromatin1' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Chromatin1" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Chromatin2' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Chromatin2" update.save() VDNA.objects.setVars() if (request.method == 'POST' and 'Default' in request.POST): key = VDNA.objects.last().Save_Key update = VDNA.objects.get(pk=key) update.Geometry = "Default" update.save() VDNA.objects.setVars() ### Error Messages ############################################################ '''SaveKey, Geometry = VDNA.objects.last().Save_Key, VDNA.objects.last().Geometry Tilt, Roll, Twist = VDNA.objects.last().TiltStrng, VDNA.objects.last().RollStrng, VDNA.objects.last().TwistStrng Shift, Slide, Rise = VDNA.objects.last().ShiftStrng, VDNA.objects.last().SlideStrng, VDNA.objects.last().RiseStrng MaxS, Lk, Nuc = VDNA.objects.last().sMax, VDNA.objects.last().Lk, VDNA.objects.last().Nuc V1, V2, Cores = VDNA.objects.last().V1Strng, VDNA.objects.last().V2Strng, VDNA.objects.last().IsNucStrng''' SaveKey = VDNA.objects.last().Save_Key Tilt = VDNA.objects.last().TiltStrng Roll = VDNA.objects.last().RollStrng Twist = VDNA.objects.last().TwistStrng Shift = VDNA.objects.last().ShiftStrng Slide = VDNA.objects.last().SlideStrng Rise = VDNA.objects.last().RiseStrng MaxS = VDNA.objects.last().sMax Lk = VDNA.objects.last().Lk Nuc = VDNA.objects.last().Nuc V1 = VDNA.objects.last().V1Strng V2 = VDNA.objects.last().V2Strng Cores = VDNA.objects.last().IsNucStrng Geometry = VDNA.objects.last().Geometry Tilt_E, Roll_E, Twist_E, Shift_E, Slide_E, Rise_E, MaxS_E, Lk_E, Nuc_E, V1Strng_E, V2Strng_E, Cores_E = "", "", "", "", "", "", "", "", "", "", "", "" if (Tilt == "" or Roll == "" or Twist == "" or Shift == "" or Slide == "" or Rise == "" or MaxS == "" or Lk == "" or Nuc == "" or V1 == "" or V2 == "" or Cores == ""): Errors = "Invalid Characters in Submission: " if (Tilt != "" and Roll != "" and Twist != "" and Shift != "" != Slide != "" != Rise != "" and MaxS != "" and Lk != "" and Nuc != "" and V1 != "" and V2 != ""): Errors = "Invalid Characters in Submission: NONE" if (Tilt == ""): Tilt_E = "Tilt," if (Roll == ""): Roll_E = "Roll," if (Twist == ""): Twist_E = "Twist," if (Shift == ""): Shift_E = "Shift," if (Slide == ""): Slide_E = "Slide," if (Rise == ""): Rise_E = "Rise," if (MaxS == ""): MaxS_E = "Max S," if (Lk == ""): Lk_E = "Lk," if (Nuc == ""): Nuc_E = "Nuc," if (V1 == ""): V1Strng_E = "V1," if (V2 == ""): V2Strng_E = "V2," if (Cores == ""): Cores_E = "Cores," context['Errors'], context['Tilt_E'], context['Roll_E'], context[ 'Twist_E'], context[ 'Shift_E'] = Errors, Tilt_E, Roll_E, Twist_E, Shift_E context['Slide_E'], context['Rise_E'], context['MaxS_E'], context[ 'Lk_E'] = Slide_E, Rise_E, MaxS_E, Lk_E context['Nuc_E'], context['V1Strng_E'], context['V2Strng_E'], context[ 'Cores_E'] = Nuc_E, V1Strng_E, V2Strng_E, Cores_E C = 5 ### Develepoment Tools ######################################################## context[ 'Tilt'] = Tilt ######################################################## context[ 'Roll'] = Roll ######################################################## context[ 'Twist'] = Twist ###################################################### context[ 'Shift'] = Shift ###################################################### context[ 'Slide'] = Slide ###################################################### context[ 'Rise'] = Rise ######################################################## context[ 'MaxS'] = MaxS ######################################################## context[ 'Lk'] = Lk ############################################################ context[ 'Nuc'] = Nuc ########################################################## context[ 'V1'] = V1 ############################################################ context[ 'V2'] = V2 ############################################################ context[ 'Cores'] = Cores ###################################################### context[ 'Geometry'] = Geometry ################################################ context[ 'SaveKey'] = SaveKey ################################################## context[ 'formset'] = formset ##################################################
class ProposalForm2(forms.Form): title = "Time line of the project and related projects" start_date = forms.DateField(label="Project Start Date", widget = DateTimeInput) end_date = forms.DateField(label="Project End Date", widget = DateTimeInput) past_projects = modelformset_factory(PastProject,extra=1, exclude=('proposal',)) past = past_projects(queryset=PastProject.objects.order_by('project_title'))
def aprobar_requisiciones_empleado(request, id_requisicion): """ Vista que usa el usuario empleado digitador de la requisicion para poder aprobar los items individualmente de la requisición que ha solicitado, una vez estos hayan sido aprobados """ requisicion = get_object_or_404(Requisicion, pk=id_requisicion) # HACER MODIFICACION PORQUE SI PUEDE ENTRAR CON LA CONDICION DE QUE TENGA ALGO EN CREDITO try: empleado = request.user.empleado if empleado != requisicion.empleado: raise Http404 _accepted = [Requisicion.DATA_SET['solicitante'], Requisicion.DATA_SET['pago']] if requisicion.get_rastreo() not in _accepted: raise Http404 elif requisicion.get_rastreo() == _accepted[1]: if not requisicion.detallerequisicion_set.filter(forma_pago=DetalleRequisicion.CREDITO): raise Http404 except: raise Http404 data = {} # Se crea el formset para los detalles de la requisicion DetalleRequisicionFormSet = modelformset_factory( DetalleRequisicion, form=FormularioCumplirDetalleRequisicion, min_num=requisicion.detallerequisicion_set.count(), extra=0, validate_min=True, can_delete=False ) if request.method == 'POST': if requisicion.get_rastreo() == Requisicion.DATA_SET['solicitante']: queryset = requisicion.detallerequisicion_set.all() else: queryset = requisicion.detallerequisicion_set.filter(forma_pago=DetalleRequisicion.CREDITO) form = DetalleRequisicionFormSet(data=request.POST, prefix='detallerequisicion_set', queryset=queryset) if form.is_valid(): form.save() if not requisicion.detallerequisicion_set.filter(cumplida=False): historial = requisicion.crear_historial(estado=Historial.APROBADA, empleado=empleado) historial.save() requisicion.estado = Requisicion.TERMINADA requisicion.fecha_termina = timezone.now().date() requisicion.save() messages.success( request, _('Ha culminado el proceso de la requisición NO.{} exitosamente'.format(requisicion.id)) ) return redirect(reverse('compras:ver_requisiciones_empleado')) messages.success(request, _('Se ha editado correctamente el estado de la requisición')) return redirect(reverse('compras:aprobar_requisiciones_empleado', args=(requisicion.id, ))) else: messages.error(request, _('Ha ocurrido un error al enviar el formulario')) else: if requisicion.get_rastreo() == Requisicion.DATA_SET['solicitante']: queryset = requisicion.detallerequisicion_set.all() else: queryset = requisicion.detallerequisicion_set.filter(forma_pago=DetalleRequisicion.CREDITO) form = DetalleRequisicionFormSet(prefix='detallerequisicion_set', queryset=queryset) data['formset_detalles'] = form data['requisicion'] = requisicion return render(request, 'compras/aprobar_requisiciones_empleado.html', data)
'placeholder': 'Position Title', 'class': '' })) description = forms.CharField(widget=forms.Textarea( attrs={ 'placeholder': 'Position description...', 'class': '' })) skills = forms.ModelMultipleChoiceField( queryset=models.Skill.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False, help_text='Select one or more skill') class Meta: model = models.Position fields = ('name', 'description', 'skills') PositionFormSet = forms.modelform_factory(models.Position, form=PositionCreateForm) PositionInlineFormSet = forms.modelformset_factory( models.Position, form=PositionCreateForm, fields=('name', 'description', 'skills'), extra=5, )
def editar_requisicion(request, id_requisicion): """ Vista para la edicion de requisiciones, siempre y cuando esta se encuentre en estado PENDIENTE, es decir, nadie puede editar una requisicion, solo el que la crea y solo mientras mas nadie haya hecho algo con esa misma requisicion, al momento de apsar a otra area deja de ser editable """ try: # se obtiene la requisicion requisicion = Requisicion.objects.get(id=id_requisicion) if requisicion.estado != Requisicion.PENDIENTE: raise Http404 except Requisicion.DoesNotExist: raise Http404 # si el empleado no tiene los permisos se redirecciona a la pagina de sin permisos # si el empleado no fue quien realizó la requisicion empleado = requisicion.empleado try: if empleado != request.user.empleado: return redirect('sin_permiso') except Empleado.DoesNotExist: raise Http404 # se crean los modelos de los formularios DetalleRequisicionFormSet = modelformset_factory( DetalleRequisicion, form=FormularioDetalleRequisicion, min_num=1, extra=0, validate_min=True, can_delete=True ) AdjuntoFormset = modelformset_factory( Adjunto, form=FormularioAdjunto, min_num=0, extra=1, validate_min=False, can_delete=True ) if request.method == 'POST': # se instancian los formularios de el POST form = FormularioSolicitudRequisicion(data=request.POST, instance=requisicion) # se les pone un prefijo a los formularios para que todo pueda trabajar bien formset_detalles = DetalleRequisicionFormSet( prefix='detallerequisicion_set', queryset=requisicion.detallerequisicion_set.all() ) formset_adjunto = AdjuntoFormset( prefix='adjunto_set', queryset=requisicion.adjunto_set.all() ) if form.is_valid(): # si el formulario es valido se vuelven a instanciar los formularios [FORMSETS] formset_detalles = DetalleRequisicionFormSet( data=request.POST, prefix='detallerequisicion_set', queryset=requisicion.detallerequisicion_set.all() ) formset_adjunto = AdjuntoFormset( data=request.POST, files=request.FILES, prefix='adjunto_set', queryset=requisicion.adjunto_set.all() ) if formset_adjunto.is_valid() and formset_detalles.is_valid(): # si todo está válido url = """ <a class='alert-link' href='%s'>Ver Mis Requisiciones</a> """ % reverse_lazy('compras:ver_requisiciones_empleado') requisicion = form.save() # se guarda la requisicion y sus campos relacionados for form_adjunto in formset_adjunto: if form_adjunto.cleaned_data.get('DELETE', False) and hasattr(form_adjunto.instance, 'pk'): if form_adjunto.instance.id is not None or form_adjunto.instance.pk is not None: form_adjunto.instance.delete() continue form_adjunto.instance.requisicion = requisicion if not form_adjunto.cleaned_data.get('archivo', False): continue form_adjunto.save() for form_detalle in formset_detalles: if form_detalle.cleaned_data.get('DELETE', False) and hasattr(form_detalle.instance, 'pk'): if form_detalle.instance.id is not None or form_detalle.instance.pk is not None: form_detalle.instance.delete() continue form_detalle.instance.requisicion = requisicion if not form_detalle.cleaned_data.get('descripcion', False): continue form_detalle.save() # formset_detalles.save() # formset_adjunto.save() messages.success(request, _("Se ha editado la requisicion con éxito " + url)) return redirect(reverse('compras:editar_requisicion', args=(id_requisicion, ))) else: messages.error(request, _("Ha ocurrido un error al enviar el formulario")) else: messages.error(request, _("Ha ocurrido un error al enviar el formulario")) else: # se instancian los formularios para el GET form = FormularioSolicitudRequisicion(instance=requisicion) formset_detalles = DetalleRequisicionFormSet( prefix='detallerequisicion_set', queryset=requisicion.detallerequisicion_set.all() ) formset_adjunto = AdjuntoFormset( prefix='adjunto_set', queryset=requisicion.adjunto_set.all() ) data = { 'requisicion': requisicion, 'formset_detalles': formset_detalles, 'formset_adjunto': formset_adjunto, 'form': form } return render(request, 'compras/crear_requisicion.html', data)
def adjuntar_archivos_requisicion(request, id_requisicion): """ Vista para adjuntar archivos a una requisicion, solo disponible para usuarios de el area de compras """ # se obtiene el usuario try: empleado = request.user.empleado except: raise Http404 # se obtiene la requisicion requisicion = get_object_or_404(Requisicion, pk=id_requisicion) # deja entrar siempre y cuando la solicitud no este anulada o terminada if requisicion.is_anulada or requisicion.estado == Requisicion.TERMINADA or \ Requisicion.DATA_SET['compras'] != requisicion.get_rastreo(): raise Http404 # inicializa variable para saber si instnciar el formulario o no _historial_nuevo = False # se crea un formulario para los detalles de la requisicion DetalleRequisicionFormSet = modelformset_factory( DetalleRequisicion, form=FormularioEditarValoresDetallesRequisiciones, min_num=requisicion.detallerequisicion_set.count(), extra=0, validate_min=True, ) # se crea el formset que manejará los formularios de documentos adjuntos AdjuntoFormset = modelformset_factory( Adjunto, form=FormularioAdjunto, min_num=0, extra=1, validate_min=False, can_delete=True ) if request.method == 'POST': # se instancia el formulario de detalles de requisicion formset_detalles = DetalleRequisicionFormSet( data=request.POST, prefix='detallerequisicion_set', queryset=requisicion.detallerequisicion_set.all() ) # si la requisicion en su ultimo historial fue hecho por un usuario del area de compras if Requisicion.DATA_SET['administrativo'] == requisicion.get_rastreo(): # se crea el formulario instanciado form_historial = FormularioObservacionHistorial( data=request.POST, instance=requisicion.historial_set.last() ) else: # se crea un formulario nuevo form_historial = FormularioObservacionHistorial(data=request.POST) # se asigna true a la variable para indicar que es un formulario sin instancia _historial_nuevo = True # se instancia el formset formset_adjunto = AdjuntoFormset( data=request.POST, files=request.FILES, queryset=requisicion.adjunto_set.all(), prefix='adjunto_set' ) # si todo es valido if formset_adjunto.is_valid() and form_historial.is_valid() and formset_detalles.is_valid(): url = """ <a href='%s' class='alert-link'>Volver a la lista de Requisiciones</a> """ % reverse_lazy('compras:ver_requisiciones_compras') # ciclo encargado de borrar los documentos que seran eliminados y agregar los nuevos documentos for form_adjunto in formset_adjunto: # si el formulario tiene el DELETE en el post y si la instancia ya fue creada alguna vez if form_adjunto.cleaned_data.get('DELETE', False) and hasattr(form_adjunto.instance, 'pk'): # si todo esta bien con el pk y id if form_adjunto.instance.id is not None or form_adjunto.instance.pk is not None: # se borra el documento que se pidio desde la vista form_adjunto.instance.delete() continue # si no, crea el documento y le asigna la requisicion form_adjunto.instance.requisicion = requisicion # si no tiene archivo no lo guarda if not form_adjunto.cleaned_data.get('archivo', False): continue # de el caso contrario guarda el formulario con el nuevo archivo form_adjunto.save() historial = form_historial.save(commit=False) # Si es nuevo y tiene alguna observacion # si no tiene observacion tiene la opcion de darle en aceptar desde la vista de lista if _historial_nuevo and historial.observacion != '': # se crea el hitorial historial.empleado = empleado historial.requisicion = requisicion historial.estado = Historial.APROBADA # siempre y cuando sea un historial completo se guarda if hasattr(historial, 'requisicion'): historial.save() # se guarda el formset de detalles formset_detalles.save() messages.success( request, _("Se ha editado la requisicion No.{} exitosamente ".format(requisicion.id) + url) ) if Requisicion.DATA_SET['compras'] == requisicion.get_rastreo(): return redirect(reverse('compras:adjuntar_archivos_requisicion', args=(requisicion.id, ))) return redirect(reverse('compras:ver_requisiciones_compras')) else: messages.error(request, _("Ha ocurrido un error al enviar el formulario")) else: # if requisicion.historial_set.last().observacion != '': # se verifica quien fue el ultimo en hacer algo con la requisicion para instanciar o no el formulario if Requisicion.DATA_SET['administrativo'] == requisicion.get_rastreo(): form_historial = FormularioObservacionHistorial( instance=requisicion.historial_set.last() ) # si no, no se instancia el formulario else: form_historial = FormularioObservacionHistorial() # se instancia el formulario de archivos adjuntos formset_adjunto = AdjuntoFormset(queryset=requisicion.adjunto_set.all(), prefix='adjunto_set') # se instancia el formset de los detalles de requisiciones formset_detalles = DetalleRequisicionFormSet( prefix='detallerequisicion_set', queryset=requisicion.detallerequisicion_set.all() ) data = { 'formset_adjunto': formset_adjunto, 'form': form_historial, 'requisicion': requisicion, 'formset_detalles': formset_detalles } return render(request, 'compras/adjuntar_archivos_requisicion.html', data)
def forms(request): if request.method == 'POST' and 'add_object2' in request.POST: objCE = request.POST.get('add_object2') if objCE != '': ce = request.POST['add_object2'] scrapy = Command.handle(ce) ScrapyCapa = scrapy[0] ScrapyMerc = scrapy[1] form = ATIForm(prefix='FormConhec') form.fields["BL"].initial = ScrapyCapa[ 'Número BL do Conhecimento de Embarque Original :'] form.fields["CE"].initial = ce form.fields["REPCNPJ"].initial = ScrapyCapa['CNPJ :'] form.fields["REPREZAO"].initial = ScrapyCapa['Razão Social :'] #formStatus = StatusForm(prefix='StatusForm') form.fields["EMISSAO"].initial = ScrapyCapa[ 'Data de Emissão do BL :'] form.fields["SITUACAO"].initial = ScrapyCapa['Situação :'] form.fields["MODALIDADE"].initial = ScrapyCapa[ 'Modalidade de Frete :'] form.fields["pORIGEM"].initial = ScrapyCapa['Porto de Origem :'] form.fields["psPROCEDE"].initial = ScrapyCapa[ 'País de Procedência :'] form.fields["UFdestino"].initial = ScrapyCapa[ 'UF de Destino Final :'] Formset = modelformset_factory(CNT, form=MercForm) formMerc = Formset(queryset=CNT.objects.none(), initial=[{ 'CNT': ScrapyMerc[0][index], 'cntISO': ScrapyMerc[1][index], 'cntTipo': ScrapyMerc[2][index], 'cntTara': ScrapyMerc[3][index], 'cntPB': ScrapyMerc[4][index], 'm3': ScrapyMerc[5][index], 'codIMO:': ScrapyMerc[6][index], 'clasIMO': ScrapyMerc[7][index] } for index, i in enumerate(ScrapyMerc[0])]) formMerc.prefix = 'merda' a = len(ScrapyMerc[0]) formMerc.extra = a formsetAnexo = modelformset_factory(Anexos, AnexoForm, extra=1) formAnexo = formsetAnexo(queryset=Anexos.objects.none(), prefix='form2') return render(request, 'forms.html', { 'form': form, 'formMerc': formMerc, 'formAnexo': formAnexo }) formsetPost = request.POST.get('merda-0-CNT') if formsetPost != '' and formsetPost != None: Formset = modelformset_factory(CNT, form=MercForm) formCNT = Formset(request.POST, prefix='merda') formCE = ATIForm(request.POST, prefix='FormConhec') formAnexos = request.FILES formAnexoBL = formAnexos.getlist('formAnexoBL-arquivo') formAnexoCE = formAnexos.getlist('formAnexoCE-arquivo') formAnexoDT = formAnexos.getlist('formAnexoDT-arquivo') formAnexoIV = formAnexos.getlist('formAnexoIV-arquivo') formAnexoOT = formAnexos.getlist('formAnexoOT-arquivo') if formCE.is_valid(): idATI = formCE.save() if formCNT.is_valid(): for formset in formCNT: ObjCNT = formset.save(commit=False) ObjCNT.ID_CNT = idATI ObjCNT.save() #file_objs = formAnexo.getlist('form2-0-arquivo') """for obj in file_objs: anexo = Anexos.objects.create(arquivo=obj) anexoUp = Anexos.objects.get(pk=anexo.pk) anexoUp.ATI_ANEXO = idATI anexoUp.save()""" for obj in formAnexoBL: anexo = Anexos.objects.create(arquivo=obj) anexoUp = Anexos.objects.get(pk=anexo.pk) anexoUp.ATI_ANEXO = idATI anexoUp.tipo = 'BL' anexoUp.save() for obj in formAnexoCE: anexo = Anexos.objects.create(arquivo=obj) anexoUp = Anexos.objects.get(pk=anexo.pk) anexoUp.ATI_ANEXO = idATI anexoUp.tipo = 'CE' anexoUp.save() return redirect('/update/' + str(idATI.pk)) form = ATIForm(prefix='FormConhec') Formset = modelformset_factory(CNT, MercForm, extra=1) formMerc = Formset(queryset=CNT.objects.none(), prefix="merda") formsetAnexo = modelformset_factory(Anexos, AnexoForm, extra=1) #formAnexoBL = formsetAnexo(queryset=Anexos.objects.none(), prefix='form2') formAnexoBL = AnexoForm(prefix='formAnexoBL') formAnexoCE = AnexoForm(prefix='formAnexoCE') formAnexoDT = AnexoForm(prefix='formAnexoDT') formAnexoIV = AnexoForm(prefix='formAnexoIV') formAnexoOT = AnexoForm(prefix='formAnexoOT') return render( request, 'forms.html', { 'form': form, 'formMerc': formMerc, 'formAnexoBL': formAnexoBL, 'formAnexoCE': formAnexoCE, 'formAnexoDT': formAnexoDT, 'formAnexoIV': formAnexoIV, 'formAnexoOT': formAnexoOT })
#from django.forms import ModelForm from django.forms import modelformset_factory, TextInput, DateTimeInput #from django.forms import TextInput from .models import Trains UserForm = modelformset_factory(Trains, fields=( 'ordNumber', 'carNumber', 'trainIndex', 'trainNumber', 'carStatus', 'invoiceId', 'invoiceNumber', 'stateId', 'lastOperDt' ), # initial=[{'trainIndex': '-',}], widgets={ 'ordNumber': TextInput(attrs={'size': 10}), 'carNumber': TextInput(attrs={'size': 10}), 'trainIndex': TextInput(attrs={'size': 20}), 'trainNumber': TextInput(attrs={'size': 10}), 'carStatus': TextInput(attrs={'size': 35}), 'invoiceId': TextInput(attrs={'size': 10}), 'invoiceNumber': TextInput(attrs={'size': 10}), 'stateId': TextInput(attrs={'size': 5}), 'lastOperDt': DateTimeInput(attrs={'size': 15}), }, can_order=True ) ''' class Meta: model = Trains exclude = ['ordNumber'] '''