Exemplo n.º 1
0
def post_Estate(request):
    EstateImageFormSet = modelformset_factory(EstateImage,
                            form = EstateImageForm, extra = 3)

    if request.method == 'POST':
        estateForm = EstateForm(request.POST)
        formset = EstateImageFormSet(request.POST, request.FILES, queryset = EstateImage.objects.none())

        if estateForm.is_valid() and formset.is_valid():

            estate_form = estateForm.save(commit=False)
            estate_form.save()

            for form in formset.cleaned_data:
                image = form['image']
                photo = EstateImage(estate=estate_form,image=image)
                photo.save()
            messages.succes(request,"Post succesfull.")
            return HttpResponseRedirect("/")

        else:
            print estateForm.errors , formset.errors
    else:
        estateForm = EstateForm()
        formset = EstateImageFormSet(queryset=EstateImage.objects.none())

    return render(request, 'websiteSofie/postpand.html', {'estateForm': estateForm, 'formset': formset},)
Exemplo n.º 2
0
 def delete(
     self,
     *arg,
     **kwargs,
 ):
     messages.succes(self.request, 'Post Deleted')
     return super().delete(*args, **kwargs)
Exemplo n.º 3
0
def post_new(request):
    if request.method == 'GET':
        form = MenuForm()
    elif request.method == 'POST':
        form = MenuForm(data=request.POST)
        # import ipdb; ipdb.set_trace();
        if form.is_valid():
            form.save()
            messages.succes(request, "Comanda a fost adaugata cu succes!")
        else:
            # pass
            messages.error(request, "Nu ati completat corect!")
    return render(request, 'restaurant/post_edit.html', {'form': form})
Exemplo n.º 4
0
def checkout_request(request, order_number):
    save_info = request.session.get('save_info')
    order = get_object_or_404(order_number=order_number)
    messages.succes(request, f'Order succesfully processed! \
        Your order number is{order_number}. A confirmation \
        email will be sent to {order.email}.')

    if 'bag' in request.session:
        del request.session['bag']

    template = 'checkout/checkout_success.html'
    context = {
        'order': order,
    }

    return render(request, template, context)
Exemplo n.º 5
0
def change_password(request):
    if request.method =='POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.succes(request, 'Your password was successfuly updated!')
            return HttpResponseRedirect('/user')
        else:
            messages.error(request, "Please correct the error below <br>"+str(form.errors))
            return HttpResponseRedirect('/user/password')
    else:
        category = Category.objects.all()
        form = PasswordChangeForm(request.user)
        return render(request, 'change_password.html', {
            'form': form, 'category': category
        })
Exemplo n.º 6
0
    def post(self, request, *args, **kwargs):
        if not self.request.user.is_authenticated():
            messages.error(self.request, 'Faça login para Responder')
            return redirect(self.request.path)
        else:
            self.object = self.get_object()
            context = self.get_context_data(object=self.object)
            form = context['form']
            if form.is_valid():
                reply = form.save(commit=False)
                reply.thread = self.object
                reply.author = self.request.user
                reply.save()
                messages.succes(request, 'Resposta enviada com sucesso!')
                context['form'] = ReplyForm()

        return self.render_to_response(context)
Exemplo n.º 7
0
def import_user(request, uidb64, token):
    """
    View which handles the importing of the legacy user to the new website. Uses the information
    from the unique link to determine the user and verifies this link belongs to them using the
    token. Redirects the user to the account creation page with filled in information, as there
    may be stricter requirements on the supplied information, and a new password needs to be
    chosen.
    """
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        old_user = AuthUser.objects.get(username=uid)
    except (TypeError, ValueError, OverflowError, AuthUser.DoesNotExist):
        old_user = None

    if (old_user is not None
            and account_import_token.check_token(old_user, token)
            and not Profile.objects.filter(user__username=uid).exists()):
        if request.method == "POST":
            user_form = MemberCreateForm(request.POST, instance=request.user)
            profile_form = ProfileCreateForm(request.POST,
                                             instance=request.user.profile)
            if user_form.is_valid() and profile_form.is_valid():
                user_form.save()
                profile_form.save()
                messages.succes(request, "Account imported succesfully!")
                return redirect("import_user")
        else:
            user_data = {
                "first_name": old_user.first_name,
                "last_name": old_user.last_name,
                "username": old_user.username,
                "email": old_user.email,
            }
            profile_data = {
                "nationality": old_user.mysiteprofile.nationality,
                "department": old_user.mysiteprofile.department,
                "program": old_user.mysiteprofile.program,
            }
            user_form = MemberCreateForm(initial=user_data)
            profile_form = ProfileCreateForm(initial=profile_data)
        return render(request, "user/register.html", {
            "user_form": user_form,
            "profile_form": profile_form
        })
    else:
        return HttpResponse("Account import link is invalid!")
Exemplo n.º 8
0
def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        user = auth.authenticate(username=username, password=password)

        if user is not None:
            auth.login(request, user)
            messages.succes(request, 'You are now logged in')
            return redirect('dashboard')
        else:
            mesages.error(request, 'Invalid credentials')
            return redirect('login')

    else:
        return render(request, 'accounts/login.html')
Exemplo n.º 9
0
def addi(request):
	messages.success(request, "that's a start")
	if request.POST == "POST":
		message.succes(request, "Au moins t'as fait ton form")
		my_form = (request.POST.get("name", ""), request.POST.get("group2", ""),request.POST.get("group1", ""),request.POST.get("descritpion", ""))
		message.succes(request, "Au moins t'as fait ton form")
		if my_form.is_valid():
			new_Book = Book(book_name=request.POST.get("name", ""),book_owner =request.POST.get("group2", ""), book_availibility="Availible",book_category=request.POST.get("group1", ""), book_description=request.POST.get("descritpion", ""))
			new_Book.save()
			messages.succes(request, "The book was successfully added")
			return redirect("/")
		else:
			message.error(request, "t'as faux sale merde")
			return redirect("/")
	return render(request=request,
				  template_name="main/add.html",context={"category": Category.objects.all
				  ,"owner": Owner.objects.all}
				  )
Exemplo n.º 10
0
def profile(request, username):
    if request.method == 'POST':
        imageForm = ProfileImageForm(request.POST)
        if imageForm.is_valid():
            image = imageForm.cleaned_data["image"]
            user = User.objects.get(username=username)
            game_sprout = GameSprout.objects.get(user=user)
            game_sprout.image = image
            game_sprout.save()
            messages.succes(request, "<strong>Profile image updated!</strong> congratulations, you interneted!", extra_tags="alert alert-success fade in")

    imageForm = ProfileImageForm()
    has_reviews = True
    reviews = []
    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        messages.add_message(request, messages.INFO, "<strong>Sorry duder</strong> that user couldn't be found, you probably typed it wrong... yeah that's what it is, it's your fault. Contact admin if your sure you're right. Buy you're probably wrong. Just sayin'", extra_tags="alert alert-warning fade in")
        redirect('home')
    try:
        game_sprout = GameSprout.objects.get(user=user)
    except GameSprout.DoesNotExist:
        messages.add_message(request, messages.INFO, "<strong>Sorry duder</strong> that user couldn't be found, weird... If this keeps happening erroneously contact admin.", extra_tags="alert alert-warning fade in")
        redirect('home')

    # get user's reviews
    reviews = Review.objects.filter(reviewer=user).order_by('publish_date',)
    # if there are no reviews set flag so message can be diplayed
    if not reviews:
        has_reviews = False

    form = SearchForm()

    context = {
        'form' : form,
        'user' : request.user,
        'profile_user' : user,
        'game_sprout' : game_sprout,
        'has_reviews' : has_reviews,
        'reviews' : reviews,
        'imageForm' : imageForm,
    }

    return render(request, "GameBean/profile.html", context)
Exemplo n.º 11
0
def register(request):
    if request.method == 'POST':
        form = request.User

        #if form.is_valid():
        USERNAME = form.get('username')
        PASSWORD = form.get('password')
        user = Player.objects.create(username=USERNAME,
                                     password=PASSWORD,
                                     rating=1500)
        messages.succes(request, f'Account created for {username}')

    else:
        #form = formid()
        pass

    context = {'username': request.user}

    return render(request, 'login/regist.html', context)
Exemplo n.º 12
0
def register_user(request):
    if request.method == 'POST':
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        username = request.POST['username']
        email = request.POST['email']
        password = request.POST['password']
        password2 = request.POST['password2']
        password_min = 6

        if len(password) < password_min:
            messages.error(
                request,
                'Your Password is Too Short, Please choose a password at least 6 characters long!'
            )
            return redirect('register_user')
        else:
            if password == password2:
                if User.objects.filter(username=username).exists():
                    messages.error(request, 'Username Already Exists')
                    return redirect('register_user')
                else:
                    if User.objects.filter(email=email).exists():
                        messages.error(request, 'Email Already Exists!')
                        return redirect('register_user')
                    else:
                        user = User.objects.create_user(first_name=first_name,
                                                        last_name=last_name,
                                                        username=username,
                                                        password=password)
                        auth.login(request, user)
                        messages.success(request, 'you are now logged in')
                        return redirect('dashboard')
                        user.save()
                        messages.succes(
                            request, 'Account Successfully Created. Welcome')
                        return redirect('index')
            else:
                messages.error(request, 'Passwords Do Not Match!')
                return redirect('register_user')
    else:
        return render(request, 'pages/register.html')
Exemplo n.º 13
0
def remove_from_cart(request, slug):
    item = get_object_or_404(Item, slug=slug)
    order_qs = OrderItem.objects.filter(user=request.user, ordered=False)

    if order_qs.exists():
        order = order_qs[0]
        if order.items.filter(item__slug=item.slug).exists():
            order_item = OrderItem.objects.filter(item=item,
                                                  user=request.user,
                                                  ordered=False)[0]

            order.items.remove(order_item)
            messages.succes(request, "This item was remove from your Cart")
        else:
            # add a message saying order doesnot contain the item
            messages.info(request, "This item was not in your Cart")
            return redirect('core:item-detail', slug=slug)
    else:
        # add a message saying no orders
        messages.info(request, "Your doesnot have an active order")
        return redirect('core:item-detail', slug=slug)
    return redirect('core:item-detail', slug=slug)
Exemplo n.º 14
0
    def post(self, *args, **kwargs):
        order = Order.objects.get(user=self.request.user, ordered=False)
        form = PaymentForm(self.request.POST)
        userprofile = UserProfile.objects.get(user=self.request.user)
        if form.is_valid():
            token = form.cleaned_data.get('stripeToken')
            save = form.cleaned_data.get('save')
            use_default = form.cleaned_data.get('use_default')

            if save:
                if not userprofile.stripe_customer_id:
                    customer = stripe.Customer.create(
                        email=self.request.user.email, source=token)
                    userprofile.stripe_customer_id = customer['id']
                    userprofile.one_click_purchasing = True
                    userprofile.save()
                else:
                    stripe.Customer.create_source(
                        userprofile.stripe_customer_id, source=token)

        amount = int(order.get_total() * 100)

        try:

            if use_default:
                charge = stripe.Charge.create(
                    amount=amount,
                    currency="usd",
                    customer=userprofile.stripe_customer_id)
            else:
                charge = stripe.Charge.create(
                    amount=amount,  # cents
                    currency="usd",
                    source=token)

            payment = Payment()
            payment.stripe_charge_id = charge['id']
            payment.user = self.request.user
            payment.amount = order.get_total()
            payment.save()

            order_items = order.items.all()
            order_items.update(ordered=True)
            for item in order_items:
                item.save()

            order.ordered = True
            order.payment = payment
            order.ref_code = create_ref_code()
            order.save()

            messages.succes(self.request, "Your order was successful!")
            return redirect("/")

        except stripe.error.CardError as e:
            # Since it's a decline, stripe.error.CardError will be caught
            body = e.json_body
            err = body.get('error', {})
            messages.warning(self.request, f"{err.get('message')}")
            return redirect("/")

        except stripe.error.RateLimitError as e:
            # Too many requests made to the API too quickly
            messages.warning(self.request, "Rate limit error")
            return redirect("/")

        except stripe.error.InvalidRequestError as e:
            # Invalid parameters were supplied to Stripe's API
            messages.warning(self.request, "Invalid Parameters")
            return redirect("/")

        except stripe.error.AuthenticationError as e:
            # Authentication with Stripe's API failed
            # (maybe you changed API keys recently)
            messages.warning(self.request, "Not Authenticated")
            return redirect("/")

        except stripe.error.APIConnectionError as e:
            # Network communication with Stripe failed
            messages.warning(self.request, "Network error")
            return redirect("/")

        except stripe.error.StripeError as e:
            # Display a very generic error to the user, and maybe send
            # yourself an email
            messages.warning(
                self.request,
                "Something went wrong. You were not charged. Please try again")
            return redirect("/")

        except Exception as e:
            # Something else happened, completely unrelated to Stripe
            messages.warning(
                self.request,
                "A serious error ocurred. We have been notified.")
            return redirect("/")
Exemplo n.º 15
0
def logout(request):
    if request.method == 'POST':
        auth.logout(request)
        messages.succes(request, 'You are now logged out')
        return redirect('index')