Why am I getting NoReverseMatch error with no arguments found? - django

Error:
NoReverseMatch at /leachers/11/donate/
Reverse for 'donate' with no arguments not found. 1 pattern(s) tried: ['leachers/(?P[0-9]+)/donate/$']
views.py
#login_required
def donate(request,pk):
if request.method == 'POST':
form = forms.UserDonateForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.donator = request.user
user.save()
return redirect('leacher_list')
else:
form = forms.UserDonateForm()
return render(request,'my_app/donation_form.html',{'form':form})
urls.py
from django.urls import path
from . import views
from .views import donate
urlpatterns = [
path('',views.HomePageView.as_view(),name='home_page'),
path('about/',views.AboutView.as_view(),name='about'),
path('leachers/',views.LeacherListView.as_view(),name='leacher_list'),
path('leachers/<int:pk>/donate/',donate,name='donate'),
]
here I am assigning pk to link:
{% for member in leacher_list %}
<h4>Name : {{ member.name }}</h4>
<h5>Address : {{ member.address }}</h5>
<h5>Location : {{ member.location }}</h5>
<!--original href="donate" -->
<a class="btn btn-primary" href="{% url 'donate' pk=member.pk %}" role="button">Donate</a>
I am new to django.

Please add app_name before namespace in url. I would suggest doing something like this:
<a class="btn btn-primary" href="{% url 'my_app:donate' pk=member.pk %}" role="button">Donate</a>
Here we consider my_app is app_name. Please try this.

Related

My view does not redirect after processing a form. Used HttpResponseRedirect

I am new to Django and I am trying to use custom forms. My problem is that my form does not do anything after I submit it.
I am following the documentation here:https://docs.djangoproject.com/en/4.1/topics/forms/
I have the following files:
forms.py:
from django import forms
class TestForm(forms.Form):
text = forms.CharField(label='Text', max_length=50)
urls.py:
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
path('test', views.test_view, name='test')
]
views.py:
def index(request):
return render(request, 'index.html', context)
def test_view(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('home:index')
else:
form = TestForm()
return render(request, 'test.html', context={'form':form, 'text':'No text yet.',})
template: test.html
<div>
<form action="home:club-invite" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<hr>
<p>Your text: {{ text }}</p>
</div>
The problem is that the Submit button does nothing. I was expecting a redirect to the index page. But here is no error, no subsequent http request or redirect, nothing...
Am I missing something here?
PS:I also tried return redirect('home:index'). Still no success.

NoReverseMatch at /options/ Reverse for 'sales' with arguments '('',)' not found. 1 pattern(s) tried: ['sales/(?P<pk>\\d+)/$']

I am trying to learn django and I have encountered this error. It has persisted irrespective of the fact that I have tried the available SO remedies but for some reason, it refuses to go away. Can someone please see an error anywhere.
show_options.html
<a class="btn btn-sm btn-block bg-dark" style="color: black;" href="{% url 'Management:addProduct' %}"> Add </a>
**<a class="btn btn-sm btn-danger" href="{% url 'Management:sales' add_user_sales.pk %}"> Add Sales </a>**
<a class="btn btn-sm btn-danger" href="{% url 'Management:total' %}"> View Total </a>
function to render my show_options page
def show_options(request):
return render(request, 'show_options.html', {})
function add_user_sales
#login_required
def add_user_sales(request , pk):
current_user = request.user
context = {}
context["data"] = MadeSale.objects.get(id=pk)
profiles = UserProfile.get_profile()
for profile in profiles:
if profile.profile_name.id == current_user.id:
if request.method == 'POST':
form = SalesForm(request.POST)
if form.is_valid():
upload = form.save(commit=False)
upload.posted_by = current_user
upload.profile = profile
upload.save()
messages.success(request, f'Hi, Your data has successfully been updated' )
return redirect('addProduct')
else:
form = SalesForm()
return render(request,'addProduct.html',{"user":current_user,"form":form}, context)
my app urls
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.authtoken.views import obtain_auth_token
app_name = 'Management'
url(r'^sales/(?P<pk>\d+)/$', views.add_user_sales, name='sales')
,

Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<item_id>[^/]+)/$']

I cant seem to add products/plans to my cart page im getting this error.
This is my views
def add_to_cart(request, item_id):
""" Add plan to shopping cart """
cart = request.session.get('cart', {})
cart[item_id] = cart.get(item_id, 1)
request.session['cart'] = cart
return redirect(reverse('plans'))
This is my plans.html - this is a button where im trying to a plan to my cart
<form method="post" action="{% url 'add_to_cart' item.id %}">
{% csrf_token %}
<div class="text-center">
<span class="input-group-btn">
<button class="btn btn-light color-orange " type="submit">
Add to Cart
</button>
</span>
</div>
</form>
And this is my urls from my cart app
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.view_cart, name='view_cart'),
path('add/<item_id>/', views.add_to_cart, name='add_to_cart'),
]
Would be great if someone could guide me
urlpatterns = [
path('', views.view_cart, name='view_cart'),
# path('add/<item_id>/', views.add_to_cart, name='add_to_cart'),
path('add/<int:item_id>/', views.add_to_cart, name='add_to_cart'),
]
Make sure that you are passing a value with key "item" to the context data in your form HTML, or else "item.id" will be None.

Linking of homePage view to other views

I am trying to link my home page view to other views but it's not working
I also tried to take only a single view but it still not working
I also don't know how to connect multiple views into a single URL
app/views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.shortcuts import render
from homePage.forms import SignInForm,DropUsaMessage
# Create your views here.
def homePage(request):
sign_in_detail=SignIn
message_detail=DropUsaMessage
return render(request, "index.html",{"form":sign_in_detail,"forms":message_detail})
def SignIn(request):
sign_in_detail=SignInForm()
if request.method == 'POST':
sign_in_detail = SignInForm(request.POST)
if sign_in_detail.is_valid():
return render(request, "index2.html",{"form":sign_in_detail})
else:
sign_in_detail = SignInForm()
# "form":sign_in_detail
return render(request, "index.html",{})
def Contact(request):
message_detail=DropUsaMessage()
if request.method == 'POST':
message_detail = DropUsaMessage(request.POST)
if message_detail.is_valid():
return homePage(request)
else:
message_detail = DropUsaMessage()
# "forms":message_detail
return render(request, "index.html",{"forms":message_detail})
app/urls.py
from django.urls import path
from . import views
urlpatterns=[
path('', views.homePage),
]
app/forms.py
from django import forms
from django.core import validators
class SignInForm(forms.Form):
email=forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Enter E-mail',"id": 'exampleInputEmail1'}))
password=forms.CharField(widget=forms.PasswordInput(attrs={"class":'form-control',"placeholder":'Enter Password',"id":'exampleInputPassword1'}))
class DropUsaMessage(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={"class":'form-control',"placeholder":'Your Name'}))
email = forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Your E-mail',"id": 'exampleInputEmail1'}))
phone = forms.IntegerField(widget=forms.NumberInput(attrs={"class":'form-control',"placeholder":'Your Phone Number'}))
message = forms.CharField(widget=forms.Textarea(attrs={"class":'form-control',"placeholder":'Type Your Message',"style":'width:100%; height: 150px'}))
index.html
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<img src="{% static 'img/sampleImage.jpg' %}" width="100%" height="100%" class="d-inline-block align-top" alt="">
</div>
<div class="col-md-4">
<form method="POST">
{% csrf_token %}
{{ form }}
<div class="form-check">
<span class="fpswd">Forgot password?</span>
</div>
<button type="submit" class="btn btn-primary" name="SignIn">Submit</button>
</form>
</div>
</div>
</div>
<div class="container contact-form">
<form method="post">
<h3>Drop Us a Message</h3>
{% csrf_token %}
{{ forms }}<br><br>
<div class="form-group">
<input type="submit" name="SendMessage" class="btnContact" value="Send Message" />
</div>
</form>
</div>
the signin field is not showing up. there is a long address is showing in django-debug-toolbar
Give names to your URL patterns like below:
urlpatterns=[
path('', views.homePage, name='home'),
]
Then in your templates you can use Jinja to reference these names like.
Home
You can get a little help from DjangoProject site tutorial with the link.
UPDATE:
You need to create a Navbar (Navigation bar). You can then call all your pages with URLS in your home page. Like
Home | Services | Portfolio
You need to create urlpatterns with name for each page and you can then use it like.
<ul><li>Home</li>
<ul><li>Services</li>
<ul><li>Portfolio</li>.
So then all the pages will link up to your home page and you can navigate.
For that you need to create 3 respective views like below in your urls.py:
urlpatterns=[
path('', views.homePage, name='home'),
path('services/', views.servicePage, name='services'),
path('portfolio/', views.portfolioPage, name='portfolio'),
]
You can not have multiple views on a single URL. One URL maps to a single view.

Unable to redirect Django form

I am trying to build a simple blog with a basic post function through a very simple form. The function I am trying to accomplish is:
if the new post POSTs (no errors etc.) save to the database and redirect to the newly created post_details page. Otherwise I want it to re render the post form again. I keep getting the error NoReverseMatch at /post/pk and I cannot find my error. I am obviously not understanding something properly. The related code is below:
views.py
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
post_edit.html
{% extends 'blog/base.html' %}
{% block content %}
<h2>New post</h2>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new/', views.post_new, name='post_new'),
]
I found my error inside my link for in my template view post_detail.html:
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
It was redirecting properly to post_detail.html but the link above was breaking my page.