Exemplo n.º 1
0
def collection_requests(request, pk):
    try:
        collection = Collection.objects.get(pk=pk)
        requests = collection.request_set.all()
    except Collection.DoesNotExist:
        requests = []
    if request.method == 'POST':
        data = {'meta': {'status': 'OK'}}
        requests = json.loads(request.body).get('requests', [])
        for req in requests:
            p = urlparse(req['url']['href'])
            req.update(dict(p._asdict()))
            req_instance = Request.objects.get(pk=req['pk'])
            form = RequestForm(req, instance=req_instance)
            if form.is_valid():
                # need check permission
                form.save()
            else:
                data['meta']['status'] = 'error'
                return HttpResponse(content=json.dumps(data), status=400)
    else:
        data = {
            'meta': {
                'status': 'OK'
            },
            'data': [req.as_dict() for req in requests]
        }
    return HttpResponse(content=json.dumps(data), status=200)
Exemplo n.º 2
0
def collection_requests(request, pk):
    try:
        collection = Collection.objects.get(pk=pk)
        requests = collection.request_set.all()
    except Collection.DoesNotExist:
        requests = []
    if request.method == 'POST':
        data = {
            'meta': {
                'status': 'OK'
            }
        }
        requests = json.loads(request.body).get('requests', [])
        for req in requests:
            p = urlparse(req['url']['href'])
            req.update(dict(p._asdict()))
            req_instance = Request.objects.get(pk=req['pk'])
            form = RequestForm(req, instance=req_instance)
            if form.is_valid():
                # need check permission
                form.save()
            else:
                data['meta']['status'] = 'error'
                return HttpResponse(content=json.dumps(data), status=400)
    else:
        data = {
            'meta': {
                'status': 'OK'
            },
            'data': [req.as_dict() for req in requests]
        }
    return HttpResponse(content=json.dumps(data), status=200)
Exemplo n.º 3
0
def request_new(request):
    if request.method == 'POST':
        request_form = RequestForm(request.POST, request.FILES)
        if request_form.is_valid():
            try:
                req = request_form.save(commit=False)
                req.owner = request.user
                try:
                    req.save()
                    gcode_process_out = subprocess.check_output(
                        'Slic3r/slic3r.pl ' + str(req.cad_file.path),
                        shell=True,
                        timeout=5)
                    messages.success(request, "Solicitação recebida!")
                    return redirect('request:Request_list')
                except subprocess.CalledProcessError as gcode_exception:
                    req.delete()
                    print("error code " + str(gcode_exception.returncode) +
                          str(gcode_exception.output))
                    messages.error(request,
                                   "Arquivo STL não pôde ser validado!")
            except Exception as e:
                print(e)
                traceback.print_exc()
            messages.error(request, "Falha ao salvar solicitação!")
    else:
        request_form = RequestForm()
    return render(request, 'request/request_form.html', {'form': request_form})
Exemplo n.º 4
0
Arquivo: views.py Projeto: kpx13/navaz
def request_page(request):
    c = get_common_context(request)
    if request.method == "GET":
        c["request_form"] = RequestForm()
    else:
        form = RequestForm(request.POST)
        if form.is_valid():
            send_mail_to_admin(form.cleaned_data)
            form.save()
            form = RequestForm()
            messages.success(request, u"Ваш запрос отправлен.")
            return HttpResponseRedirect("/")
        else:
            c["request_form"] = form
    return render_to_response("request.html", c, context_instance=RequestContext(request))
Exemplo n.º 5
0
    def dispatch(self, request, *args, **kwargs):
        if self.request.method == "POST":
            flight_from = self.request.POST.get("flight_from")
            flight_to = self.request.POST.get("flight_to")
            departure_date = self.request.POST.get("departure_date")
            return_flight_date = self.request.POST.get("return_flight_date")
            amount_adults = self.request.POST.get("adults")
            amount_children = self.request.POST.get("children")
            travel_class = self.request.POST.get("travel_class")
            flight_type = self.request.POST.get("flight_type")
            phone = self.request.POST.get("phone")

            print(f"jo: {amount_adults}")

            form = RequestForm(self.request.POST)

            if form.is_valid() is True:
                body = "<strong>Abflug</strong><br/>"
                body += f"&nbsp;&nbsp;&nbsp;&nbsp;<strong>Von: </strong>: {flight_from}<br/>"
                body += f"&nbsp;&nbsp;&nbsp;&nbsp;<strong>Datum: </strong>: {departure_date}<br/>"
                body += "<strong>Ankunft</strong><br/>"
                body += f"&nbsp;&nbsp;&nbsp;&nbsp;<strong>In: </strong>: {flight_to}<br/>"
                body += "<strong>Rückflug</strong><br/>"
                body += f"&nbsp;&nbsp;&nbsp;&nbsp;<strong>Datum: </strong>: {return_flight_date}<br/>"
                body += f"<strong>Anzahl Erwachsene:</strong> {amount_adults}<br/>"
                body += f"<strong>Anzahl Kinder:</strong> {amount_children}<br/>"
                body += f"<strong>Reiseklasse:</strong> {travel_class}<br/>"
                body += f"<strong>{flight_type}</strong><br/>"
                body += f"<strong>Rufnummer: </strong>{phone}<br/>"
                email = EmailMessage(f"{flight_from} - {flight_to}", body,
                                     to=["*****@*****.**", "*****@*****.**", "*****@*****.**"])
                email.content_subtype = "html"
                status = email.send()
                if status == 1:
                    return JsonResponse(data={"message": "Email wurde erfolgreich abgesendet", "status": "SUCCESS"},
                                        status=201, safe=False)
                else:
                    return JsonResponse(data={"message": "Email konnte nicht abgesendet werden", "status": "FAILURE"},
                                        status=500, safe=False)
            else:
                errors = {}
                for e in form.errors:
                    errors[e] = form.errors[e]
                    print(f"{e} : {errors[e]}")
                return JsonResponse(data={"message": "form_error", "errors": errors, "status": "FAILURE"}, status=400, safe=False)
Exemplo n.º 6
0
Arquivo: views.py Projeto: kpx13/avg
def request_f(request):
    if request.POST and request.POST['action'] == 'request':
        form = RequestForm(request.POST)
        if form.is_valid():
            form.save()
            form = RequestForm()
            messages.success(request, u'Ваша заявка отправлена.')
            return HttpResponseRedirect('/')
        else:
            c = get_common_context(request)
            c.update(Page.get_by_slug('home'))
            c['actions'] = Action.objects.all()
            c['request_url'] = 'home'
            c['request_form'] = form
            c['request_form_open'] = True
            return render_to_response('home.html', c, context_instance=RequestContext(request))
    raise Http404() 
    
Exemplo n.º 7
0
def order_page(request):
    c = get_common_context(request)
    if request.method == 'GET':
        c['request_form'] = RequestForm()
    else:
        form = RequestForm(request.POST)
        if form.is_valid():
            form.save()
            data = form.cleaned_data
            message= u'Имя: ' + data['name'] + u"\n" + u'email: ' + data['email'] + '\n' + u'Телефон: ' + data['phone'] + '\n' + u'Текст: ' + data['comment'] + '\n'
        
            email = EmailMessage(u'Новое сообщение с сайта', message, settings.EMAIL_HOST_USER, settings.REQUEST_TO)
            file = request.FILES.get('brief')
            if file: email.attach_file(handle_file(file))
            email.send()

            messages.success(request, u'Ваш запрос отправлен.')
            return HttpResponseRedirect('/')
        else:
            c['request_form'] = form
            messages.error(request, u'При обработке формы произошла ошибка.')
    c.update(Page.get_page_by_slug('order'))
    return render_to_response('request.html', c, context_instance=RequestContext(request))
Exemplo n.º 8
0
Arquivo: views.py Projeto: kpx13/dieks
def get_common_context(request):
    c = {}
    
    callform = FeedbackForm()
    requestform = RequestForm()
    if request.method == 'POST':
        if request.POST['action'] == 'call':
            callform = FeedbackForm(request.POST)
            if callform.is_valid():
		if request.POST.get('phone') != '123456':
	            callform.save()
                c['msg'] = u'Спасибо! Ваша заявка принята, в ближайшее время с Вами свяжутся.'
                callform = FeedbackForm()
            else:
                c['msg'] = u'Необходимо ввести имя и телефон.'
            c['show_callform'] = True
        elif request.POST['action'] == 'request':
            requestform = RequestForm(request.POST)
            if requestform.is_valid():
		if request.POST.get('phone') != '123456':
                    requestform.save()
                c['msg'] = u'Спасибо! Ваша заявка принята, в ближайшее время с Вами свяжутся.'
                requestform = RequestForm()
            else:
                c['msg'] = u'Необходимо ввести имя и телефон.'
            c['show_requestform'] = True

    c['request_url'] = request.path
    c['is_debug'] = settings.DEBUG
    c['callform'] = callform
    c['requestform'] = requestform
    c['request_url'] = request.path
    c['title'] = u'АНО Диэкс: промышленная безопасность, экспертиза, неразрушающий контроль'
    c['slideshow'] = Slider.objects.all()
    c['reviews'] = Review.objects.all()[:3]
    c.update(csrf(request))
    return c