My django didnt work(I'm studying in tutorial) - python

I'm very new to django. So I'm studying using tutorial site.
I think type perfectly same on site, but it's not work.
so plz give me advice.
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
mysite/polls/urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'), #url : base/polls/
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
mysite/polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
{% if errer_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
{% endfor %}
<input type="submit" value="Vote">
</form>
part of def vote in mysite/polls/views.py
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
error
NoReverseMatch at /polls/1/
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/
Django Version: 3.0.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
Exception Location: C:\Users\hdh45\crawling_practice\firstP\venv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677
Python Executable: C:\Users\hdh45\crawling_practice\firstP\venv\Scripts\python.exe
Python Version: 3.8.3
Error during template rendering
In template X:\python\practice_well\polls\templates\polls\detail.html, error at line 5
I guess vote url isnt work. maybe something wrong. but i dont know exact anwser. My googling power is useless.. help me.

<form action="{% url '***polls***:vote' question.id %}" method="post">
polls was a string and your urls.py in a
path('**<int:question_id>**/vote/', views.vote, name='vote')
<int:question_id> is a int. i think that's a mistake
and I'm also begginer

Related

Django: Reverse for 'login' not found. 'login' is not a valid view function or pattern name

I'm working on my project for a course and I'm totally stuck right now.
Login doesn't work. I using class-based views. When I`m logged in, everything works.The Logout View works too.
The error is as follows:
NoReverseMatch at /
Reverse for 'login' not found. 'login' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'login' not found. 'login' is not a valid view function or pattern name.
Exception Location: /home/aleo/#HOME/.virtualenvs/znajdki/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix
Python Executable: /home/aleo/#HOME/.virtualenvs/znajdki/bin/python3
Python Version: 3.8.6
My files:
poszukiwania/urls.py
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
app_name = 'poszukiwania'
urlpatterns=[
path('<slug:kategoria_slug>/', views.rzeczy_list, name='rzeczy_list_by_category'),
path('<int:year>/<int:month>/<int:day>/<slug:rzecz_slug>/<int:id>', views.rzecz_detail, name='rzecz_detail'),
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('', views.rzeczy_list, name='rzeczy_list'),
]
znajdki/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('poszukiwania.urls', namespace='poszukiwania'))
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL)
settings.py
LOGIN_REDIRECT_URL = 'poszukiwania:rzeczy_list'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
templates/registration/login.html
{% extends "poszukiwania/base.html" %}
{% load static %}
{% block title %}Logowanie{% endblock %}
{% block content %}
<h1>Logowanie</h1>
{% if form.errors %}
<p>
Nazwa użytkownika lub hasło są nieprawidłowe.
Spróbuj ponownie
</p>
{% else %}
<p>Wypełnij aby się zalogować</p>
{% endif %}
<div class="login-form">
<form action="{% url 'poszukiwania:login' %}" method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}" />
<p><input type="submit" value="Zaloguj się"></p>
</form>
</div>
{% endblock %}
help me, please

Python Django NoReverseMatch Template

I configured the path and made the template but when I try to run server it gives
NoReverseMatch at /password-reset/
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name.
Request Method: POST
Request URL: http://localhost:8000/password-reset/
Django Version: 3.0.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name.
error.
My urls.py
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from users import views as user_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name= 'register'),
path('profile/', user_views.profile, name='profile'),
path('login/', auth_views.LoginView.as_view(template_name = 'users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name = 'users/logout.html'), name='logout'),
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'),
name='password_reset'),
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),
name='password_reset_done '),
path('password-reset-confirm///',
auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'),
name='password_reset_confirm '),
path('', include('blog.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and my template
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class = "content section">
<form method="POST">
{% csrf_token %}
<fieldset class= "form-group">
<legend class = "border-bottom mb-4">Reset Password</legend>
{{form|crispy}}
</fieldset>
<div class = "form-group">
<button class="btn btn-outline-info" type ="submit"> Reset Password </button>
</div>
</form>
</div>
{% endblock content %}
Could you please tell me what is wrong with my project? Thank you
It looks like you got a space in the name of 'password_reset_confirm '
'password_reset_confirm '
^
Not sure how django well django handles that. If that is not the issue, please post the code where you reverse-call the URL in the template (where the {% url ... %} template tag is or possibly from your view where you configured your e.g. success URL.

Problem with linking ID of a task in DJANGO

I am working on to do app, and I cannot solve this problem.
The problem is linking the tasks with ID or PK...
i am getting this error:
NoReverseMatch at /
Reverse for 'update_task' with arguments '(1,)' not found. 1 pattern(s) tried: ['update_task/
and it is pointing that error is here (in template):
Update
views.py
def updateTask(request, pk):
task = Task.objects.get(id=pk)
form =TaskForm(instance=task)
context = {'form': form}
return render(request, 'tasks/update_task.html',context)
template
<h3>To Do</h3>
<form action='/' method="POST">
{% csrf_token %}
{{form.title}}
<input type="submit" name="Create Task">
</form>
{% for task in tasks %}
<div class="">
Update
<p>{{task}}</p>
</div>
{% endfor %}
URLS.PY
from django.urls import path
from tasks import views
urlpatterns = [
path('', views.index, name='list'),
path('update_task/<str:pk/', views.updateTask, name='update_task'),
]
this will help you
path('update_task/<str:pk>/',views.updateTask, name='update_task'),

How to use URL names in views?

I have been following this Django tutorial, and I am trying to remove hardcoded URLs, but I can't make the reverse function work.
That's my detail view:
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
# How it was before:
# return render(request, 'polls/detail.html', {'question': question})
return HttpResponse(reverse('polls:detail', kwargs={'question': question}))
path('<int:question_id>/', views.detail, name='detail')
This is the urls.py:
app_name = 'polls'
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
And this is the template for the detail view:
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
Index
</form>
Can somebody help me with that or give any tips?
Thanks in advance.
I think your original code was fine. If you were in another view (say, the vote view) and wanted to redirect the user to the detail view, you could do this:
return HttpResponseRedirect(reverse('polls:detail', args=(question.id,)))
Copied from part 4 of the tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial04/#write-a-simple-form:
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
The last line redirects the user from the vote view to the results view and uses reverse() to avoid hard-coding the url.

Django "reverse for ____ with arguments"... error

I'm receiving the following error
Error: Reverse for placeinterest with arguments ('',) and keyword arguments {} not found. 1 pattern(s) tried:
[u'polls/(?P<section_id>[0-9]+)/placeinterest/$']
I worked through the Django example for a polling app, and now I'm trying to create a class registration app adapting what I already have. Error points to line 5 here:
<h1>{{ section.class_name }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:placeinterest' section.id %}" method="post">
{% csrf_token %}
<input type="radio" name="incr" id="incr" value="incr" />
<label for="incr"></label><br />
<input type="submit" value="Placeinterest" />
</form>
But I think the problem is in my placeinterest function:
def placeinterest(request, section_id):
section = get_object_or_404(Section, pk=section_id)
try:
selected_choice = section.num_interested
except (KeyError, Section.num_interested.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'section': section,
'error_message': "You didn't select a choice.",
})
else:
section.num_interested += 1
section.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(section.id,)))
I'm not sure what my POST call should be if my Section class looks like this:
class Section(models.Model):
class_name = models.CharField(max_length=200)
num_interested = models.IntegerField(default=0)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.class_name
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(minutes=3)
def some_interested(self):
if self.num_interested > 0:
return "There is currently interest in this class"
else:
return "There is currently no interest in this class"
The results part comes up fine in my browser, and here is urls.py for good measure:
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<section_id>[0-9]+)/placeinterest/$', views.placeinterest, name='placeinterest'),
]
Edit: adding the original code from the example in hopes that might help someone see where I went wrong:
urls:
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
vote function in views.py:
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
detail.html, where I'm having problems after making my changes:
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
The error has nothing to do with your view. It specifically says it's trying to match the URL named placeinterest in the error. It knows the URL exists, but the arguments are wrong.
It thinks you're trying to pass an empty string as a positional argument. This means that section.id is probably None when the template is rendered. It's converting the null value into an empty string and passing it as a positional argument, hence ('',). That's a tuple with one empty string value in it.
The problem is here:
<form action="{% url 'polls:placeinterest' section.id %}" method="post">
Django can't figure out the url argument as it's misconfigured. Use this:
<form action="{% url 'polls:placeinterest' section_id=section.id %}" method="post">
You also need to ensure that section id is valid a number (be careful of what you supply as "section" as your context.

Categories

Resources