I'm having a problem with the way my URL's look in Django. I have a view like this:
def updatetext(request, fb_id):
Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])
fb = get_object_or_404(Account, pk=fb_id)
return render(request, 'myapp/account.html', {
'success_message': "Success: Settings updated.",
'user': fb
})
When a user clicks on the URL to update the text they are then redirected to the account page but the URL then looks like 'account/updatetext/'. I would like it just be 'account/'.
How would I do this in Django. What would I use in place of render that would still allow me to pass request, 'success_message' and 'user' into the returned page but to not contain the 'updatetext' within the URL?
[edit]
The urls.py file looks like this:
from django.conf.urls import patterns, url
from myapp import views
urlpatterns = patterns('',
url(r'^home/$', views.index, name='index'),
url(r'^(?P<fb_id>\d+)/$', views.account, name='account'),
url(r'^(?P<fb_id>\d+)/updatetext/$', views.updatetext, name='updatetext'),
url(r'^(?P<fb_id>\d+)/updatepages/$', views.updatepages, name='updatepages'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^admin/$', views.useradmin, name='admin'),
)
You need to actually redirect the user to '/account/'. Rather than returning a call to render you can do the following:
from django.http import HttpResponseRedirect
def updatetext(request, fb_id):
Account.objects.filter(id=fb_id).update(display_hashtag=request.POST['hashtag'])
fb = get_object_or_404(Account, pk=fb_id)
return HttpResponseRedirect(reverse('account', kwargs={"fb_id": fb_id}))
However, it would be better to pass in a call to reverse into the HttpResponseRedirect constructor, but since I don't know your urls.py I just wrote the relative url.
Related
I'm new to Django and I'm trying to make a learning log website.
When I try to restrict my topics with login_required function I get a 404 error.
Here is my code:
from django.contrib.auth.decorators import login_required
#login_required(login_url='/users/login/')
def topics(request):
""" Show all topics."""
topics = Topic.objects.order_by("date_added")
context = {"topics": topics}
return render(request, "learning_logs/topics.html", context)
I get this error whenever I use the decorator in my code:
Using the URLconf defined in learning_log.urls, Django tried these URL
patterns, in this order:
admin/
users/ login [name='login']
users/ logout [name='logout']
users/ registration [name='register']
learning_logs/ยจ
The current path, users/login/, didn't match any of these.
The url works fine but when I use the decorator it breaks.
that means you have not defined the django builtin login in your url to solve it you can just past that inside you urls.py
##urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('users/login/', auth_views.login, name='login'),
path('users/logout/', auth_views.logout, name='logout'),
path('admin/', admin.site.urls),
]
if you have already done that you need to do the following in views
##views.py
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
#login_required(login_url=reverse_lazy("login"))
def topics(request):
""" Show all topics."""
topics = Topic.objects.order_by("date_added")
context = {"topics": topics}
return render(request, "learning_logs/topics.html", context)
It looks like your users urls don't have trailing slashes. Make sure that the URLS in your users/urls.py end with slashes. For example:
urlpatterns = [
url(r'^login/$', LoginView.as_view(), name='login')
]
I am currently working with my Django authentification app. My goal is once the user logged in successful I want to redirect it to the index page where my code shows a customised message:
messages.success(request, 'Login Successful', extra_tags='alert alert-dark')
My problem is I didn't manage to 'access' LoginView in my views.py.
I read about SuccessMessageMixin, but this LoginView won't work (Template Not Found):
class LoginView(auth_views.LoginView):
template_name = "accounts/login.html"
Do you have any idea how to solve this?
Only as long I include template_name in my urls.py it works, but I can't add the success message mixin there.
urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
]
You have a custom LoginView, but in the urls.py you call auth_views.LoginView.
To call your custom view you should do
from <module_name>.views import LoginView
urlpatterns = [
path('login/', LoginView.as_view(), name='login'),
]
It's a good idea to have a different name for your custom view, i.e.CustomLoginView.
You can add the followng snippet in the settings.py files:
LOGIN_REDIRECT_URL = '/'
You can add your own index page URL in 'LOGIN_REDIRECT_URL' variable
My app is hosted on shezankazi.pythonanywhere.com
When I open this link I get to index.html. However I would like to open login.html directly as occurs when I choose "Anmelden" at the index page. Herefore I require assistance
This is my views.py
def index(request):
return render(request, 'crm/index.html')
class MyRegistrationView(RegistrationView):
def get_success_url(self, request, user):
return '/crm/'
This is my app/urls.py
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
from crm import views as crm_views
from person import views as person_views
urlpatterns = [
url(r'^$', crm_views.index, name='index'),
url(r'^crm/', include('crm.urls')),
...
]
And this is my crm/urls.py
from django.conf.urls import url
from crm import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^dashboard/', views.dashboard, name='dashboard'),
]
And this is the end of my settings.py:
# If True, users can register
REGISTRATION_OPEN = False
# One-week activation window; you may, of course, use a different value.
ACCOUNT_ACTIVATION_DAYS = 7
# If True, the user will be automatically logged in.
REGISTRATION_AUTO_LOGIN = False
# The page you want users to arrive at after they successful log in
LOGIN_REDIRECT_URL = '/crm/dashboard/'
# The page users are directed to if they are not logged in,
# and are trying to access pages requiring authentication
LOGIN_URL = '/accounts/login/'
# The page users are directed to upon logging out
LOGOUT_REDIRECT_URL = '/accounts/login'
At first I changed the index view to render registration/login.html but then whenever I enter my credentials, the login page loads again instead of redirecting me to the dashboard.
change the order of the following two lines:
url(r'^$', views.index, name='index'),
url(r'^dashboard/', views.dashboard, name='dashboard'),,
and change the following:
return '/crm/dashboard/'
I have my url:
url(r'^home/', HomeQuestionView, name='home_question') ,
When I enter localhost:8000/home I get my homepage but what I want is when I just enter I get my homepage.
I mean I want to redirect to the above homepage url when user enters only my site likewww.xyz.com not www.xyz.com/home
I dont want to configure in this way
url(r'^', HomeQuestionView, name='home_question') ,
Thanx in advance
Use generic RedirectView:
from django.views.generic.base import RedirectView
url(r'^$', RedirectView.as_view(url='/home/')),
I found this solution (long story short, you need to add views.py to your main project folder and make view which redirect your empty route to your url):
In your urls.py inside urlpatterns add this:
urlpatterns = [
...
path("", views.home, name="home"),
...
]
In main Django folder create views.py and import it in urls.py
example
In views.py add this code:
from django.shortcuts import render, redirect
def home(request):
return redirect("blog:index") # redirect to your page
Now every time your url will be empty like (localhost:8000) it will be redirected to (localhost:8000/your_adress). Also, you can use this not only with blank url, but anywhere you need this sort of redirection
I'm totally new to Django, and I'm trying to understand how does it work (I'm more used to PHP and Spring frameworks.
I have a project called testrun and inside it an app called graphs, so my views.py looks like:
#!/usr/bin/python
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, World. You're at the graphs index.")
then, in graphs/urls.py:
from django.conf.urls import patterns, url, include
from graphs import views
urlpatterns = patterns(
url(r'^$', views.index, name='index'),
)
finally, at testrun/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'testrun.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^graphs/', include('graphs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
However, when I try to access http://127.0.0.1:8000/graphs/ I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/graphs/
Using the URLconf defined in testrun.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, graphs/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
What am I doing wrong that I can't get that simple message to be displayed in the browser?
To expand on my comment, the first argument to patterns() function is
a prefix to apply to each view function
You can find more information here:
https://docs.djangoproject.com/en/dev/topics/http/urls/#syntax-of-the-urlpatterns-variable
Therefore in graphs/urls.py you need to fix the patterns call like so:
urlpatterns = patterns('', # <-- note the `'',`
url(r'^$', views.index, name='index'),
)