Django-Ajax giving error "Method Not Allowed (POST): /post/like/" - python

I am new to django i am using ajax and django for very first time. I have tried by best to search here and there but i couldn't get to solution
this answer didn't help as well
Django and ajax request Method Not Allowed (POST)
the error i am getting is
Method Not Allowed (POST): /post/like/
[07/Jun/2019 16:06:16] "POST /post/like/ HTTP/1.1" 405 0
below are the codes
likes_section.html
{% if request.user.is_authenticated %}
<form action="{% url 'like_post' %}" method="post">
{% csrf_token %}
{% if is_liked %}
<span class="mr-2" style="color:black;">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}">DisLike</button></span>
{% else %}
<span class="mr-2" style="color:black;">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}">Like</button></span>
{% endif %}
</form>
{% else %}
<span class="mr-2">{{ post.total_likes }} Like{{ post.total_likes|pluralize }}<button type="submit" id="like_the_post_by_user" class="btn btn-primary ml-2" name="post_id" value="{{ post.id }}" disabled>Like</button>Please Login to enable Like button</span>
{% endif %}
Ajax
$(document).ready(function(event){
$(document).on('click',"#like_the_post_by_user", function(event){
event.preventDefault();
console.log($("#like_the_post_by_user").val())
console.log("from jquery section")
var pk = $(this).attr('value');
$.ajax({
type : "POST",
url : "{% url 'like_post' %}",
data : {'id': pk , "csrfmiddlewaretoken": '{{ csrf_token }}' },
dataType : 'json',
success : function(response){
$('#like-section_user').html(response['form'])
console.log($('#like-section_user').html(response['form']));
},
error : function(rs, e){
console.log(rs.responseText);
}
});
});
});
urls.py
urlpatterns = [
path('', PostListView.as_view(),name="blog-home"),
path('post/<int:pk>/', PostDetailView.as_view(),name="post-detail"),
path('post/new/', PostCreateView.as_view(),name="post-create"),
path('post/<int:pk>/update/', PostUpdateView.as_view(),name="post-update"),
path('post/<int:pk>/delete/', PostDeleteView.as_view(),name="post-delete"),
path('user/<str:username>/', UserPostListView.as_view(),name="user-posts"),
path('post/<str:category>/', CategoryListView.as_view(),name="category-posts"),
path('about/', AboutListView.as_view(),name="about"),
#path('users/myposts/', ActiveUserPostDetailView.as_view(),name="my-blogs"),
path('feedback-email/', views.feedback_email,name="feedback-email"),
path('post/like/', views.like_post,name="like_post"),
]
views.py
def like_post(request):
#post = get_object_or_404(Post,id=request.POST.get("post_id"))
if request.method == 'POST':
print('method is {}'(request.method))
print("\ninside like view\n")
print("\n in {} \n".format(request.POST.get('id')))
post = get_object_or_404(Post,id=request.POST.get("id"))
is_liked = False
if post.likes.filter(id=request.user.id).exists():
print("\ninside like\n")
post.likes.remove(request.user)
is_liked = False
else:
print("\ninside dislike\n")
post.likes.add(request.user)
is_liked = True
comments = Comment.objects.filter(post=post,reply=None).order_by("-id")
context = {
"post":post,
"is_liked":is_liked,
"comment": comments
}
#return redirect("post-detail",pk=request.POST.get("post_id"))
print("\ngetting in ajax\n")
if request.is_ajax():
print("\ninside ajax\n")
html = render_to_string('blog/likes_section.html', context, request=request)
return JsonResponse({"form":html})
any help will be greatly appreciated !
Thanks in advance

Your "/post/like" URL is matching the URL pattern for CategoryListView, since it is "post" plus a string.
As you have done with the post detail view, bring the pattern for the like view earlier in the list of URLs so that it matches first.

Related

"POST /......... / ......... / HTTP/1.1" 405 0 - Django

I have a problem, in my work I need to insert a system of likes to published posts but by clicking on the button that should give the post a like, nothing happens and this error comes out..."POST /posts/like/ HTTP/ 1.1" 405 0
views.py
#ajax_required
#require_POST
#login_required
def post_like(request):
post_id = request.POST.get('id')
action = request.POST.get('action')
if post_id and action:
try:
post = Post.objects.get(id=post_id)
if action == 'like':
post.users_likes.add(request.user)
else:
post.users_likes.remove(request.user)
return JsonResponse({'status': 'ok'})
except:
pass
return JsonResponse({'status': 'error'})
urls.py
from django.urls import path, include
from . import views
app_name = 'posts'
urlpatterns = [
path('like/', views.post_like, name='like'),
]
index.html
{% with total_likes=post.users_likes.count users_likes=post.users_likes.all %}
<div class="post-info">
<div>
<span class="count">
<span class="total">{{ total_likes }}</span>
like{{ total_likes|pluralize }}
</span>
<a href="#" data-id="{{ post.id }}" data-action="{% if request.user in users_likes %}un{% endif %}like" class="like">
{% if request.user not in users_likes %}
Like
{% else %}
Unlike
{% endif %}
</a>
</div>
</div>
<div class="post-likes">
{% for user in users_likes %}
<div>
<p>{{ user.first_name }}</p>
</div>
{% empty %}
<p>No body likes this post yet</p>
{% endfor %}
</div>
{% endwith %}
<p>{{ post.id }}</p>
<a class="normal-text" href="{{ post.get_absolute_url }}">Discover more...</a>
</div>
</div>
ajax code
<script>
{% block domready %}
$('a.like').click(function(e){
e.preventDefault();
$.post("{% url 'posts:like' %}",
{
id: $(this).data('id'),
action: $(this).data('action')
},
function(data){
if (data['status'] == 'ok')
{
var previous_action = $('a.like').data('action');
// toggle data-action
$('a.like').data('action',
previous_action == 'like' ? 'unlike' : 'like');
// toggle link-text
$('a.like').text(
previous_action == 'like' ? 'Unlike' : 'Like');
// update total likes
var previous_likes = parseInt(
$('span.count .total').text());
$('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes -1);
}
}
);
});
{% endblock %}
</script>
I don't understand where the problem is... I thought in the url but I don't think so
From the documentation, it appears that your urls.py is at fault - you define a "like/" pattern, but there's nothing to tell the router that you mean for it to have a "posts/" prefix.
The examples given there explicitly use an include directive to do that, and you do no such thing. Try:
from django.urls import include, path
from . import views
urlpatterns = [
path('posts/', include([
path('like/', views.post_like, name='like'),
# Other posts/... endpoints
])),
# path('users/', include([ ...
]

.is_valid() method but is not validating when ajax used

when i used ajax in my project the form.is_valid() method not validating the form. it showing the 'this field required error' but i access that using request.POST means i fill all the fields.
'''
this is html code which render the django model form
##HTML FORM##
<form action="" method="post" enctype="multipart/form-data" id="reception_form" novalidate> {% csrf_token %}
{% for field1 in form1 %}
<label for="{{field1.id_for_label}}"> {{field1.label}} </label> {{field1}}
<div>
{% if field1.errors %}{% for error in field1.errors %} <small class="errorlist">{{error}}</small> {% endfor %}{% endif %}
</div>
{% endfor %}
{% for field2 in reception %}
{% if field2.name != 'gender' %}
<label for=" {{field2.id_for_label}} "> {{field2.label}} </label> {{field2}}
<div>
{% if field2.errors %}{% for error in field2.errors %} <small class="errorlist">{{error}}</small> {% endfor %}{% endif %}
</div>
{% endif %}
{% endfor %}
{% for radiofield in reception.gender %}
{{radiofield.tag}}
<label for=" {{radiofield.id_for_label}} "> {{radiofield.choice_label}} </label> <br>
{% endfor %}
<input type="submit" value="Add Reception" name="Add Reception" class="btn btn-secondary mb-3" >
</form>
----------
## Ajax ##
$('#reception_form').submit(function(e){
console.log(" submit pressed")
e.preventDefault();
let Rnm = $('#id_username').val();
let Rfnm = $('#id_first_name').val();
let Rlnm = $('#id_last_name').val();
let Rem = $('#id_email').val();
let Rpwd = $('#id_password1').val();
let Rmob = $('#id_mob_no').val();
let Rcty= $('#id_city').val();
let Rdob = $('#id_dob').val();
let Rpr = $('#id_profile_photo').val();
let Rgen = $("input[name='gender']:checked").val()
let Rcsr = $("input[name='csrfmiddlewaretoken']").val()
reception_data = {Rusername : Rnm , Rfirst_name:Rfnm ,Rlast_name:Rlnm ,Remail:Rem , Rpassword:Rpwd, RmMob_no:Rmob , Rcity:Rcty , RBirth_Date :Rdob, Rprofile:Rpr, Rgender:Rgen , csrfmiddlewaretoken:Rcsr};
//console.log(reception_data)
$.ajax({
url: "{% url 'AddReception' %}" ,
type : 'POST',
data : reception_data,
dataType:'json',
success: function(data){
console.log("ajax executed");
console.log(data);
}
});
});
----------
admin_home view render the initial form and user information
## views ##
## 1) home##
def Admin_home(request):
print("admin Home")
user = request.user
admin = Admin.objects.get(pk=user)
# print(request)
form1 = Register()
reception = Register_Reception()
param = {'user':user , 'admin':admin , 'form1':form1 , 'reception':reception}
return render(request , "patients/admin/home.html" , param)
----------
This view function handles the ajax request but is_valid() returns false
## 2) Add Reception ##
def Add_reception(request):
if request.method == "POST":
form1 = Register(request.POST) #usercreation form
form2 = Register_Reception(request.POST , request.FILES) #reception profile form
print(form1.is_valid())
print(form1.errors)
print(request.POST['Rpassword'])
return HttpResponse("form submited")
'''
i think you are using jquery, right? Then i would try to serialize the form data like this:
reception_data = $("#reception_form").serialize()
Maybe this is better to send the POST data to the form...
Best,
jingo

Getting NoReverseMatch even though url patterns are correct?

I've been learning Django for like a month so apologies if I'm doing something stupid, but, I'm getting a NoReverseMatch Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<use>[^/]+)$'] error when trying to render a "profile" page under the url '/profile/[a user's name]', and I'm pretty sure all my paths/patterns are correct?? Here's my code, could someone help me with this? All my other url patterns work fine. This path also worked fine before, I just renamed the "user" variable into "use" and this happened.
urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("profile/<str:use>", views.profile, name="profile"),
path("following", views.following, name="following"),
#api
path('', include(router.urls)),
]
views.py:
def profile(request, use):
currentuser = str(request.user)
followers = []
following = []
for follow in Follow.objects.filter(following=use):
followers.append(follow.person)
for item in Follow.objects.filter(person=use):
following.append(item.following)
follower_count = len(followers)
following_count = len(following)
try:
Follow.objects.get(person=currentuser, following=use)
followed = True
except:
followed = False
post_list = Post.objects.filter(user=use)
dates = []
for post in post_list:
dates.append(post.timestamp)
dates.sort(key = lambda date: datetime.strptime(date, '%B %d, %Y, %I:%M %p'), reverse=True)
formattedlist = []
for date in dates:
postobject = Post.objects.get(timestamp=date)
formattedlist.append(postobject)
paginatorlist = Paginator(formattedlist, 10)
now_page_content = paginatorlist.page(1)
nowpage = 1
if request.method == "POST":
# Update the database
followbutton = request.POST.get("button")
button = request.POST.get("nav-button")
pagenum = request.POST.get("pg")
if followbutton:
if followbutton == "Follow":
followid = Follow.objects.all().count() + 1
person = currentuser
following = use
newfollow = Follow(followid, person, following)
newfollow.save()
return HttpResponseRedirect(f"/profile/{use}")
else:
deletefollow = Follow.objects.get(person=currentuser, following=use)
deletefollow.delete()
return HttpResponseRedirect(f"/profile/{use}")
else:
currentpage = paginatorlist.page(pagenum)
if button == 'Previous':
if pagenum == '1':
return render(request, "network/profile.html", {
"formattedlist": now_page_content, "currentnumber": nowpage, "message":'No previous page', "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
})
else:
nowpage = int(pagenum)-1
now_page_content = paginatorlist.page(nowpage)
return render(request, "network/profile.html", {
"formattedlist": now_page_content, "currentnumber": nowpage, "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
})
else:
if currentpage.has_next() == False:
return render(request, "network/profile.html", {
"formattedlist": currentpage, "currentnumber": pagenum, "message":'No next page', "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "list": formattedlist, "followed": followed,
})
else:
nowpage = int(pagenum)+1
now_page_content = paginatorlist.page(nowpage)
return render(request, "network/profile.html", {
"formattedlist": now_page_content, "currentnumber": nowpage, "use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed,
})
return render(request, "network/profile.html", {
"use": use, "currentuser": currentuser, "follower_count": follower_count, "following_count": following_count, "followed": followed, "formattedlist": now_page_content, "currentnumber": nowpage,
})
network/profile.html
{% extends "network/layout.html" %}
{% block body %}
<script src="http://127.0.0.1:8000/static/network/network.js"></script>
<div>
<h2 class="profiletext">{{use}}'s profile page</h2>
{{use}}
{% if message %}
<h6 style="color: red; margin-left: 10px">{{message}}</h6>
{% endif %}
<h5 class="profiletext">Follows: {{follower_count}} // Following: {{following_count}}</h5>
{% if use != currentuser %}
<form method="POST" class="profiletext" action="{% url 'profile' use %}">
{% csrf_token %}
{% if followed == False %}
<input type="submit" value="Follow" name="button">
{% else %}
<input type="submit" value="Unfollow" name="button">
{% endif %}
</form>
{% endif %}
</div>
{% for post in formattedlist %}
<div class="post">
<h5>{{post.use}}</h5>
<h6 style="font-weight: 60" class="edit"><a>Edit</a></h6>
<h4 class="content" style="font-size: 16px;">{{post.content}}</h4>
<h6 style="color: #d3d3d3; font-weight: 50">{{post.timestamp}}</h6>
<h1 class="hidden">{{post.id}}</h1>
{% if user.is_authenticated %}
<img src="https://cdn.shopify.com/s/files/1/0649/0603/products/bigo-0002-GH-8-bit-heart_grande.jpeg?v=1410449344">
<h2 class="likes">TODO</h2>
{% endif %}
</div>
{% endfor %}
<div>
<form class="pagination" method="POST" action="{% url 'profile' use %}">
{% csrf_token %}
<input type="submit" value="Previous" class="page-link" name="nav-button">
<input type="submit" value="Next" class="page-link" name="nav-button" >
<input type="text" value={{currentnumber}} class="pagenumber" name="pg">
</form>
</div>
{% endblock %}
I assume you have not changed user foreignkey from Post model. So, I guess your error is from this line:
<h5>{{post.use}}</h5>
So, it should be like:
<h5>{{ post.user }}</h5>

Heroku adds an extra "/checkout" in the URL when completing order with Stripe using Django

I have a small ecommerce project hosted on Heroku that I've built using Django, when clicking "complete order" on the checkout page I should be taken to the template "checkout_success" but instead I get stuck on the same page due to the URL trying to find a path with an extra "/checkout". I've posted some screenshots below to further explain.
Checkout app URLS.py:
from django.urls import path
from . import views
from .webhooks import webhook
urlpatterns = [
path('', views.checkout, name='checkout'),
path('checkout_success/<order_number>',
views.checkout_success, name='checkout_success'),
path('cache_checkout_data/', views.cache_checkout_data,
name='cache_checkout_data'),
path('wh/', webhook, name='webhook'),
]
Checkout apps view for checkout:
def checkout(request):
stripe_public_key = settings.STRIPE_PUBLIC_KEY
stripe_secret_key = settings.STRIPE_SECRET_KEY
if request.method == 'POST':
bag = request.session.get('bag', {})
form_data = {
'full_name': request.POST['full_name'],
'email': request.POST['email'],
'phone_number': request.POST['phone_number'],
'country': request.POST['country'],
'postcode': request.POST['postcode'],
'town_or_city': request.POST['town_or_city'],
'street_address1': request.POST['street_address1'],
'street_address2': request.POST['street_address2'],
'county': request.POST['county'],
}
order_form = OrderForm(form_data)
if order_form.is_valid():
order = order_form.save(commit=False)
pid = request.POST.get('client_secret').split('_secret')[0]
order.stripe_pid = pid
order.original_bag = json.dumps(bag)
order.save()
for item_id, item_data in bag.items():
try:
product = Product.objects.get(id=item_id)
if isinstance(item_data, int):
order_line_item = OrderLineItem(
order=order,
product=product,
quantity=item_data,
)
order_line_item.save()
else:
for size, quantity in item_data['items_by_size'].items():
order_line_item = OrderLineItem(
order=order,
product=product,
quantity=quantity,
product_size=size,
)
order_line_item.save()
except Product.DoesNotExist:
messages.error(request, (
"One of the products in your bag wasn't found in our database. "
"Please call us for assistance!")
)
order.delete()
return redirect(reverse('view_bag'))
request.session['save_info'] = 'save-info' in request.POST
return redirect(reverse('checkout_success', args=[order.order_number]))
else:
messages.error(request, 'There was an error with your form. \
Please double check your information.')
else:
bag = request.session.get('bag', {})
if not bag:
messages.error(
request, "There's nothing in your bag at the moment")
return redirect(reverse('products'))
current_bag = bag_contents(request)
total = current_bag['grand_total']
stripe_total = round(total * 100)
stripe.api_key = settings.STRIPE_SECRET_KEY
intent = stripe.PaymentIntent.create(
amount=stripe_total,
currency=settings.STRIPE_CURRENCY,
)
if request.user.is_authenticated:
try:
profile = UserProfile.objects.get(user=request.user)
order_form = OrderForm(initial={
'full_name': profile.user.get_full_name(),
'email': profile.user.email,
'phone_number': profile.default_phone_number,
'country': profile.default_country,
'postcode': profile.default_postcode,
'town_or_city': profile.default_town_or_city,
'street_address1': profile.default_street_address1,
'street_address2': profile.default_street_address2,
'county': profile.default_county,
})
except UserProfile.DoesNotExist:
order_form = OrderForm()
else:
order_form = OrderForm()
if not stripe_public_key:
messages.warning(request, 'Stripe public key is missing. \
Did you forget to set it in your environment?')
template = 'checkout/checkout.html'
context = {
'order_form': order_form,
'stripe_public_key': settings.STRIPE_PUBLIC_KEY,
'client_secret': intent.client_secret,
}
return render(request, template, context)
Checkout apps views.py for successful checkout:
def checkout_success(request, order_number):
"""
Handle successful checkouts
"""
save_info = request.session.get('save_info')
order = get_object_or_404(Order, order_number=order_number)
if request.user.is_authenticated:
profile = UserProfile.objects.get(user=request.user)
# Attach the user's profile to the order
order.user_profile = profile
order.save()
# Save the user's info
if save_info:
profile_data = {
'default_phone_number': order.phone_number,
'default_country': order.country,
'default_postcode': order.postcode,
'default_town_or_city': order.town_or_city,
'default_street_address1': order.street_address1,
'default_street_address2': order.street_address2,
'default_county': order.county,
}
user_profile_form = UserProfileForm(profile_data, instance=profile)
if user_profile_form.is_valid():
user_profile_form.save()
messages.success(request, f'Order successfully 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)
checkout template:
<form action="{% url 'checkout' %}" method="POST" id="payment-form">
{% csrf_token %}
<fieldset class="rounded px-3 mb-5">
<legend class="fieldset-label small text-black px-2 w-auto">Details</legend>
{{ order_form.full_name | as_crispy_field }}
{{ order_form.email | as_crispy_field }}
</fieldset>
<fieldset class="rounded px-3 mb-5">
<legend class="fieldset-label small text-black px-2 w-auto">Delivery</legend>
{{ order_form.phone_number | as_crispy_field }}
{{ order_form.street_address1 | as_crispy_field }}
{{ order_form.street_address2 | as_crispy_field }}
{{ order_form.town_or_city | as_crispy_field }}
{{ order_form.county | as_crispy_field }}
{{ order_form.postcode | as_crispy_field }}
{{ order_form.country | as_crispy_field }}
<div class="form-check form-check-inline float-right mr-0">
{% if user.is_authenticated %}
<label class="form-check-label" for="id-save-info">Save this delivery information to my
profile</label>
<input class="form-check-input ml-2 mr-0" type="checkbox" id="id-save-info" name="save-info"
checked>
{% else %}
<label class="form-check-label" for="id-save-info">
<a class="text-info" href="{% url 'account_signup' %}">Create an account</a> or
<a class="text-info" href="{% url 'account_login' %}">login</a> to save this information
</label>
{% endif %}
</div>
</fieldset>
<fieldset class="px-3">
<legend class="fieldset-label small text-black px-2 w-auto">Payment</legend>
<!-- A Stripe card element will go here -->
<div class="mb-3" id="card-element"></div>
<!-- Used to display form errors -->
<div class="mb-3 text-danger" id="card-errors" role="alert"></div>
<input type="hidden" value="{{ client_secret }}" name="client_secret">
</fieldset>
<div class="submit-button text-right mt-5 mb-2">
<a href="{% url 'view_bag' %}" class="btn btn-outline-black rounded-0">
<span class="icon">
<i class="fas fa-chevron-left"></i>
</span>
<span class="font-weight-bold">Adjust Bag</span>
</a>
<button id="submit-button" class="btn btn-black rounded-0">
<span class="font-weight-bold">Complete Order</span>
<span class="icon">
<i class="fas fa-lock"></i>
</span>
</button>
<p class="small text-danger my-0">
<span class="icon">
<i class="fas fa-exclamation-circle"></i>
</span>
<span>Your card will be charged <strong>${{ grand_total|floatformat:2 }}</strong></span>
</p>
</div>
</form>
JS for Stripe payment
// Handle form submit
var form = document.getElementById('payment-form');
form.addEventListener('submit', function (ev) {
ev.preventDefault();
card.update({
'disabled': true
});
$('#submit-button').attr('disabled', true);
$('#payment-form').fadeToggle(100);
$('#loading-overlay').fadeToggle(100);
var saveInfo = Boolean($('#id-save-info').attr('checked'));
// From using {% csrf_token %} in the form
var csrfToken = $('input[name="csrfmiddlewaretoken"]').val();
var postData = {
'csrfmiddlewaretoken': csrfToken,
'client_secret': clientSecret,
'save_info': saveInfo,
};
var url = '/checkout/cache_checkout_data/';
$.post(url, postData).done(function () {
stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: card,
billing_details: {
name: $.trim(form.full_name.value),
phone: $.trim(form.phone_number.value),
email: $.trim(form.email.value),
address: {
line1: $.trim(form.street_address1.value),
line2: $.trim(form.street_address2.value),
city: $.trim(form.town_or_city.value),
country: $.trim(form.country.value),
state: $.trim(form.county.value),
}
}
},
shipping: {
name: $.trim(form.full_name.value),
phone: $.trim(form.phone_number.value),
address: {
line1: $.trim(form.street_address1.value),
line2: $.trim(form.street_address2.value),
city: $.trim(form.town_or_city.value),
country: $.trim(form.country.value),
postal_code: $.trim(form.postcode.value),
state: $.trim(form.county.value),
}
},
}).then(function (result) {
if (result.error) {
var errorDiv = document.getElementById('card-errors');
var html = `
<span class="icon" role="alert">
<i class="fas fa-times"></i>
</span>
<span>${result.error.message}</span>`;
$(errorDiv).html(html);
$('#payment-form').fadeToggle(100);
$('#loading-overlay').fadeToggle(100);
card.update({
'disabled': false
});
$('#submit-button').attr('disabled', false);
} else {
if (result.paymentIntent.status === 'succeeded') {
form.submit();
}
}
});
}).fail(function () {
// just reload the page, the error will be in django messages
location.reload();
})
Heroku Logs Error:
**notice the extra "/checkout" in the POST URL.
Same in the browser console URL
I've tried an array things from adding and taking away "/" in my settings.py file and other URL paths. I'm sure this is something im overlooking but i've been stuck with this bug for days now. If anyone could help that would be great! And if any additional info is needed i'll be happy to provide. Thanks!
In your views.py in checkout_success view You should use
return HttpResponseRedirect(reverse('checkout_success',args=(order)))
instead of
template = 'checkout/checkout_success.html'
context = {
'order': order,
}
return render(request, template, context)
thanks I solved this, I problems, this problems was in js

NoReverseMatch at /why is this occuring?

I had this error before but I couldn't fix it, so I moved back to previous git state. Now I have to fix this, why does this error keep happening? And what does this even mean? It's occuring from index.html {% url vote_for_post %} Here's my code, thanks in advance.
views.py
def index(request):
categories = Category.objects.order_by('likes')
latest_posts = list(Post.objects.order_by('pub_date')[:50])
hot_posts = sorted(latest_posts, key=lambda x: x.hot(), reverse=True)
controversial_topics = sorted(latest_posts, key=lambda x: x.controversy(), reverse=True)
context_dict = {
'latest_posts': latest_posts,
'categories': categories,
'hot_posts': hot_posts,
'controversial_topics':controversial_topics
}
return render(request, 'main/index.html', context_dict)
def vote_for_post(request, category_name, post_id):
category = get_object_or_404(Category, name=category_name)
post = get_object_or_404(Post, id=post_id, category=category)
if request.POST['type'] == 'upvote':
post.upvotes += 1
if request.POST['type'] == 'downvote':
post.downvotes += 1
post.save()
if request.POST['referer'] == 'index':
return HttpResponseRedirect(reverse('main:index'))
if request.POST['referer'] == 'category':
return HttpResponseRedirect(reverse('main:category', args=(category.name,)))
urls.py
urlpatterns = [
url(r'^$', views.index, name='index'),
#url(r'^add_post/', views.add_post, name='add_post'),
url(r'^add_post/$', PostCreateView.as_view(), name='post-add'),
url(r'^vote/$', views.vote_for_post, name='vote_for_post'),
url(r'^(?P<slug>[\w|\-]+)/edit/$', PostUpdateView.as_view(), name='post-edit'),
url(r'^(?P<slug>[\w|\-]+)/delete/$', PostDeleteView.as_view(), name='post-delete'),
url(r'^add_category/', views.add_category, name='add_category'),
url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),
]
index.html
<div class="row placeholders">
<div class="col-sm-8">
<div class="row">
{% if hot_posts %}
{% for vote in hot_posts %}
<article>
<div class="vote">
<form method="post" style="display: inline"
action="{% url vote_for_post %}">
<input type="hidden" value="upvote" name="type">
<input type="hidden" value="index_page" name="referer">
<button type="submit">+</button>
{% csrf_token %}
</form>
<form method="post" style="display: inline"
action="{% url 'main:vote' vote.category.name vote.id %}">
<input type="hidden" value="downvote" name="type">
<input type="hidden" value="index_page" name="referer">
<button type="submit">-</button>
{% csrf_token %}
</form>
</div>
</article>
<hr>
{% endfor %}
{% else %}
<p>No topics are available.</p>
{% endif %}
</div>
</div>
</div>
As I see, "add_post", "vote" and "add_category" are ambiguous with your "slug" due to regex match.
url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),
url(r'^vote/$', views.vote_for_post, name='vote_for_post'),
url(r'^add_post/$', PostCreateView.as_view(), name='post-add'),
url(r'^add_category/', views.add_category, name='add_category'),
Try to give a better identifier for your urls.
e.g.
url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),
url(r'^vote/post/$', views.vote_for_post, name='vote_for_post'),
url(r'^add/post/$', PostCreateView.as_view(), name='post-add'),
url(r'^add/category/$', views.add_category, name='add_category'),
Let me know if this helped.
From the Django documentation: https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#url
{% url 'some-url-name' v1 v2 %}
In your code you should add ' ' to the name in the url template tag.
<form method="post" style="display: inline" action="{% url vote_for_post %}">
should be:
<form method="post" style="display: inline" action="{% url 'vote_for_post' %}">
Concerning the NoReverseMatch at / u'main' is not a registered namespace.
Remove the 'main:' in your (reverse('main:index')) and reverse('category', args=(category.name,)) in your views.py
if request.POST['referer'] == 'index':
return HttpResponseRedirect(reverse('index'))
if request.POST['referer'] == 'category':
return HttpResponseRedirect(reverse('category', args=(category.name,)))

Categories