Why this form doesn't change the language of the website? - python

This is my language-switching form.
{% get_current_language as lang_code %}
{% get_available_languages as languages %}
{% get_language_info_list for languages as langs %}
<form action="{% url 'set_language' %}" method="POST">
{% csrf_token %}
<select name="language" title="{% translate 'Language' %}">
{% for lang in langs %}
<option value="{{ lang.code }}"{% if lang.code == lang_code %} selected{% endif %}>
{{ lang.name_local }} ({{ lang.name_translated }})
</option>
{% endfor %}
</select>
<input type="submit" value="OK" />
</form>
I include this in the footer of my base template.
Then, here is my courses/urls.py (app urls).
from django.contrib import admin
from django.urls import path
from django.utils.translation import gettext_lazy as _
from . import views
admin.site.site_header = _("FilFak administration")
admin.site.site_title = _("FilFak admin")
admin.site.index_title = _("Manage FilFak")
urlpatterns=[
path("courses/", views.CourseList.as_view(), name="course_list"),
path("professors/", views.ProfessorList.as_view(), name="professor_list"),
path("exams/", views.ExamList.as_view(), name="exam_list"),
path("courses/<slug:slug>", views.CourseDetails.as_view(), name="course_details"),
path("professors/<slug:slug>", views.ProfessorDetails.as_view(), name="professor_details"),
path("exams/<slug:slug>", views.ExamDetails.as_view(), name="exam_details"),
path("", views.Index.as_view(), name="index"),
]
filfak/urls.py (project urls.py)
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.conf import settings
from django.utils.translation import gettext_lazy as _
urlpatterns = [
path("admin/", admin.site.urls),
path("lang/", include("django.conf.urls.i18n")),
]
urlpatterns += i18n_patterns(
path("", include("courses.urls")),
prefix_default_language=False
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And here's the list of middlewares from settings.py.
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
When I click OK on the language-switching form, it actually changes the language only on the homepage of the default language. On any other URL it just refreshes the page, without changing the language.
Am I doing something wrong?

Check the flag value of USE_I18N, look like its set to False and thats why the language are not setting properly.
Change it to :-
USE_I18N = True
As per Django document :-
If you don’t use internationalization, you should take the two seconds to set USE_I18N = False in your settings file.

Related

Django (Password_change) doesn't work url

I'm learning Django book named by (Django for beginners)
I have a problem with password _change
Below my code from urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('',include('pages.urls')),
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('users/',include('django.contrib.auth.urls')),
]
Next is password_change_form.html
{% extends 'base.html' %}
{% block title %}
Password Change
{% endblock %}
{% block content %}
<h1>Password change</h1>
<p>Please enter your old password, for security's sake, and then enter your
new password twice so we can verify you typed it in correctly.</p>
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<input type="submit" class="btn btn-success" value="Change my password">
</form>
{% endblock %}
my content does'nt linking to password_change_form.html
Via versa linking to password_change from Django adminstration
Try this:
Crete an app named 'registration'
python manage.py startapp registration
Set it in the first position of your installed Apps:
INSTALLED_APPS = [
'registration',
....
]
Inside the app 'registration', create a the folder 'templates/registration'
Inside the folder created in the previous step, you can now set all your custom templates, 'password_change_form.html', 'password_change_done.html', etc....
import the urls inside the main urls, I would prefer using like this:
urlpatterns = [
... # your urls
path('accounts/',include('django.contrib.auth.urls')),
]

can't delete item from database in django view

i created a view to delete an object through a template but it seems im missing something i cant quite put together
def product_delete_view(request, id):
obj = get_object_or_404(Product, id=id)
if request.method == "POST":
obj.delete()
return redirect('../../')
context = {
"obj": obj
}
return render(request, "products/product_delete.html", context)
from django.contrib import admin
from django.urls import path
from pages.views import home_view, contact_view, about_view, social_view, services_view
#from products.views import product_detail_view, product_create_view, render_intial_data
from products.views import render_intial_data, dynamic_lookup_view, product_delete_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name='home'),
path('contact/', contact_view, name='contact'),
path('about/', about_view, name='about'),
path('services/', services_view, name='services'),
path('social/', social_view, name='social'),
#path('product/detail', product_detail_view, name='pdtDetail'),
#path('product/create', product_create_view, name='pdtCreate')
path('product/create', render_intial_data, name='pdtCreate'),
path('product/<int:id>', dynamic_lookup_view, name="pdt"),
path('product/<int:id>/delete', product_delete_view, name='pdtDelete')
]
{% extends 'base.html' %} {% block content %}
<form action="." method="POST">
{% csrf_token %}
<h1>Do you want to delete the product "{{ obj.title }}"</h1>
<p><input type="submit" value="Yes" /> Cancel</p>
</form>
{% endblock %}
when i try to delete object is not removed from the database table
Your patterns doesn't ending with slash. Try to add ending slash to it:
path('product/create/', render_intial_data, name='pdtCreate'),
path('product/<int:id>/', dynamic_lookup_view, name="pdt"),
path('product/<int:id>/delete/', product_delete_view, name='pdtDelete')
In your urls.py there is something like this product/<int:id>/delete and you are typing produck/4/ in your browser. use this http://127.0.0.1:8000/product/4/delete and use '/' at last like this http://127.0.0.1:8000/product/4/delete/
your problem seems here
path('product/<int:id>/delete', product_delete_view, name='pdtDelete')
you had left that url without closing with /. just do this
path('product/<int:id>/delete/', product_delete_view, name='pdtDelete')

Trying to create a home page with a login form, but getting 'NameError: name 'url' is not defined'

I'm relatively new to django and trying to create a home page that has a login form on it, consisting of username and pw bars. I was trying to recreate what I saw here in my own project:
homepage login form Django
but I keep getting back
NameError: name 'url' is not defined. I am pretty lost on what is causing this. I was initially writing into the project level urls.py but then moved to the app level (accounts) urls.py because that makes sense to me...but I'm not confident about this.
Here are my files:
project
├── manage.py
├── db.sqlite3
├── templates
├── accounts
| ├──migrations
| ├──_pycache_
| ├──admin.py
| ├──apps.py
| ├──models.py
| ├──_init__.py
| ├──urls.py
| ├──tests.py
| └──views.py
└── project
├── settings.py
├── urls.py
└── wsgi.py
project/settings.py
from django.urls import reverse_lazy
import os
...
SITE_ID = 1
LOGIN_URL = reverse_lazy('login')
LOGIN_REDIRECT__URL = reverse_lazy('home')
LOGOUT_REDIRECT__URL = '/'
enter code here
project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('accounts/', include('accounts.urls')),
path('accounts/', include('allauth.urls')),
path('', include('posts.urls')),
]
accounts/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('signup/', views.SignUpView.as_view(), name='signup'),
url(r'^accounts/', HomeView.as_view(template_name='../templates/home.html', name='home')),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', name='logout'),
]
accounts/views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic.base import TemplateView
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class SignUpView(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
class HomeView(TemplateView):
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(HomeView, self).dispatch(*args, **kwargs)
templates/home.html
<!--user checks-->
{% if user.is_authenticated %}
<div class = "greeting">
Hi {{ user.username }}!
logout
</div>
{% else %}
<div class = "register">
sign up!
</div>
login
<form method = "post" action = "{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<!--username bar-->
<div class="container-2">
{{ form.username.label_tag }}
{{ form.username }}
</div>
<!--pw bar-->
<div class="container-3">
{{ form.password.label_tag }}
{{ form.password }}
</div>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endif %}
You need to import url in accounts/urls.py:
from django.conf.urls import url

Unexpected NoReverseMatch error when using include() in urls patterns

I'm getting an error when referencing detail.html in index.html
Reverse for 'detail' with arguments '(3,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$(?P<pk>[0-9]+)/$']
views.py
def rock_and_feat(request):
feats = Feat.objects.order_by('-created')[:3]
rocks = Rockinfo.objects.order_by('-rank')[:50]
context = RequestContext(request, {
'feats': feats, 'rocks': rocks
})
return render_to_response('template.html', context)
class DetailView(generic.DetailView):
model = Feat
template_name = 'feature/detail.html'
context_object_name = 'feat'
urls.py
urlpatterns = [
url(r'^$', views.rock_and_feat, name='rock_and_feat'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]
index.html
{% extends "index.html" %}
{% block mainmast %}
<div id="wrapper">
{% if feats %}
{% for feat in feats %}
<div class="specialsticky">
<img src="{{ feat.image.url }}" alt="some text">
<h1 class="mast-header">
{{feat.title}}
</h1>
</div>
{% endfor %}
{% else %}
<p>No </p>
{% endif %}
</div>
{% endblock %}
detail.html
{% extends "index.html" %}
<iframe width="560" height="345" src="{{ feat.youtube_link }}" frameborder="0" allowfullscreen></iframe>
project urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', include('feature.urls', namespace="feature")),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
the app worked fine before I added the <a href= on the image in index.html.
Can't figure out what's wrong.
This indicates the problem.
'$(?P<pk>[0-9]+)/$'
There shouldn't be a dollar sign (which matches the end of the string) at the beginning of the pattern.
The problem is caused by the way you are including the urls.py. You currently have a dollar in the regex:
url(r'^$', include('feature.urls', namespace="feature")),
To fix the problem, remove the dollar from the regex.
url(r'^', include('feature.urls', namespace="feature")),

Problems in finding urls from the application template in Django

Here is the full map of my Poll application:
My Project/
Poll_app/
__init__.py
settings.py
urls.py
wsgi.py
polls/
migrations/
__init__.py
0001_initial.py
templates/
polls/
detail.html
index.html
results.html
__init__.py
admin.py
models.py
tests.py
urls.py
views.py
db.sqlite3
manage.py
Here, are the codes inside my files:
Poll_app/settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 't#o_s8#^88go6lx9haux#b^p%&g63r)03ai!9cw7dm%h#2mjy^'
DEBUG = False
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['localhost']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'Poll_app.urls'
WSGI_APPLICATION = 'Poll_app.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
Poll_app/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin', include(admin.site.urls)),
)
polls/admin.py
from django.contrib import admin
from polls.models import Poll
admin.site.register(Poll)
polls/models.py
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
polls/urls.py
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$',views.index,name='index'),
# ex: /polls/5/
url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
polls/views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Choice, Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
context = {'latest_poll_list': latest_poll_list}
return render(request, 'polls/index.html', context)
def detail(request, poll_id):
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render(request, 'polls/detail.html', {'poll':poll})
def results(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/results.html', {'poll': poll})
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render(request, 'polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
My templates:
polls/templates/polls/detail.html:
<<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.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>
polls/templates/polls/index.html:
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/polls/{{ poll.id }}/"{{ poll.question }}></a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
polls/templates/polls/results.html:
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
Vote again?
I have run my app like following:
python manage.py runserver
When i visit (from localhost) ../polls/results, the page shows the message The requested URL /polls/results was not found on this server.
I am having same result for ..../polls/votes also.
N.B.
While i access ..../polls/ i see a 'dot' only.
I am stuck here from yesterday. I have tried to rebuild the app for 2 times. And yet, still getting the same result again and again. May be, there are spelling errors or problems in setting the Poll_app/settings.py. It would be really helpful for me, if you help me to figure out the problem.
I think the problem is in polls/urls.py, your regexp pattern only catches those urls of form "../polls/some_number/results" but you are trying "../polls/results" which will not be catched. In the regexp try replacing + with * and then try to access the url like this ^(?P<poll_id>\d*)/results/$.
Hope this helps.
Check your urls settings.
# ex: /polls/5/results/
url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote')
so you should visit localhost:port/polls/poll_id/results

Categories