def impersonate_user(request, pk): user = get_object_or_404(get_user_model(), pk=pk) if request.method == 'POST': # Find a suitable backend. if not hasattr(user, "backend"): for backend in settings.AUTHENTICATION_BACKENDS: if not hasattr(load_backend(backend), "get_user"): continue if user == load_backend(backend).get_user(user.uuid): user.backend = backend break else: raise ImproperlyConfigured( "Could not found an appropriate authentication backend") form = forms.Form(request.POST) if form.is_valid(): try: original_user = request.user auth_login(request, user) messages.warning( request, _("You are logged in as %s ." % user.username)) # Add admin log entry change_message = "User {0} logged in as {1}.".format( original_user, user) log_change(request, user, change_message) return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) except Exception as e: message = _("There was an error %s") % e messages.error(request, message) return redirect(request.headers.get('Referer'))
def del_course_bundle(request: WSGIRequest, course_bundle_pk: int) -> HttpResponse: course_bundle: CourseBundle = get_object_or_404(CourseBundle, id=course_bundle_pk) form = forms.Form(request.POST or None) if form.is_valid(): course_bundle.delete() messages.success(request, _("The Course-bundle was successfully deleted")) return redirect("list_course_bundles") messages.warning( request, _( "Be aware that deleting this cascades. This means that if a subject has this Course-bundle it will be " "deleted. This includes everything that cascades of that subject. ", ), ) messages.warning( request, _("Be aware that deleting this affects all semesters. There be dragons." )) context = {"form": form, "course_bundle": course_bundle} return render( request, "settool_common/settings/subjects/course_bundle/del_course_bundle.html", context)
def change_tutor_status(request: WSGIRequest, uid: UUID, status: str) -> HttpResponse: tutor = get_object_or_404(Tutor, pk=uid) form = forms.Form(request.POST or None) if form.is_valid() and status in (x for x, _ in Tutor.STATUS_OPTIONS): tutor.status = status tutor.save() return HttpResponseRedirect(request.META.get("HTTP_REFERER", "/")) return http.HttpResponseBadRequest()
def info(request): if request.method == 'POST': my_form = forms.Form(request.POST, request.FILES) if my_form.is_valid(): new_img = Upload1(img=request.FILES.get('img'), finder=request.POST.get('finder', ''), phoneNumber=request.POST.get('phoneNumber', ''), details=request.POST.get('details', ''), user=request.user) new_img.save() return render(request, 'info.html')
def del_mail(request: WSGIRequest, mail_pk: int) -> HttpResponse: mail = get_object_or_404(Mail, pk=mail_pk) form = forms.Form(request.POST or None) if form.is_valid(): mail.delete() return redirect("list_mail") context = { "mail": mail, "form": form, } return render(request, "settool_common/settings/mail/delete_email.html", context)
def del_requirement(request: WSGIRequest, uid: UUID) -> HttpResponse: question = get_object_or_404(Question, pk=uid) form = forms.Form(request.POST or None) if form.is_valid(): question.delete() messages.success(request, f"Deleted Question {question.question}.") return redirect("tutors:list_requirements") context = { "requirement": question, "form": form, } return render(request, "tutors/requirement/delete.html", context)
def del_event(request: WSGIRequest, uid: UUID) -> HttpResponse: event = get_object_or_404(Event, pk=uid) form = forms.Form(request.POST or None) if form.is_valid(): event.delete() messages.success(request, f"Deleted Event {event.name}.") return redirect("tutors:list_event") context = { "event": event, "form": form, } return render(request, "tutors/event/delete.html", context)
def del_task(request: WSGIRequest, uid: UUID) -> HttpResponse: task = get_object_or_404(Task, pk=uid) form = forms.Form(request.POST or None) if form.is_valid(): task.delete() messages.success(request, f"Deleted Task {task.name}.") return redirect("tutors:list_task") context = { "task": task, "form": form, } return render(request, "tutors/task/delete.html", context)
def del_tutor(request: WSGIRequest, uid: UUID) -> HttpResponse: tutor = get_object_or_404(Tutor, pk=uid) form = forms.Form(request.POST or None) if form.is_valid(): tutor.delete() messages.success(request, _("Deleted Tutor {tutor}.").format(tutor=tutor)) return redirect("tutors:list_status_all") context = { "tutor": tutor, "form": form, } return render(request, "tutors/tutor/delete.html", context)
def image(request): print('Image is Available here...') myform = forms.Form(request.POST, request.FILES) print(myform.files) file1 = myform.files['image'] img_str = file1.read() file1.close() config = ('-l eng --oem 1 --psm 3') nparr = np.fromstring(img_str, np.uint8) im = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # Run tesseract OCR on image corpus = pytesseract.image_to_string(im, config=config) # print(corpus) request.session['corpus'] = 'Why' # Print recognized text return redirect('features')
def context(self): m_HeadDic = self.grid.HeadDic() m_init_option = { "url": "/grid/%s/%s/" % (self.app_menu, self.__class__.__name__), "dataType": "json", "usepager": True, "useRp": True, "rp": 15, "showTableToggleBtn": True, "onToggleCol": '$do_ToggleCol$', "onSubmit": '$do_Submit$', "pagestat": '显示 {from} 到 {to} ,共 {total} 条记录', 'nomsg': '无记录', 'procmsg': '正在处理中...', 'pagetext': '第', 'outof': '页 / 共', 'findtext': '查找' } m_init_option.update(self.option) m_HeadDic.update(m_init_option) addition = { "grid_option": smart_str(dumps(m_HeadDic)).replace('"$', '').replace('$"', ''), "hide_list": self.hide_list } if self.search_form: ''' 查询表单的处理 ''' form = forms.Form() for e in self.search_form: field = e[1] widget = None if field.__class__ in widgets.WIDGET_FOR_DBFIELD_DEFAULTS: widget = widgets.WIDGET_FOR_DBFIELD_DEFAULTS[ field.__class__] if widget: form_field = field.formfield(widget=widget) if hasattr(field, 'add_attrs'): form_field.widget.attrs.update(field.add_attrs) # form_field.widget_attrs = lambda o,w:field.add_attrs form.fields[e[0]] = form_field else: form.fields[e[0]] = field.formfield() addition["search_form"] = form addition.update(self.m_context) return addition
def del_qr_code(request: WSGIRequest, qr_code_pk: int) -> HttpResponse: qr_code: QRCode = get_object_or_404(QRCode, id=qr_code_pk) form = forms.Form(request.POST or None) if form.is_valid(): qr_code.delete() messages.success(request, _("The QRCode was successfully deleted")) return redirect("list_qr_codes") messages.warning( request, _( "Be aware that deleting this deletes the actual file from the server. This means that if an other user " "has included this image via a hardlink, this image will not be loaded anymore.", ), ) messages.warning( request, _("Be aware that deleting this affects all semesters. There be dragons." )) context = {"form": form, "qr_code": qr_code} return render(request, "settool_common/settings/qr-codes/del_qr_code.html", context)
def del_subject(request: WSGIRequest, subject_pk: int) -> HttpResponse: subject: Subject = get_object_or_404(Subject, id=subject_pk) form = forms.Form(request.POST or None) if form.is_valid(): subject.delete() messages.success(request, _("The Subject was successfully deleted")) return redirect("list_subjects") messages.warning( request, _( "Be aware that deleting this cascades. This means that if a participant has this Subject he/she will be " "deleted. ", ), ) messages.warning( request, _("Be aware that deleting this affects all semesters. There be dragons." )) context = {"form": form, "subject": subject} return render(request, "settool_common/settings/subjects/subject/del_subject.html", context)
def gen_form_fields(tables, fields): from django.forms import forms, widgets as wg from django.forms import RadioSelect import widgets from django.db import models form = forms.Form() for f in fields: if f.split(".")[1] not in form.fields.keys(): model = [t for t in tables if f.split(".")[0] == t.__name__][0] fd = model._meta.get_field(f.split(".")[1]) if isinstance(fd, models.ForeignKey) or isinstance( fd, models.ManyToManyField): fd = fd.formfield(widget=wg.TextInput) else: try: widget = None #print "mf.class :%s"% mf.__class__ if hasattr(model, "Admin"): if hasattr(model.Admin, "default_widgets"): if model.Admin.default_widgets.has_key( f.split(".")[1]): widget = model.Admin.default_widgets[f.split( ".")[1]] if not widget: if fd.__class__ in widgets.WIDGET_FOR_DBFIELD_DEFAULTS: widget = widgets.WIDGET_FOR_DBFIELD_DEFAULTS[ fd.__class__] if widget == RadioSelect: widget = None if widget: fd = fd.formfield(widget=widget) else: fd = fd.formfield() except: import traceback traceback.print_exc() form.fields[f.split(".")[1]] = fd return form
def gen_form_fields(tables, fields): from django.forms import forms, widgets as wg from django.forms import RadioSelect import widgets from django.db import models form = forms.Form() for f in fields: if f.split(".")[1] not in form.fields.keys(): model = [t for t in tables if f.split(".")[0] == t.__name__][0] fd = model._meta.get_field(f.split(".")[1]) if isinstance(fd, models.ForeignKey) or isinstance( fd, models.ManyToManyField): fd = fd.formfield(widget=wg.TextInput) else: try: widget = None #print "mf.class :%s"% mf.__class__ if hasattr(model, "Admin"): if hasattr(model.Admin, "default_widgets"): if model.Admin.default_widgets.has_key( f.split(".")[1]): widget = model.Admin.default_widgets[f.split( ".")[1]] if not widget: if fd.__class__ in widgets.WIDGET_FOR_DBFIELD_DEFAULTS: widget = widgets.WIDGET_FOR_DBFIELD_DEFAULTS[ fd.__class__] if widget == RadioSelect: widget = None if widget: fd = fd.formfield(widget=widget) else: fd = fd.formfield() except: import traceback traceback.print_exc() form.fields[f.split(".")[1]] = fd # for f in fields: # if f.find('__')>0 or f.find('.')>0: # f=f.replace(".","__") # s,p=f.split("__") # pf=model._meta.get_field(s).rel.to._meta.get_field(p) # if not pf.editable: # continue # fd=pf.formfield() # else: # mf=model._meta.get_field(f) # if not mf.editable: # continue # if isinstance(mf,models.ForeignKey) or isinstance(mf,models.ManyToManyField): # fd=mf.formfield(widget=wg.TextInput) # else: # widget=None # #print "mf.class :%s"% mf.__class__ # if mf.__class__ in widgets.WIDGET_FOR_DBFIELD_DEFAULTS: # widget=widgets.WIDGET_FOR_DBFIELD_DEFAULTS[mf.__class__] # if widget: # fd=mf.formfield(widget=widget) # else: # fd=mf.formfield() # # #print form.as_table() return form
def get_context_data(self, **kwargs): data = super(FavoriteRecipeRemove, self).get_context_data(**kwargs) # dummy form to check CSRF data['form'] = forms.Form() return data
def post(self, request, *args, **kwargs): # dummy form to check CSRF form = forms.Form(data=request.POST) if form.is_valid(): return self.form_valid(form) return self.form_invalid(form)
def confirm_delete_email(request, pk: int): email = models.Email.objects.get(id=pk) enable_delete_mailer_contact_checkbox = apps.is_installed( "basxconnect.mailer_integration") and hasattr(email, "subscription") fields = [] if enable_delete_mailer_contact_checkbox: from basxconnect.mailer_integration.settings import MAILER class DeleteMailerSubscriptionForm(forms.Form): delete_mailer_contact = django.forms.BooleanField( label=_("Delete linked %s subscription as well") % MAILER.name(), required=False, ) fields.append("delete_mailer_contact") if request.method == "POST": form = DeleteMailerSubscriptionForm(request.POST) if form.is_valid(): person = email.person if enable_delete_mailer_contact_checkbox and form.cleaned_data.get( "delete_mailer_contact"): try: from basxconnect.mailer_integration.settings import MAILER MAILER.delete_person(email.email) except Exception: logging.error( "tried to delete person from mailer but failed") email.delete() person.refresh_from_db() person.save() return HttpResponseRedirect( reverse_model(person, "read", kwargs={"pk": person.pk})) else: form = DeleteMailerSubscriptionForm() else: if request.method == "POST": form = forms.Form(request.POST) if form.is_valid(): email.delete() return HttpResponseRedirect( reverse_model(email.person, "read", kwargs={"pk": email.person.pk})) else: form = forms.Form() return layout.render( request, import_string(settings.DEFAULT_PAGE_LAYOUT)( menu.main, Form( form, hg.BaseElement( hg.H3(_("Delete email %s") % email.email), *(bread.layout.forms.FormField(field) for field in fields), ), hg.DIV( Button.from_link( Link( href=reverse_model(email.person, "read", kwargs={"pk": email.person.pk}), label=_("Cancel"), iconname=None, ), buttontype="tertiary", ), hg.DIV(style="width: 1rem"), *layout.forms.helpers.Submit(_("Confirm")), style="display: flex; ", ), ), ), )