NoReverseMatch at /index/ - python

I have been through all of the similar issues and I have gotten nowhere and I have gone through the djangogirls and the officail Django tutorials and as far as I can tell it should be working.
In the polls/templates/index.html file I have this:
[...]
{% if forms %}
<ul>
{% for form in forms %}
<li>
<h1><a href="{% url 'form_detail' pk=form.pk %}">
{{ form.fname }}
</a></h1>
[...]
In my polls/urls.py file I have this:
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
[...]
url(r'^index/$', 'polls.views.site_index'),
[...]
url(r'^form/(?P<pk>\d+)/$', views.form_detail, name='form_detail'),
[...]
In my polls/views.py file I have this:
from django.shortcuts import render, render_to_response, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from .models import Nform, Choice, Question, Post
from django.template import loader
from django.utils import timezone
from django.views import generic
from django.contrib import auth
from django.db import models
from .form import PostForm
def site_index(request):
forms = Nform.objects.order_by('-published_date')
return render_to_response('polls/index.html', {'forms': forms})
def form_detail(request, pk):
current_form = get_object_or_404(Nform, pk=pk)
fame = current_form.fname
latest_question_list = Question.objects.filter(for_form=fame).order_by('-pub_date')
choice_quest_list = []
text_quest_list = []
form = PostForm()
for i in range(len(latest_question_list)):
if len(latest_question_list[i].choice_set.all()) == 0:
text_quest_list.append(latest_question_list[i])
else:
choice_quest_list.append(latest_question_list[i])
return render(request, 'polls/read_only.html', {'choice_quest_list': choice_quest_list, 'text_quest_list': text_quest_list, 'form_name': fame, 'form': form})
[...]
I am assume that I have made a very simple mistake somewhere and I would be very grateful to anyone who finds it.
See this issue for pics.
Here is a link to my code.
Thanks :)

This is happening because you have defined a variable named app_name in your application urls.py.
When you define that variable, it becomes your url namespace.
You either have to reverse your url like this:
<h1><a href="{% url 'polls:form_detail' pk=form.pk %}">
or remove the app_name variable to use the url name directly.
Read more about reversing url names # django-docs

Related

Django copy object: func with self.id in html, urls and views

I try copy my object.
I can receive copy from my "def checklist_copy" if i explicitly specify pk.(example)
But, i try work with 'self.pk' and this is not work. I want to copy the object under which I click on the button
i used different variations:
(pk=pk) in function,
checklist.id and checklist.pk in html template,
tried passing "self" to function and doing self.pk
doing pk=int(Checklist.object.get.id()) to then transfer this "pk" to (pk=pk) in object.id()
try include func in class DetailView
did not achieve a result
Please help. I don't know where and what to look for
Example:
models.py
from django.urls import reverse
from django.db import models
class Checklist(models.Model):
title = models.CharField(max_length=250)
def get_absolute_url(self):
return reverse ('checklist:checklist', kwargs={'id': self.id, 'title': self.title})
def __str__(self):
return self.title
view.py
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Checklist
from django.shortcuts import redirect
from django.urls import reverse_lazy
class CheckListView(ListView):
model = Checklist
context_object_name = 'checklists'
class CheckListDetail(DetailView):
model = Checklist
context_object_name = 'checkList'
template_name = 'base/checklist.html'
def checklist_copy(request):
dest = Checklist.objects.get(pk=2) #here i need to use self.id(pk), but can't include 'self' in args of func
dest.pk = None
dest.save()
return redirect(reverse_lazy('checklists'))
urls.py (my app)
from django.urls import path
from .views import CheckListView, CheckListDetail
from . import views
urlpatterns = [
path('', CheckListView.as_view(), name='checklists'),
path('checklist/<int:pk>/', CheckListDetail.as_view(), name='checklist'),
path('checklist-copy/', views.checklist_copy, name='checklist_copy'),
]
checklist_list.html
<div id="tasklist" class="task-items-wrapper">
{% for checklist in checklists %}
<div class="task-wrapper" data-position="{{checklist.pk}}">
<div class="task-title">
{{checklist}}
</div>
</div>
<a class="task-wrapper" href="{% url 'checklist_copy' %}">Copy</a>
{% endfor %}

Django form not rendering? (No Model)

So my Django form is not rendering in the html.
all I'm able to see is the Get Rank text.
I'm not sure if it's because I don't have a model or maybe it's something wrong with my html?
If you need to see anything else let me know not sure what's wrong, I also tried just doing it all inside of the home function but then it doesn't render the html at all.
Side question - Also I only plan on grabbing the users name, and the tag outside their name ("JohnDoeNA#1") so I probably use a get method correct?
EDIT: Fixed the button not working now only thing not rendering is the form. (Mis-spelling)
Updated Code to be correct.
views.py:
from urllib import response
from django.shortcuts import render
from django.http import HttpResponse
import requests
from .forms import SearchUser
import json
# Create your views here.
def index(response):
return render(response, "main/base.html")
def home(response):
form = SearchUser()
data = requests.get(
'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-ee8fcdce-05c5-4ad4-b909-8efa722b1134')
userid = data.json()['puuid']
return render(response, "main/home.html", {
'form': form,
'userid': userid,
# 'mmr': apidata['rank']
})
forms.py:
from django import forms
class SearchUser(forms.Form):
name = forms.CharField(label="Name", max_length=200)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("home/", views.home, name="home")
]
home.html:
{% extends 'main/base.html'%}
{% block content %}
<h2>Valorant Ranked Checker</h2>
<form method="post" action="/home/">
{{form}}
<button type="submit", name="search">
Get rank
</button>
</form>
<p><strong>{{userid}} - {{mmr}}</strong></p>
{% endblock %}
base.html:
<!DOCTYPE html>
<head>
<title>Blue's Valorant Ranked Checker</title>
</head>
<body>
<div id="content", name="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
You have two main issues here:
You were rendering your base template as your root directory (base.html) and therefore Django's template inheritance wasn't working correctly. You'll want to render the child template (the one that includes extends) if you want template inheritance to work properly.
You need to pass your Django form (SearchUser) to the render function of the view
I recommend making these changes:
====================
Remove reference to the index view in your urls.py as we don't need it. Instead, use your home child template as your root view:
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home")
]
====================
Remove the no longer needed index function from views.py. You'll also want to pass reference to your form (SearchForm) inside of Django's render shortcut function.
views.py:
from urllib import response
from django.shortcuts import render
from django.http import HttpResponse
import requests
from .forms import SearchUser
import json
# Create your views here.
def home(response):
data = requests.get(
'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-APIKEY')
userid = data.json()['puuid']
return render(response, "main/home.html", {
'form': SearchUser(), # include reference to your form
'userid': userid,
# 'mmr': apidata['rank']
})
def search(response):
form = SearchUser()
return render(response, "main/home.html", {"form": form})
Your view function that renders the form and the form template must match. form also must be in your context.
Put the form in the home.html and change the home view like so:
def home(response):
form = SearchUser()
return render(response, "main/home.html", {'form': form})

how to handle httpresponseredirect

test2/urls.py
from django.conf.urls import url
from .import views
from .forms import forms
urlpatterns=[
url(r'^$',views.index,name='index'),
url(r'^thankyou/$',views.thankyou,name='thankyou')
]
test1/urls.py
from django.contrib import admin
from django.conf.urls import url , include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test2/',include('test2.urls')),
]
views.py
this view should redirect to /test2/thankyou/ but why it is going to /thankyou
and what to do enable the view given by redirect method
from django.shortcuts import render
from django.http import HttpResponseRedirect,HttpResponse
from .forms import Get_name
# Create your views here.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thankyou/')
else:
form = Get_name()
return render(request, 'test2/name.html' , {'form':form})
def thankyou(request):
return HttpResponse('sai chaitanya')
name.html
after submitting the form it should redirect to test2/thankyou but it is going to /thankyou.
<form action="/thankyou/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
user_choice =[('space',''),('passenger','Passenger'),('driver','Driver')]
class Get_name(forms.Form):
user_name = forms.CharField(label='user name',max_length='50',required=True)
pass_word1 = forms.CharField(widget=forms.PasswordInput,max_length='20',label='Password')
pass_word2 = forms.CharField(widget=forms.PasswordInput, max_length='20', label='Confirm Password')
email = forms.EmailField(label='email',max_length='100')
mobile = forms.CharField(label='contact number ',widget=forms.NumberInput,max_length='10')
address = forms.CharField(label='Address',max_length='100')
user_type = forms.CharField(label='select user type',widget=forms.Select(choices=user_choice))
It is going to /thankyou/ because you have hardcoded the URL /thankyou/:
return HttpResponseRedirect('/thankyou/')
You can redirect to /test2/thankyou/ by changing the code to:
return HttpResponseRedirect('/test2/thankyou/')
However the best practice is to reverse the URL instead of hardcoding it:
from django.urls import reverse
return HttpResponseRedirect(reverse('thankyou'))
This can be simplified using the redirect shortcut:
from django.shortcuts import redirect
return redirect('thankyou')

Method Not Allowed (POST) using DeleteView

I am new to Django and i using Class based views to add a delete option to my Restaurant List, However when i click the delete button i am getting a blank screen and getting the following error in the console
"Method Not Allowed (POST):"
Below is my code
views.py
from __future__ import unicode_literals
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, ListView, DetailView,
CreateView,DeleteView
from django.urls import reverse_lazy
class RestaurantDeleteView(DeleteView):
model = RestaurantLocation
success_url = reverse_lazy('restaurants:list')
urls.py
from django.conf.urls import url, include
from .views import (
RestaurantListView,
RestaurantDetailView,
RestaurantCreateView,
RestaurantDeleteView,
)
urlpatterns = [
url(r'^create/$', RestaurantCreateView.as_view(), name= 'create'),
url(r'^$',RestaurantListView.as_view(), name= 'list'),
url(r'^(?P<slug>[\w-]+)/$',RestaurantDetailView.as_view(),
name="detail"),
url(r'^(?P<slug>[\w-]+)/delete/$', RestaurantDeleteView.as_view(),
name="restaurant-delete"),
]
delete.html
<form method="post" action="" >{% csrf_token %}
<p>Are you sure you want to delete <strong> {{ obj }}</strong>?</p>
<input type="submit" value="DELETE" />
</form>
method in your delete.html is currently "t", change to "post" and see if that works.
Your form action is pointing to root url that is /.
This route is determined by the RestaurantListViews and it is accesed via GET method.
In your example, you are trying to access this using POST, thus you're getting the error.
To make use of your RestaurantDeleteView change the action property in your form to point to an existing restaurant, like:
<form method="post" action="{your_existing_restaurant_slug}/delete" >
{% csrf_token %}
...
...

"' object has no attribute 'get' Error

Have stuck here for 2 days. Hoping to get some enlightenment. The error code here is "'inputform' object has no attribute 'get'". I highly suspect the error is because of the forms.py. I want to make a dynammic choice field list there.
Model.py
from django import forms
from django.forms import ModelForm
from django.db import models
from dupont.models import dupont
class input(models.Model):
...
Region=models.CharField(max_length=100)
Forms.py
from django import forms
from django.forms import ModelForm
from .models import input
from anothermodel.models import A
from django.contrib.auth.models import User
import Queue
class inputform(forms.ModelForm):
regionlist = forms.ChoiceField(label=u'Region',choices=())
def __init__(self,*args,**kwargs):
super(inputform,self).__init__(*args,**kwargs)
self.fields['regionlist'] = forms.ModelChoiceField(queryset=anothermodel.objects.values('Region').distinct())
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from inputform.forms import inputform
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def input(request):
if request.method == 'POST':
form = inputform(request.POST)
if form.is_valid():
return HttpResponseRedirect('templates/About')
else:
form = inputform()
return render_to_response('inputform.html', {
'form': form,
})
Part of html
<body>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<form action="" method="post">{% csrf_token %}
{{ form.regionlist }}
{% for region in form.regionlist.choices %}
<option value="{{ val }}" {% ifequal data.val val %}selected {% endifequal %}>
{% endfor %}
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from metrics import views
from django.views.generic.list import ListView
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from inputform.views import input,ifglobal
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/',include('login.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^input', 'inputform.views.inputform'),
)
The trackback
Traceback:
File "C:\Python27\lib\site-packages\django-1.8.3 py2.7.egg\django\core\handlers\base.py" in get_response
223. response = middleware_method(request, response)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\middleware\clickjacking.py" in process_response
31. if response.get('X-Frame-Options', None) is not None:
Exception Type: AttributeError at /input
Exception Value: 'inputform' object has no attribute 'get'
The error is indeed in your URLs. Your pattern is pointing at 'inputform.views.inputform', ie the form, not the view. It should be 'inputform.views.input'.

Categories

Resources