コード例 #1
0
ファイル: views.py プロジェクト: mkramb/errorify
def feedback_save(request):
    form = FeedbackForm(request.user, data=request.POST.copy() or None)

    if form.is_bound and form.is_valid():
        form.save(request.user) 

    return HttpResponse()
コード例 #2
0
ファイル: views.py プロジェクト: MaratFM/Djanym
def feedback(request):
    '''
    '''
    message = u'Форма обратной связи' 
    if request.method == 'POST':    
        form = FeedbackForm(request.POST) 
   
        if form.is_valid():

            email = render_to_string('feedback/email.html', {'object': form.cleaned_data})
            subject, content = EMAIL_SPLIT_RE.split(email, 1)            
            
            from_email = settings.DEFAULT_FROM_EMAIL                                                               
            to_email = getattr(settings, 'FEEDBACK_EMAILS', [e[1] for e in settings.MANAGERS])     

            msg = EmailMultiAlternatives(subject, content, from_email, to_email)                                   
            msg.content_subtype = "html"                                                                       
            msg.send()
            
            message = u'Ваш вопрос успешно отправлен!'
            form = None
    else:            
        form = FeedbackForm()

    return {
            'form': form,
            'message': message,            
            }
コード例 #3
0
ファイル: views.py プロジェクト: kblauer/kinder-updates
def create(request):
    username = None
    group = 'teacher'
    
    if request.user.is_authenticated():
        username = request.user.username
        if request.user.has_perm('feedback.add_feedback'):
            group = 'parent'
            
    if request.POST:
        form = FeedbackForm(request.POST)
        if form.is_valid():
            # this saves the form submission data, but doesn't submit it to the server yet
            # It is needed so that we can set the parent ID on the model data before final submission
            fb = form.save(commit=False)
            fb.sentByParent = request.user
            fb.save()
            
            return HttpResponseRedirect('/feedback/parent_view/')
        
    else:
        form = FeedbackForm()
        
        args = {}
        args.update(csrf(request))
        
        args['form'] = form
        args['username'] = username
        args['group'] = group
        
        return render_to_response('create_feedback.html', args)
コード例 #4
0
ファイル: views.py プロジェクト: IIIT-Delhi/findmystuff
def feedback(request):
    """
    sends the feedback modal.
    """
    logged_in = True

    # CHECKS:
    #   i) user is logged in
    #   ii) request is either ajax for requesting feedback modal
    #   iii) request is a POST request for submitting feedback
    # else error
    if (not request.user.is_authenticated()) or \
            (not request.is_ajax() and not request.method == "POST"):
        return HttpResponse("Please login and go to the main page.")

    form = FeedbackForm()
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user         # add user
            obj.save()
            messages.success(request, "Thank you for your valuable feedback.")
        return HttpResponseRedirect(reverse('home'))
    return render(request, 'feedback.html',{
        'form': form, 'logged_in': logged_in })
コード例 #5
0
def feedback(request):
    """
    sends the feedback modal.
    """
    logged_in = True

    # CHECKS:
    #   i) user is logged in
    #   ii) request is either ajax for requesting feedback modal
    #   iii) request is a POST request for submitting feedback
    # else error
    if (not request.user.is_authenticated()) or \
            (not request.is_ajax() and not request.method == "POST"):
        return HttpResponse("Please login and go to the main page.")

    form = FeedbackForm()
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user  # add user
            obj.save()
            messages.success(request, "Thank you for your valuable feedback.")
        return HttpResponseRedirect(reverse('home'))
    return render(request, 'feedback.html', {
        'form': form,
        'logged_in': logged_in
    })
コード例 #6
0
def add(request):
    if request.method == "POST":
        form = FeedbackForm(request.POST)

        if form.is_valid():
            form.instance.user = request.user
            if 'HTTP_REFERER' in request.META:
                form.instance.page = request.META['HTTP_REFERER']

            form.save()

            return HttpResponse('', mimetype="text/plain")
        else:
            logger.debug(form.errors)
            error_msg = []
            for field in form.errors:
                for error in form.errors[field]:
                    error_msg.append('%s: %s' %
                                     (form.fields[field].label, error))
            error_msg = '\n'.join(error_msg)

            return HttpResponseBadRequest(error_msg, mimetype="text/plain")
    else:
        return HttpResponseNotAllowed([
            "POST",
        ])
コード例 #7
0
ファイル: views.py プロジェクト: mkramb/errorify
def feedback_save(request):
    form = FeedbackForm(request.user, data=request.POST.copy() or None)

    if form.is_bound and form.is_valid():
        form.save(request.user)

    return HttpResponse()
コード例 #8
0
def FeedbackView(request):
    if request.method == 'POST':
        fform = FeedbackForm(request.POST)
        if fform.is_valid():
            name = request.POST.get('name', '')
            rating = request.POST.get('rating', '')
            feedback = request.POST.get('feedback', '')

            data = FeedbackData(name=name,
                                rating=rating,
                                date=date1,
                                feedback=feedback)
            data.save()
            fform = FeedbackForm()
            feedbacks = FeedbackData.objects.all()
            return render(request, 'institute_feedback.html', {
                'fform': fform,
                'feedbacks': feedbacks
            })
        else:
            return HttpResponse("Enter all fields")

    else:
        fform = FeedbackForm()
        feedbacks = FeedbackData.objects.all()
        return render(request, 'institute_feedback.html', {
            'fform': fform,
            'feedbacks': feedbacks
        })
コード例 #9
0
ファイル: views.py プロジェクト: ellenbowman/Satellite
def contact(request):

    if request.POST:
        form = FeedbackForm(request.POST)

        if form.is_valid():

            context = {
                'page_title':"Feedback",
                'name': form.cleaned_data['name'],
                'email': form.cleaned_data['email'],
                'comments': form.cleaned_data['comments'],
            }

            try:
                Feedback.objects.create(name=context['name'], email=context['email'], comments=context['comments'])
            except Exception as e:
                context['error'] = str(e)

            return render(request, 'risk_ratings/contact_thanks.html', context)
    else:
        form = FeedbackForm()

    context = {
            'page_title':"Feedback",
            'feedbacks':Feedback.objects.all(),
            'form': form,
        }

    return render(request, 'risk_ratings/contact.html', context)
コード例 #10
0
ファイル: views.py プロジェクト: Bl3f/django-feedback
    def post(self, request, *args, **kwargs):
        form = FeedbackForm(data=request.POST)

        if form.is_valid():
            data = form.cleaned_data

            feedback_message = FeedbackMessage()
            feedback_message.type = data.get('type')
            feedback_message.subject = data.get('subject')
            feedback_message.content = data.get('content')
            feedback_message.user = request.user
            feedback_message.save()

            requester = '*****@*****.**'
            if '@' in feedback_message.user.email:
                requester = feedback_message.user.email

            message = (u"[FEEDBACK ADHOC] {0}: {1}".format(feedback_message.type.capitalize(), feedback_message.subject),
                       u"{0}\n- - - - - - - - - -\nFrom user: {1}".format(feedback_message.content,
                                                                          feedback_message.user.username,
                                                                          ),
                       requester,
                       getattr(settings, 'EMAIL_FOR', None),
                       )

            send_mail(*message, fail_silently=False)

            return HttpResponse('true')
        else:
            context = super(FeedbackView, self).get_context_data(**kwargs)
            context.update({
                'form': form,
            })
            return self.render_to_response(context)
コード例 #11
0
ファイル: views.py プロジェクト: romantix74/Raduga
def contact(request):
    """Renders the contact page."""
    assert isinstance(request, HttpRequest)
    args = {}
    args['formFeedback'] = FeedbackForm()
    args['title'] = u'Контактная информация'
    args['year'] = datetime.now().year
    if request.POST:
        _form = FeedbackForm(request.POST)
        if _form.is_valid():
            user_mail = _form.cleaned_data['user_mail']
            user_question = _form.cleaned_data['user_question']
            #отправляем админам письмо о создании коллектива
            _mails = User.objects.filter(is_superuser=1).values_list('email',
                                                                     flat=True)
            for mail in _mails:
                try:
                    print "debug====================="
                    send_mail(u'Вопрос от: {0}'.format(user_mail),
                              u'{0}'.format(user_question),
                              '*****@*****.**', [mail],
                              fail_silently=False)
                except Exception as ex:
                    print ex.message
            messages.add_message(request, messages.SUCCESS,
                                 u'Ваш запрос отправлен')
            return redirect(reverse('contact'))  #return redirect('/');
        else:
            # если что то не так , то выводим форму с ошибками
            args['formFeedback'] = _form
    return render(
        request,
        'app/contact.html',
        args  #context_instance = RequestContext(request, args)
    )
コード例 #12
0
def show_feedback_form(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            form.mail()
            return render_to_response('feedback/thankyou.html', {'form': form})
    else:
        form = FeedbackForm()
    return render_to_response('feedback/feedback.html', {'form': form})
コード例 #13
0
def feedback(request):
    feedbackform = FeedbackForm(request.POST)
    if not feedbackform.is_valid():
        return redirect("search")
    else:
        message = feedbackform.cleaned_data["message"]
        email = feedbackform.cleaned_data["email"]
        send_mail("feedback", message, email, ["*****@*****.**"], fail_silently=True)
        return redirect("feedbackThanks")
コード例 #14
0
ファイル: views.py プロジェクト: nixilla/where-is-when-is
def feedback(request):

    form = FeedbackForm(request.POST or None)
    if form.is_valid():
        form.save()

        # TODO: Add message (django.contrib.messages)

        return redirect('/')

    return render(request, 'feedback.html', {'form': form})
コード例 #15
0
def feedback_view(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('ok')
        else:
            errors = {}
            for key, value in form.errors.items():
                errors[key] = value[0]
            return HttpResponse(json.dumps(errors))
コード例 #16
0
def send_feedback(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'guestbook/frontend/thanks.html')
    else:
        form = FeedbackForm()

    return render(request, 'guestbook/frontend/send_feedback.html', {
        'form': form,
    })
コード例 #17
0
ファイル: views.py プロジェクト: VBelozyorov/libcms
def send_feedback(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'guestbook/frontend/thanks.html')
    else:
        form = FeedbackForm()

    return render(request, 'guestbook/frontend/send_feedback.html', {
        'form': form,
    })
コード例 #18
0
ファイル: views.py プロジェクト: isergey/system
def add_feedback(request, conference_slug=''):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('guestbook_index'))
    else:
        form = FeedbackForm()
    return render(request, 'guestbook/feedback_add.html',
                              {'form': form,
                               'module':'guestbook',})
コード例 #19
0
def add(request):
    """Gather feedback for a page, and if it is ok show a thanks message and link back to the page."""

    submit_was_success = False
    return_to_url      = None
    submit_error_message  = None

    # If it is a post request try to create the feedback
    if request.method == 'POST':
        form = FeedbackForm( request.POST )

        if form.is_valid():
            feedback = Feedback()
            feedback.url      = form.cleaned_data['url']
            feedback.email    = form.cleaned_data['email']
            feedback.comment  = form.cleaned_data['comment']

            submit_was_success = True

            if settings.GOOGLE_RECAPTCHA_SECRET_KEY:
                recaptcha_response = request.POST.get("g-recaptcha-response")
                if not recaptcha_client.verify(recaptcha_response):
                    submit_was_success = False
                    submit_error_message = "Sorry, something went wrong. Please try again or email us at <a href='mailto:[email protected]'>[email protected]</a>"
            
            # if the comment starts with an html tag it is probably spam
            if re.search('\A\s*<\w+>', form.cleaned_data['comment']):
                feedback.status = 'spammy'

            if request.user.is_authenticated():
                feedback.user = request.user

            if submit_was_success:
                feedback.save()

            return_to_url = feedback.url or None
        
    else:
        # use GET to grab the url if set
        form = FeedbackForm(initial=request.GET)
        
    
    return render(
        request,
        'feedback/add.html',
        {
            'form':               form,
            'submit_was_success': submit_was_success,
            'return_to_url':      return_to_url,
            'submit_error_message': submit_error_message
        },
    )
コード例 #20
0
ファイル: views.py プロジェクト: Bauerr/geoq
def feedbackcreate(request):

    form = FeedbackForm(request.POST or None)
    topics = Topic.objects.all()

    if request.method == 'POST':
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(reverse('thanks'))
        else:
            return render(request, 'feedback.html', {'form': form, 'topics': topics })

    return render(request, 'feedback.html', {'form': FeedbackForm(), 'topics': topics})
コード例 #21
0
ファイル: views.py プロジェクト: VBelozyorov/libcms
def edit_feedback(request, id):
    feedback = get_object_or_404(Feedback, id=id)
    if request.method == 'POST':
        form = FeedbackForm(request.POST, instance=feedback)
        if form.is_valid():
            form.save()
            return redirect('guestbook:administration:feedbacks_list')
    else:
        form = FeedbackForm(instance=feedback)

    return render(request, 'guestbook/administration/edit_feedback.html', {
        'form': form,
    })
コード例 #22
0
ファイル: views.py プロジェクト: Kirito1899/libcms
def edit_feedback(request, id):
    feedback = get_object_or_404(Feedback, id=id)
    if request.method == 'POST':
        form = FeedbackForm(request.POST, instance=feedback)
        if form.is_valid():
            form.save()
            return redirect('guestbook:administration:feedbacks_list')
    else:
        form = FeedbackForm(instance=feedback)

    return render(request, 'guestbook/administration/edit_feedback.html', {
        'form': form,
    })
コード例 #23
0
ファイル: views.py プロジェクト: isergey/system
def edit(request, message_id):
    feedback = get_object_or_404(Feedback, id=message_id)
    if request.method == 'POST':
        form = FeedbackForm(request.POST, instance=feedback)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('administration_guestbook_index'))
    else:
        form = FeedbackForm(model_to_dict(feedback),instance=feedback)
    return direct_to_template(request, 'guestbook/administration/edit_message.html',
                              {'form': form,
                               'feedback':feedback,
                               'active_module': 'guestbook'})
コード例 #24
0
ファイル: views.py プロジェクト: larinam/ratings
def feedback(request):
    if request.POST:
        form = FeedbackForm(request.POST.copy())
        if not form.is_valid():
            return render_to_response("ratings/one_form_page.html", dict(form=form), context_instance=RequestContext(request))
        data = form.cleaned_data
        send_mail("Письмо с сайта", data["question"] + '\r\n\r\n' + data["name"] + data["contacts"], DEFAULT_FROM_EMAIL, [TO_EMAIL], False, "", "")
        return render_to_response("ratings/one_widget_page.html", dict(widget="Спасибо за обратную связь!", link="/ratings/", link_text="Вернуться на главную",
                                                                      title="Обратная связь" ),
                              context_instance=RequestContext(request))
    form = FeedbackForm()
    return render_to_response("ratings/one_form_page.html", dict(form=form, link="mailto:%s" % (TO_EMAIL), link_text="Написать нам через почтовый клиент", 
                                                                 title="Форма обратной связи"),
                              context_instance=RequestContext(request))
コード例 #25
0
ファイル: views.py プロジェクト: zacharyvoase/django-retracer
def feedback(request):
    if request.method == 'GET':
        request.stash_referrer()
        # Display the form.
        return django.http.HttpResponse()
    elif request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            feedback = form.save()
            # Redirect to stashed location, or index.
            return request.unstash_location_with_default('index')
        else:
            # Display the form, with errors.
            return django.http.HttpResponseBadRequest()
    return django.http.HttpResponseNotAllowed(['GET', 'POST'])
コード例 #26
0
ファイル: views.py プロジェクト: joash/djangotemplate
def contact(request):
    """
    Feedback form
    """
    form = FeedbackForm(initial={'submitter': request.user})

    if request.method == 'POST':
        form = FeedbackForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            form.save()
            messages.error(request, 'Thank you', fail_silently=False)
        else:
            messages.error(request, 'Invalid', fail_silently=False)
            print form.errors

    return render(request, "contact.html", {'form': form, 'helper': FeedbackForm.helper})
コード例 #27
0
def feedback_save(request):
    id = request.GET.get('id')

    if id == None:
        form = FeedbackForm(request.POST)
    else:
        instance = get_object_or_404(Feedback, pk=id)
        form = FeedbackForm(request.POST, instance=instance)

    try:
        if form.is_valid():
            instance = form.save()
            return JSONResponse({'id': instance.id})
        else:
            return JSONError(utils.dump_form_errors(form))
    except Exception, e:
        return JSONError(unicode(e))
コード例 #28
0
ファイル: views.py プロジェクト: Code4SA/pombola
def add(request):
    """Gather feedback for a page, and if it is ok show a thanks message and link back to the page."""

    submit_was_success = False
    return_to_url      = None

    # If it is a post request try to create the feedback
    if request.method == 'POST':
        form = FeedbackForm( request.POST )
        if form.is_valid():
            feedback = Feedback()
            feedback.url      = form.cleaned_data['url']
            feedback.email    = form.cleaned_data['email']
            feedback.comment  = form.cleaned_data['comment']

            # if there is any content in the honeypot field then label this comment as spammy
            if form.cleaned_data['website']:
                feedback.status = 'spammy'
            
            # if the comment starts with an html tag it is probably spam
            if re.search('\A\s*<\w+>', form.cleaned_data['comment']):
                feedback.status = 'spammy'

            if request.user.is_authenticated():
                feedback.user = request.user

            feedback.save()

            submit_was_success = True
            return_to_url = feedback.url or None
        
    else:
        # use GET to grab the url if set
        form = FeedbackForm(initial=request.GET)
        
    
    return render_to_response(
        'feedback/add.html',
        {
            'form':               form,
            'submit_was_success': submit_was_success,
            'return_to_url':      return_to_url,
        },
        context_instance=RequestContext(request)
    )
コード例 #29
0
ファイル: views.py プロジェクト: moomou/rateplusplus
def FeedbackHandler(request):
    if request.method == "POST":
        form = FeedbackForm(request.POST)

        if form.is_valid():
            cd = form.cleaned_data

            #send email to me 
            send_mail('Feedback for Cloverite', cd['feedback'], cd['userEmail'], ['*****@*****.**'], fail_silently=True)

            #send email to user
            if cd['userEmail']:
                send_mail('Thank you for testing Cloverite!', EMAIL_MSG, "*****@*****.**", [cd['userEmail']], fail_silently=True)

            return HttpResponse(json.dumps("pass"), mimetype="application/json")

        else:
            return HttpResponse(json.dumps(form.errors), mimetype="application/json")
コード例 #30
0
ファイル: views.py プロジェクト: isergey/libcms
def index(request):
    feedbacks_page = get_page(request, Feedback.objects.filter(publicated=True).order_by('-add_date'))

    count_feedback = len(feedbacks_page)

    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'guestbook/frontend/thanks.html')
    else:
        form = FeedbackForm()

    return render(request, 'guestbook/frontend/index.html', {
        'feedbacks_page': feedbacks_page,
        'form': form,
        'count_feedback': count_feedback
    })
コード例 #31
0
def submit_feedback(request):
    if request.method == 'GET':
        return render_to_response('feedback/feedback_form.html', 
            {'form': FeedbackForm()},
            context_instance=RequestContext(request))

    elif request.method == 'POST':
        form = FeedbackForm(request.POST)

        if form.is_valid():
            feedback = form.save(commit=False)
            feedback.is_spam = spam.is_spam(request, feedback.name, feedback.comment)
            feedback.save()
            return render_to_response('feedback/feedback_success.html',context_instance=RequestContext(request))

        return render_to_response('feedback/feedback_form.html',
                {'form':form},
                context_instance=RequestContext(request))
コード例 #32
0
ファイル: views.py プロジェクト: vault/bugit
def feedback_main(request):
    success = False
    if 'success' in request.GET:
        success = True

    if request.method == 'GET':
        form = FeedbackForm()
    elif request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            feedback = form.save(commit=False)
            feedback.sender = request.user
            feedback.save()
            furl = reverse('feedback') + '?success=1'
            return HttpResponseRedirect(furl)

    context = get_context(request, {'form':form, 'success':success})
    return render_to_response('feedback/feedback.html', context, context_instance=RequestContext(request))
コード例 #33
0
ファイル: views.py プロジェクト: glynnbailey/myshop
def feedback(request):
    
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            data = Feedback(name=form.cleaned_data['name'], email=form.cleaned_data['email'], comment=form.cleaned_data['comment'])
            data.save()
            message = "Thanks for the feedback"
            context = {'form':FeedbackForm(), 'message':message, 'count':request.session.get('count',0)}
            return render(request, 'feedback/feedback.html', context)
        else:
            # If data is not valid, reload page with error
            message = "Oops! Something went wrong!"
            context = {'form':FeedbackForm(), 'message':message, 'count':request.session.get('count',0)}
            return render(request, 'feedback/feedback.html', context)
    else:
        context = {'form':FeedbackForm(), 'count':request.session.get('count',0)}
        return render(request, 'feedback/feedback.html', context)
コード例 #34
0
ファイル: win_views.py プロジェクト: NobodyWHU/QianXun-1
def window_feedback(request):
    feedback_form = FeedbackForm(request.POST)
    if feedback_form.is_valid():
        feedback_dict = feedback_form.cleaned_data
        window_id = request.user_meta['window_model'].id
        try:
            if feedback_dict['type'] == '1':  # suggestion
                feedback_dict['subject'] = "".join([u'[校园便当_商家用户反馈]', feedback_dict['subject']])
                feedback_dict['message'] = "\n----------\nfrom ID: ".join([feedback_dict['message'], str(window_id)])
                email(feedback_dict, ADMIN_EMAIL['MANAGER_EMAIL'])
            else:  # crash report
                feedback_dict['subject'] = "".join([u'[校园便当_商家版崩溃报告]', feedback_dict['subject']])
                feedback_dict['message'] = "\n----------\nfrom ID: ".join([feedback_dict['message'], str(window_id)])
                email(feedback_dict, ADMIN_EMAIL['APP_DEVELPOER_EMAIL'])
            return json_response(OK, CODE_MESSAGE.get(OK))
        except SMTPAuthenticationError:
            return json_response(EMAIL_SEND_FAILED, CODE_MESSAGE.get(EMAIL_SEND_FAILED))
    else:
        return json_response(PARAM_REQUIRED, feedback_form.errors)
コード例 #35
0
ファイル: views.py プロジェクト: open-build/TolaWork_Dev
def contact(request):
    """
    Feedback form
    """
    form = FeedbackForm(initial={'submitter': request.user})

    if request.method == 'POST':
        form = FeedbackForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            form.save()
            messages.error(request, 'Thank you', fail_silently=False)
        else:
            messages.error(request, 'Invalid', fail_silently=False)
            print form.errors

    return render(request, "contact.html", {
        'form': form,
        'helper': FeedbackForm.helper
    })
コード例 #36
0
ファイル: views.py プロジェクト: dosberg/Feedback
def feedback_request(request):
    user = request.user

    class RequiredFormSet(BaseFormSet):
        def __init__(self, *args, **kwargs):
            super(RequiredFormSet, self).__init__(*args, **kwargs)
            for form in self.forms:
                form.empty_permitted = False

    QuestionFormSet = formset_factory(QuestionForm, max_num=10, formset=RequiredFormSet)
    if request.method == 'POST': 

        request_user = Request(user=request.user)
        request_form = FeedbackForm(request.POST, instance=request_user) # A form bound to the POST data
      
        # Create a formset from the submitted data
        question_formset = QuestionFormSet(request.POST, request.FILES)

        if request_form.is_valid() and question_formset.is_valid():
            request = request_form.save()
          
            for form in question_formset.forms:

                question = form.save(commit=False)
                question.request = request
                question.save()
              
            ''' 

            TODO: make this work 
            messages.success(request, 'Your request for feedback was sent to {{ email address }}!')
           
            '''
            return redirect('dashboard')
    else:
        request_form = FeedbackForm()
        question_formset = QuestionFormSet()

    return render_to_response('request.html', {
        'request_form': request_form,
        'question_formset': question_formset,
        'user': user,
    }, RequestContext(request))
コード例 #37
0
ファイル: views.py プロジェクト: zhipeng0117/geoq
def feedbackcreate(request):

    form = FeedbackForm(request.POST or None)
    topics = Topic.objects.all()

    if request.method == 'POST':
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(reverse('thanks'))
        else:
            return render(request, 'feedback.html', {
                'form': form,
                'topics': topics
            })

    return render(request, 'feedback.html', {
        'form': FeedbackForm(),
        'topics': topics
    })
コード例 #38
0
ファイル: views.py プロジェクト: mcdermott-scholars/mcdermott
def applicant_profile(request, event_name, name):
    try:
        applicant = Applicant.objects.get(norm_name=normalize_name(name),
                                          event__name=event_name)
    except Applicant.DoesNotExist:
        raise Http404('Applicant does not exist.')
    try:
        event = Event.objects.get(name=event_name)
    except Event.DoesNotExist:
        raise Http404('Event does not exist')
    try:
        feedback = Feedback.objects.get(applicant=applicant,
                                        scholar=request.user.mcuser)
    except Feedback.DoesNotExist:
        feedback = Feedback()
        feedback.applicant = applicant
        feedback.scholar = request.user.mcuser
    if request.method == 'POST':
        form = FeedbackForm(request.POST, instance=feedback)
        if (form.is_valid()):
            form.save()
            if request.is_ajax():
                return JsonResponse({'msg': 'saved successfully'})
            return redirect('feedback:index', event_name)
    else:
        form = FeedbackForm(instance=feedback)
    all_feedback = Feedback.objects.filter(applicant=applicant)
    is_interviewer = request.user.mcuser in event.interviewers.all()
    is_assigned = Assignment.objects.filter(scholar=request.user.mcuser,
                                            applicant=applicant).exists()

    context = {
        'feedback': all_feedback,
        'applicant': applicant,
        'form': form,
        'state': get_state(),
        'event_name': event_name,
        'survey_link': event.survey_link,
        'is_interviewer': is_interviewer and is_assigned,
        'favorited': favorited(request.user.mcuser, applicant)
    }
    return render(request, 'feedback/applicant.html', context)
コード例 #39
0
ファイル: views.py プロジェクト: vault/bugit
def feedback_main(request):
    success = False
    if 'success' in request.GET:
        success = True

    if request.method == 'GET':
        form = FeedbackForm()
    elif request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            feedback = form.save(commit=False)
            feedback.sender = request.user
            feedback.save()
            furl = reverse('feedback') + '?success=1'
            return HttpResponseRedirect(furl)

    context = get_context(request, {'form': form, 'success': success})
    return render_to_response('feedback/feedback.html',
                              context,
                              context_instance=RequestContext(request))
コード例 #40
0
ファイル: views.py プロジェクト: lokesh27/3Dex_portal
def send_form(request):
    try:
        instance=Student.objects.get(email_id=request.user.email)
    except:
        instance=''
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            name=request.POST.get('name','')
            email_id=request.POST.get('email_id','')
            query=request.POST.get('query','')
            obj = Feed(name=name, email_id=email_id, query=query)
            obj.save()
            return index(request)
        else:
            print form.errors
    else:
        form = FeedbackForm()
    context={'form': form,'student':instance}
    return render(request,'feedback1.html',context)
コード例 #41
0
ファイル: views.py プロジェクト: dragonslice/nxdom
def index(request):
    """
    Handle post requests or list recent feedback messages.
    """
    # Check if this is a post request with new feedback.
    feedback_form = FeedbackForm(request.POST or None)
    if feedback_form.is_valid():
        return submit(request,
                      page=feedback_form.cleaned_data['page'],
                      message=feedback_form.cleaned_data['message'])
    # Check if this is a post request to vote on a message.
    vote_form = VoteForm(request.POST or None)
    if vote_form.is_valid():
        return vote(request, vote_form.cleaned_data['vote'])
    # Check if this is a post request to delete a message.
    delete_form = DeleteForm(request.POST or None)
    if delete_form.is_valid():
        return delete(request, delete_form.cleaned_data['delete'])
    # Otherwise, display recent feedback.
    return render_to_response(request, 'feedback/index.html', locals())
コード例 #42
0
def send_form(request):
    try:
        instance = Student.objects.get(email_id=request.user.email)
    except:
        instance = ''
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            name = request.POST.get('name', '')
            email_id = request.POST.get('email_id', '')
            query = request.POST.get('query', '')
            obj = Feed(name=name, email_id=email_id, query=query)
            obj.save()
            return index(request)
        else:
            print form.errors
    else:
        form = FeedbackForm()
    context = {'form': form, 'student': instance}
    return render(request, 'feedback1.html', context)
コード例 #43
0
def add(request):
    """Gather feedback for a page, and if it is ok show a thanks message and link back to the page."""

    submit_was_success = False
    return_to_url = None

    # If it is a post request try to create the feedback
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            feedback = Feedback()
            feedback.url = form.cleaned_data['url']
            feedback.email = form.cleaned_data['email']
            feedback.comment = form.cleaned_data['comment']

            # if there is any content in the honeypot field then label this comment as spammy
            if form.cleaned_data['website']:
                feedback.status = 'spammy'

            # if the comment starts with an html tag it is probably spam
            if re.search('\A\s*<\w+>', form.cleaned_data['comment']):
                feedback.status = 'spammy'

            if request.user.is_authenticated():
                feedback.user = request.user

            feedback.save()

            submit_was_success = True
            return_to_url = feedback.url or None

    else:
        # use GET to grab the url if set
        form = FeedbackForm(initial=request.GET)

    return render_to_response('feedback/add.html', {
        'form': form,
        'submit_was_success': submit_was_success,
        'return_to_url': return_to_url,
    },
                              context_instance=RequestContext(request))
コード例 #44
0
def index(request):
    feedbacks_page = get_page(
        request,
        Feedback.objects.filter(publicated=True).order_by('-add_date'))

    count_feedback = len(feedbacks_page)

    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'guestbook/frontend/thanks.html')
    else:
        form = FeedbackForm()

    return render(
        request, 'guestbook/frontend/index.html', {
            'feedbacks_page': feedbacks_page,
            'form': form,
            'count_feedback': count_feedback
        })
コード例 #45
0
ファイル: views.py プロジェクト: mcdermott-scholars/mcdermott
def applicant_profile(request, event_name, name):
  try:
    applicant = Applicant.objects.get(norm_name=normalize_name(name), event__name=event_name)
  except Applicant.DoesNotExist:
    raise Http404('Applicant does not exist.')
  try:
    event = Event.objects.get(name=event_name)
  except Event.DoesNotExist:
    raise Http404('Event does not exist')
  try:
    feedback = Feedback.objects.get(applicant=applicant, scholar=request.user.mcuser)
  except Feedback.DoesNotExist:
    feedback = Feedback()
    feedback.applicant = applicant
    feedback.scholar = request.user.mcuser
  if request.method == 'POST':
    form = FeedbackForm(request.POST, instance=feedback)
    if (form.is_valid()):
      form.save()
      if request.is_ajax():
        return JsonResponse({'msg': 'saved successfully'})
      return redirect('feedback:index', event_name)
  else:
    form = FeedbackForm(instance=feedback)
  all_feedback = Feedback.objects.filter(applicant=applicant)
  is_interviewer = request.user.mcuser in event.interviewers.all()
  is_assigned = Assignment.objects.filter(scholar=request.user.mcuser, applicant=applicant).exists()

  context = {
      'feedback': all_feedback,
      'applicant': applicant,
      'form': form,
      'state': get_state(),
      'event_name': event_name,
      'survey_link': event.survey_link,
      'is_interviewer': is_interviewer and is_assigned,
      'favorited': favorited(request.user.mcuser, applicant)
      }
  return render(request, 'feedback/applicant.html', context)
コード例 #46
0
ファイル: views.py プロジェクト: truongsinh/tykes
def add(request):
	if request.method == "POST":
		form = FeedbackForm(request.POST)
		
		if form.is_valid():
			if request.user.is_authenticated(): form.instance.user = request.user
			else: form.instance.user = None
			if 'HTTP_REFERER' in request.META:
				form.instance.context = request.META['HTTP_REFERER']
			form.save()
			return HttpResponse('', mimetype="text/plain")
		else:
			logger.debug(form.errors)
			error_msg = []
			for field in form.errors:
				for error in form.errors[field]:
					error_msg.append('%s: %s' % (form.fields[field].label, error))
			error_msg = '\n'.join(error_msg)
			
			return HttpResponseBadRequest(error_msg, mimetype="text/plain")
	else:
		return HttpResponseNotAllowed(["POST",])
コード例 #47
0
ファイル: views.py プロジェクト: mwotil/nuaza
def rate_user(request, product_slug, template_name="pdcts/rate_user.html"):
    page_title = "Rate User"
    if request.method == 'POST':
        form = FeedbackForm(request.POST)
        p = get_object_or_404(Product, slug=product_slug)

        check = Feedback.objects.filter(user=request.user, product=p)
        own_check = Feedback.objects.filter(user=p.user)

        if form.is_valid():

            if check or own_check:
                chck = "You can only rate this user once for this Product"
                own_chck = "You can't rate yourself"
                form = FeedbackForm()

            else:

                rate = form.save(commit=False)
                rate.user = request.user
                rate.product = p
                rate.save()

                reputation = User_Reputation.objects.filter(user=p.user)

                if reputation:
                    r = User_Reputation.objects.get(user=p.user)

                    alpha = rate.rating

                    beta = 1 - alpha
                    repute = r.reputation
                    entity_alpha = r.entity_alpha
                    entity_beta = r.entity_beta
                    votes = r.votes
                    entity_alpha += alpha
                    entity_beta += beta
                    votes += 1
                    entity_reputation = (entity_alpha /
                                         (entity_alpha + entity_beta))

                    new_repute = (repute + entity_reputation) / 2

                    r.reputation = new_repute
                    r.votes = votes
                    r.entity_alpha = entity_alpha
                    r.entity_beta = entity_beta
                    r.save()

                else:
                    r = User_Reputation()
                    r.user = p.user
                    r.reputation = 0.5
                    r.entity_alpha = 0.5
                    r.entity_beta = 0.5
                    r.votes = 0
                    r.save()

                return HttpResponseRedirect('/home/')

    else:
        form = FeedbackForm()
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))