Exemple #1
0
def pubcomment(request):
    if request.method == "POST":
        comment = CommentForm(data=request.POST)
        if comment.is_valid():
            new_comment = comment.save(commit=False)
            urr = request.META.get("HTTP_REFERER")#http://127.0.0.1:8000/blog/2016/06/06/ZY/
            #ur = urr.split("live/")[1]#2016/06/06/ZY/
            ur = urr.split(":8000/")[1]#2016/06/06/ZY/
            data = ur.split("/")
            year = data[0]
            month = data[1]
            day = data[2]
            slug = data[3]
            post = get_object_or_404(Post, slug=slug, created__year=year, created__month=month, created__day=day)
            new_comment.post = post
            c = request.COOKIES.get("email")
            if c:
                email = request.get_signed_cookie("email",salt="color")
                if email:
                    new_comment.email = email
                    new_comment.save()
                    return HttpResponsePermanentRedirect("/" + ur + "#wgw")
                else:
                    return HttpResponsePermanentRedirect("/login")
            else:
                return HttpResponsePermanentRedirect("/login")
        else:
            return render(request,"404.html")
    else:
        return render(request,"404.html")
Exemple #2
0
def remove_from_cart(request, id):
    try:
        the_id = request.session['cart_id']
        cart = Cart.objects.get(id=the_id)
    except:
        return HttpResponsePermanentRedirect(reverse('cart'))
    cartitem = CartItem.objects.get(id=id)
    # cartitem.delete()
    cartitem.cart = None
    cartitem.save()
    return HttpResponsePermanentRedirect(reverse('cart'))
def listCreate_commit(request):
    if request.method == 'POST':
        comit_form = CommitModelFrom(request.POST, request.FILES)
        if comit_form.is_valid():
            comit_obj= comit_form.save(commit=False)
            comit_obj.author = request.user
            comit_obj.save()
            return HttpResponsePermanentRedirect('/articles/view/{}/'.format(
                comit_obj.article.id
            ))
    return HttpResponsePermanentRedirect(request, '/articles/', )
Exemple #4
0
def register(request):
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            email = data.get("email")
            re = User.objects.filter(email=email)
            if len(re):
                for u in re:
                    if u.if_use:
                        messages.info(request,"该邮箱已被注册")
                    else:
                        u.delete()
                        passwd = data.get("passwd")
                        hash_pw = make_password(passwd)
                        user = User.objects.create(email=email, passwd=hash_pw)
                        user.save()
                        token = token_confirm.generate_validate_token(email)
                        link = '/'.join([settings.DOMAIN, 'activate', token])
                        data = {"email": email, "link": link}
                        email_message = loader.render_to_string("re_email.html", data)
                        title = "注册用户验证信息"
                        from_mail = settings.EMAIL_HOST_USER
                        get_mail = [email]
                        send_mail = Send_mail_thread(title, email_message, from_mail, get_mail)
                        send_mail.start()
                        messages.info(request, "欢迎注册,请登录自己的邮箱进行验证")
                return HttpResponsePermanentRedirect("/Reuser")#用户已存在
            else:
                passwd = data.get("passwd")
                hash_pw = make_password(passwd)
                user = User.objects.create(email=email,passwd = hash_pw)
                user.save()
                token = token_confirm.generate_validate_token(email)
                link = '/'.join([settings.DOMAIN,'activate',token])
                title = "注册用户验证信息"
                from_mail = settings.EMAIL_HOST_USER
                get_mail = [email]
                data = {"email":email,"link": link}
                email_message = loader.render_to_string("re_email.html", data)
                send_mail = Send_mail_thread(title, email_message, from_mail, get_mail)
                send_mail.start()
                messages.info(request, "欢迎注册,请登录自己的邮箱进行验证")
                return HttpResponsePermanentRedirect("/Reuser")
        else:
            messages.info(request,"邮箱或者密码格式不正确")
            return HttpResponsePermanentRedirect("/Reuser")#邮箱或者密码格式不正确
    else:
        return render(request,"404.html")
def upload_csv(request):
    if request.user.force_change == True:
        return redirect("change_password")
    else:
        data = {}
        current_user = request.user
        if current_user.u_permission_level == "2":
            if "GET" == request.method:
                return render(request, "upload_csv.html", data)
            try:
                csv_file = request.FILES["csv_file"]
                if not csv_file.name.endswith(".csv"):
                    messages.error(request, "File is not the correct type")
                    return HttpResponsePermanentRedirect(reverse("upload_csv"))
                if csv_file.multiple_chunks():
                    print("FILE SIZE IS TOO LARGE")
                    return HttpResponsePermanentRedirect(reverse("upload_csv"))
                file_data = csv_file.read().decode("utf-8")

                lines = file_data.split("\n")
                for line in lines:
                    fields = line.split(",")
                    data_dict = {}
                    data_dict["t_opened"] = fields[0]
                    data_dict["c_name"] = fields[1]
                    data_dict["t_subject"] = fields[2]
                    data_dict["t_status"] = fields[3]
                    data_dict["t_assigned"] = fields[4]
                    data_dict["t_closed"] = fields[6]
                    try:
                        user = get_user_model()
                        user = user.objects.filter(u_permission_level=2)
                        form = TicketForm(data_dict, t_choices=user)
                        print("FORM: {0} | DATA_DICT: {1}".format(
                            form, data_dict))
                        if form.is_valid():
                            print("We saved the ticket?")
                            form.save()
                        else:
                            print("error saving csv")
                    except Exception as e:
                        print("ERROR: {}".format(e))
                        pass
            except Exception as e:
                print("OUTER ERROR: {}".format(e))

            return HttpResponsePermanentRedirect(reverse("upload_csv"))
        else:
            return redirect("ticketing_index")
Exemple #6
0
def contact(request):
    url = request.META.get('HTTP_REFERER')
    current_user = request.user
    cart_product = Shop_Cart.objects.filter(user_id=current_user.id)
    total_amount = 0
    for p in cart_product:
        total_amount += p.product.new_price * p.quantity
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            data = ContactMessage()
            data.name = form.cleaned_data['name']
            data.email = form.cleaned_data['email']
            data.subject = form.cleaned_data['subject']
            data.message = form.cleaned_data['message']
            data.ip = request.META.get('REMOTE_ADDR')
            data.save()

            messages.success(
                request,
                '  Your Product Has Been Added Successfully To Cart  ')
            return HttpResponsePermanentRedirect(url)

    setting = ProjectSetting.objects.get(pk=1)
    form = ContactForm
    category = Category.objects.all()
    context = {
        'setting': setting,
        'form': form,
        'category': category,
        'total_amount': total_amount,
        'cart_product': cart_product,
    }

    return render(request, 'contact_form.html', context)
Exemple #7
0
def approve(request):
    body = request.POST
    fond = models.Fond.objects.get(uid=body["localId"])
    print(fond)
    fond.published = True
    fond.save()
    return HttpResponsePermanentRedirect('http://demo3.echo.vkhackathon.com:8000/moder')
Exemple #8
0
def post_create(request):

    if not request.user.is_authenticated:
        raise Http404()

    #if request.method == "POST":
    #print(request.POST)

    #title = request.POST.get('title')
    #content = request.POST.get('content')
    #Post.objects.Create(title=title, content=content)

    #if request.method == "POST":
    #    #formdan gelen bilgileri kaydet
    #    form = PostForm(request.POST)
    #    if form.is_valid():
    #        form.save()
    #else:
    #    #formu kullanıcıya göster
    #    form = PostForm()

    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        post = form.save(commit=False)
        post.user = request.user
        post.save()
        messages.success(request, 'Başarılı bir şekilde oluşturdunuz.')
        return HttpResponsePermanentRedirect(post.get_absolute_url())

    context = {
        'form': form,
    }
    return render(request, 'post/form.html', context)
Exemple #9
0
def student_set_new_password(request):
    logout(request)
    error_message = None
    password_update_failed = None
    if request.method == 'POST':
        new_password = request.POST['new_password']
        retyped_new_password = request.POST['retyped_new_password']
        recipient_username = request.POST['student_id']
        properly_formatted_recipient_username = properly_format_student_id(
            recipient_username)
        user = User.objects.get(username=properly_formatted_recipient_username)
        if (new_password != retyped_new_password) and (new_password != ''):
            password_update_failed = True
            error_message = 'The New Password fields does not match!'
        elif (user.first_name.lower() or user.last_name.lower()
              or user.student.middleName.lower()) == new_password.lower():
            password_update_failed = True
            error_message = 'Your new password should not be too similar to your other Personal information!'
        elif re.match(r'[0-9]+', new_password):
            password_update_failed = True
            error_message = 'Your password cannot be entirely numeric!'
        elif user.email == new_password:
            password_update_failed = True
            error_message = 'Your new password is too similar to your email address!'
        elif new_password == retyped_new_password:
            user.set_password(new_password)
            user.save()
            return HttpResponsePermanentRedirect(
                '/student/student_password_reset_complete')
    context = {
        'password_update_failed': password_update_failed,
        'error_message': error_message,
        'student_id': recipient_username
    }
    return render(request, 'student/student_set_new_password.html', context)
def flatpage(request, url, extra_context=None):
    """
    Public interface to the flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or :template:`flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not url.startswith('/'):
        url = '/' + url
    site_id = get_current_site(request).id
    try:
        f = get_object_or_404(FlatPage,
                              url__exact=url,
                              sites__id__exact=site_id)
    except Http404:
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'
            return HttpResponsePermanentRedirect('%s/' % request.path)
        else:
            raise
    return render_flatpage(request, f, extra_context)
Exemple #11
0
def post_detail(request, day, month, year, post):
    post = get_object_or_404(Post, slug=post, status='published', publish__year=year,
                             publish__month=month, publish__day=day)

    # Список активных комментариев
    comments = post.comments.filter(active=True)
    new_comment = None
    if request.method == 'POST':
        # Пользователь отправил комментарий
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # Создаем комментарий, но не сохранем его
            new_comment = comment_form.save(commit=False)
            # Привязываем комментарий к статье
            new_comment.post = post
            # Сохраняем комментарий в базе данных
            new_comment.save()
            return HttpResponsePermanentRedirect('/blog/')      # Добавить пересылку на эту же статью!!
    else:
        comment_form = CommentForm()

    post_tags_ids = post.tags.values_list('id', flat=True)
    similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
    similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]
    return render(request, 'blog/post/detail.html',
                  {'post': post,
                   'comments': comments,
                   'new_comment': new_comment,
                   'comment_form': comment_form,
                   'similar_posts': similar_posts})
Exemple #12
0
def home(request, page=None):
    if request.get_host() != 'www.kantujun.com':
        return HttpResponsePermanentRedirect('http://www.kantujun.com')
    if page is None:
        page = 1
        start = 0
        end = 5
    else:
        page = int(page)
        start = (page - 1) * 5
        end = page * 5
    item_count = Article.objects.count()
    get_articles = Article.objects.order_by('-create_time').all()[start:end]
    data = []
    for i in get_articles:
        data.append({
            'title': i.title,
            'cover': i.cover,
            'description': i.description,
            'create_time': i.create_time,
            'author': i.author,
            'id': i.id
        })
    return render(
        request, 'index.html', {
            'index': 1,
            'data': data,
            'current_page': page,
            'item_count': item_count,
            'title': u'豆瓣妹子福利 - 知乎福利'
        })
def signupview(request):
    form = signupform(
        request.POST
        or None)  #we import class signupform and create form as an object
    if request.method == 'GET':
        return render(request, 'signup.html', {'form': form})
    elif request.method == 'POST':
        form = signupform(request.POST or None)
        if form.is_valid():  # is_valid used for fill all the field
            username = form.cleaned_data.get("username")
            email = form.cleaned_data.get("email")
            password = form.cleaned_data.get("password")
            user = User.objects.create_user(username=username,
                                            email=email,
                                            password=password)
            user.set_password(password)
            user.is_active = True
            user.save()
            user = authenticate(username=username,
                                password=password,
                                email=email)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponsePermanentRedirect(
                        reverse('userpro'))  # here userpro is an app name
                    # It is the power of name and namespase
        else:
            print(form.errors)
            return render(request, 'signup.html', {'form': form})

    else:
        return render(request, 'signup.html', {'form': form})
Exemple #14
0
def update_tutor_password(request):
    try:
        if request.user.tutor:
            password_update_failed = False
            error_message = None
            if request.method == 'POST':
                old_password = request.POST['current_password']
                new_password = request.POST['new_password']
                retyped_new_password = request.POST['retyped_new_password']
                user = request.user
                if new_password != retyped_new_password:
                    password_update_failed = True
                    error_message = 'The New Password fields does not match!'
                elif not user.check_password(old_password):
                    password_update_failed = True
                    error_message = 'Current Password typed is incorrect'
                elif (user.first_name.lower() or user.last_name.lower() or user.tutor.middle_name.lower()) == new_password.lower():
                    password_update_failed = True
                    error_message = 'Your new password should not be too similar to your other Personal information!'
                elif re.match(r'[0-9]+', new_password):
                    password_update_failed = True
                    error_message = 'Your password cannot be entirely numeric!'
                elif user.email == new_password:
                    password_update_failed = True
                    error_message = 'Your new password is too similar to your email address!'
                else:
                    user.set_password(new_password)
                    user.save()
                    logout(request)
                    return HttpResponsePermanentRedirect('/tutor/password_update_successful')
            context = {'password_update_failed': password_update_failed, 'password_update_error_message': error_message}
            return render(request, 'tutor/tutor_password_update.html', context)
    except Exception:
        logout(request)
        return redirect('/tutor/tutor_change_password/')
Exemple #15
0
def login_start_baidu(request):
    """ a method that loads config and redirect to Google
    """

    site = SocialSites(SOCIALOAUTH_SITES).get_site_object_by_name('baidu')
    authorize_url = site.authorize_url
    return HttpResponsePermanentRedirect(authorize_url)
Exemple #16
0
def authenticating(request):
    error_message = None
    submited_username = None
    if request.POST:
        tutor_number = request.POST['username']
        password = request.POST['password']
        next_url = request.POST['next']
        TUTOR = authenticate(username=properly_format_tutor_number(tutor_number), password=password)
        if TUTOR is not None:
            if TUTOR.is_active:
                login(request, TUTOR)

                # The Tutor's charge/hour is calculated here, just before the dashboard loads
                user = request.user
                tutor = user.tutor

                update_tutor_profile(tutor)

                # At this point, the Tutor's charge has been updated and saved to database
                # before redirecting to the next url

                return HttpResponsePermanentRedirect(next_url)
            else:
                error_message = 'Sorry, but this Account has been deleted!'
        else:
            error_message = 'Invalid Tutor Info'
            submited_username = tutor_number

    if request.GET:
        next_url = request.GET['next']
    else:
        next_url = '/tutor/dashboard/'
    context = {'error_message': error_message, 'next_url': next_url, 'submited_username': submited_username}
    return render(request, 'tutor/tutor_sign_in.html', context)
Exemple #17
0
def redirect(request, slug):
    url = URL.objects.filter(slug=slug).first()
    if not url:
        return HttpResponse(status=404)
    if url.ref_type == 'header':
        return HttpResponsePermanentRedirect(url.full)
    return TemplateResponse(request, 'redirect.html', {"href": url.full})
Exemple #18
0
def redirect(request, unique_code):
    base_url = 'http://' + request.get_host() + '/'
    try:
        o = URLToUniqueCode.objects.get(unique_code=unique_code)
        return HttpResponsePermanentRedirect(o.url)
    except URLToUniqueCode.DoesNotExist:
        return HttpResponse(base_url + unique_code + ' does not exist!!!')
Exemple #19
0
def create_fond(request):
    body = request.POST
    #  Saving POST'ed file to storage
    # print(request.FILES.getlist('logo'))
    logo_file = request.FILES.get('logo')
    back_file = request.FILES.get('back')
    # print(request.FILES)
    logo_file_name = default_storage.save(logo_file.name, logo_file)
    back_file_name = default_storage.save(back_file.name, back_file)
    print(body['name'])
    fond = models.Fond(
        name=body['name'],
        description=body['description'],
        email=body['email'],
        logo_url='http://demo3.echo.vkhackathon.com:8000/media/' + logo_file_name + '/',
        background_url='http://demo3.echo.vkhackathon.com:8000/media/' + back_file_name + '/',
        site_url=body['site_url'],
        inn=body['inn'],
        address=body['address'],
        post_address=body['post_address'],
        bank_name=body['bank_name'],
        settlment_account=body['settlment_account'],
        cor_account=body['cor_account'],
        bic=body['bic'],
        kpp=body['kpp']
    )
    fond.save()
    return HttpResponsePermanentRedirect('http://demo3.echo.vkhackathon.com:8000/')
Exemple #20
0
def auth_view(request):
    """
    Recibe los parametros username y password de request.POST.
    Seguidamente se guarda en user, para luego corroborar si existe en la
    base de datos, si existe entonces se ingresa, sino se muestra un mensaje de advertencia

    """
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = authenticate(username=username, password=password)

    if user is not None:
        login(request, user)
        return HttpResponsePermanentRedirect('/index')
    else:
        return HttpResponsePermanentRedirect('/invalid')
Exemple #21
0
def redirect(request, source):
    sink = get_object_or_404(Redirect, source__iexact=source)
    sink.usages += 1
    sink.save()
    if sink.permanent:
        return HttpResponsePermanentRedirect(sink.sink)
    else:
        return HttpResponseRedirect(sink.sink)
Exemple #22
0
def add_author(request):
    if request.method == "POST":
        form = AddAuthorForm(request.POST)
        form.save()
        return HttpResponsePermanentRedirect(reverse("homepage"))

    form = AddAuthorForm()
    return render(request, "generic_form.html", {"form": form})
Exemple #23
0
def logout_handler(request):
    """ Логаут пользователя

        :form redirect_to: урл на который сделать редирект после логаута, по умолчанию - текущая страница
    """
    if request.user.is_authenticated():
        logout(request)
    redirect_to = request.POST.get('redirect_to', '/')
    return HttpResponsePermanentRedirect(redirect_to)
Exemple #24
0
 def post(self, request):
     fm = StudentRegistration(request.POST)
     if fm.is_valid():
         nm = fm.cleaned_data['name']
         em = fm.cleaned_data['email']
         pw = fm.cleaned_data['password']
         reg = User(name=nm, email=em, password=pw)
         reg.save()
         return HttpResponsePermanentRedirect('/')
Exemple #25
0
def update_view(request, id):
    posts = get_object_or_404(post, id=id)
    form = PostForm(request.POST or None, instance=posts)
    if form.is_valid():

        form.save()
        messages.success(request, "Post Edit Successfuly")
        return HttpResponsePermanentRedirect(posts.get_absolute_url())
    context = {'form': form}
    return render(request, 'post/form.html', context)
Exemple #26
0
def add_to_cart(request, slug):
    # request.session.set_expiry(12000)
    try:
        the_id = request.session['cart_id']

    except:

        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        the_id = new_cart.id

    cart = Cart.objects.get(id=the_id)
    try:
        product = Product.objects.get(slug=slug)
    except Product.ObjectDoesNotExist:
        pass
    except:
        pass
    product_var = []
    if request.method == 'POST':
        qty = request.POST['qty']

        for item in request.POST:
            key = item
            val = request.POST[key]
            try:
                v = Variation.objects.get(product=product,
                                          category__iexact=key,
                                          title__iexact=val)
                product_var.append(v)

            except:
                pass
        cart_item = CartItem.objects.create(cart=cart, product=product)
        if len(product_var) > 0:
            cart_item.variations.add(*product_var)
        cart_item.quantity = qty
        cart_item.save()
        return HttpResponsePermanentRedirect(reverse('cart'))

    return HttpResponsePermanentRedirect(reverse('cart'))
Exemple #27
0
def redirect_search(request, search_type, options=None):
    if not options:
        options = ()
    q = request.REQUEST.get('q', '')
    order = request.REQUEST.get('sort_by', '')
    url = '/?type=%s&q=%s&filter=%s&order=%s' % (search_type, q, ''.join([
        '&%s=%s' % (opt_key.replace('-', '_'), request.REQUEST.get(opt_key))
        for opt_key in options
    ]), order)

    return HttpResponsePermanentRedirect(url)
Exemple #28
0
def update_view(request, id):
    post = get_object_or_404(Post, id=id)
    form = PostForm(request.POST or None, request.FILES or None, instance=post)

    if form.is_valid():
        post.save()
        return HttpResponsePermanentRedirect(post.get_absolute_url())

    context = {'form': form}

    return render(request, 'posts/create.html', context)
Exemple #29
0
def create_view(request):
    form = PostForm(request.POST or None, request.FILES or None)

    if form.is_valid():
        post = form.save()
        messages.success(request, "Your post has been saved")
        return HttpResponsePermanentRedirect(post.get_absolute_url())

    context = {'form': form}

    return render(request, 'posts/create.html', context)
Exemple #30
0
def index(request):
     """
     Si request.user estar auntenticado muestra un mensaje de bienvenida para ese usuario.
     sino se redirige a login para volver a introducir los datos


     """
     if request.user.is_authenticated() and request.user.is_active == True:
         return render_to_response('administracion/index.html', {'full_name': request.user.username})
     else:
         return HttpResponsePermanentRedirect('/login')