Return and link to homepage django - python

I have a project in DJANGO with this structure:
/
|---- core
|---- client
In client/views.py, I have the code:
class ClientDelete(DeleteView):
model = Cliente
success_url = reverse_lazy('cliente_list')
Where client_list is the HTML page on client/clients that lists all clients.
In core/views.py module, I have the function:
def homepage(request):
return render(request, 'home.html')
Where "home.html" is the homepage.
My main urls.py is something like this:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^cliente/', include('clientes.urls')),
url(r'^about/', aboutpage),
url(r'^$', homepage),
]
I need to return and make a link into client, core, and other apps to homepage. But when I try to return homepage into client.views.ClientDelete, the url on browser didn't redirect to home, but shows something like:
localhost:8000/client/home when I want back to localhost:8000.
What should I do?
Thank you.

First, it is useful to set names for urls:
url(r'^$', homepage, name='home')
So for your code you should do:
class ClientDelete(DeleteView):
model = Cliente
success_url = reverse_lazy('home')
if you want to be redirected to home page.
You can also use namespaces if you have different apps. So you will be able to do:
# redirect to home
success_url = reverse_lazy('home')
# redirect to clients list
success_url = reverse_lazy('clients:list')
To use it you need to make following changes:
url(r'^cliente/', include('clients.urls', namespace='clients'))
and set a name for urls inside clientes.urls.
Docs:
https://docs.djangoproject.com/es/1.9/topics/http/urls/#url-namespaces-and-included-urlconfs

Related

how to properly redirect from one app to another app in django

i am a beginner to Django and i am unable to properly handle redirects from one app to another. I have 2 apps Accounts, Dashboard. Accounts Handles login and registration of AuthUser. Dashboard handles other functionality like Fileupload
So far, I have successfully using reverse() method have redirected from /accounts/login to my upload page but it redirects from /accounts/login to /accounts/upload instead of /dashboard/upload .
Project URLS
urlpatterns = [
path('dashboard/', include('Dashboard.urls')),
path('accounts/', include('Accounts.urls')),
path('admin/', admin.site.urls),
]
Account urls.py
urlpatterns = [
url('upload',DashboardViews.upload, name='upload'),
path('login', views.login, name='Login'),
path('register', views.register, name='Register'),
path('logout', views.logout, name='logout')
]
Account views.py
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
if request.method == 'POST':
user_name = request.POST.get("username")
password = request.POST.get("password")
user = auth.authenticate(username=user_name,password=password)
if user is not None:
auth.login(request,user)
return redirect(reverse('upload'))
else:
print('Failed')
return render(request,'login')
My intention is whenever user (login/register), web page should redirect from /account/login to /dashboard/upload.
This is because you have the upload url defined in the urlpatterns of your Accounts app.
You should place it in the urls.py file from the Dashboard app if you want the full path to be /dashboard/upload, instead of /accounts/upload.
To explain it a bit more, when you define a path with the include function, like this:
path("accounts/", include("Accounts.urls")
All the urls from the Accounts app will have "accounts/" appended at the beginning.
Note: If you add the name parameter to a path, you can use it in all your apps with the reverse function. The path doesn't have to be declared in the same app where you want to call the reverse function.
A good practice to avoid having url conflicts is to add the name of the app to the url. So you should maybe name the upload path as dashboard_upload.
I faced the same problem, but below technique worked for me.
In your urls.py file of Dashboard app, use app_name = "Dashboard". then in your redirect() function use appName:Path structure. For example, use redirect('Dashboard:upload')

How do I change the url back to mysite.com in django after loging in the user?

I have two apps in my django project. After loging the user in through "visit" app I redirect to "mainapp". However, my url patter becomes something like this : mysite/accounts/profile/
If I try specifying in urls.py I get redirected to "visit" app. How do I reset my url
visit/views.py
def profile(request):
return HttpResponseRedirect(reverse("main:home"))
main/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'accounts/profile', views.home, name='home'),
]
main/views.py
def home(request):
return render(request, 'main/home.html')
You could try specifying redirect url in your settings.py file. Just include LOGIN_REDIRECT_URL = /mainapp/accounts/profile/ in that file and it should work. LOGOUT_REDIRECT_URL is also something you can list in your settings file to specify where to redirect after user logout.

Logout not working Django 1.9

I'm building a Django website, but my logout is not working. The site consists in two apps, the main app that is public and the student app that is private. In my student app i've put the #login_required decorator in every method, except the logout method. But when i click the logout link in the student app, my page is not redirected to the main app, it goes to another view inside the student app, and when i reload the page, the content is still available although i've put the #login_required decorator. Here is my code:
website/urls.py
from main_app import urls as main_urls
from student_app import urls as std_urls
urlpatterns = [
url(r'^index/', include(main_urls)),
url(r'^student-area/', include(std_urls))]
website/settings.py
LOGIN_URL = '/index/login/'
LOGIN_REDIRECT_URL = '/student-area/'
main_app/urls.py
...
urlpatterns = [
url(r'^$', views.index, name='index'),
...]
student_app/urls.py
...
urlpatterns = [
url(r'^$', views.std_videos_view, name='student_area'),
url(r'^(?P<video_key>[a-zA-Z0-9\_\.]+)/$', views.std_video_detail_view, name='video_detail'),
url(r'^materials-std/$', views.std_material_view, name='materials_std_view'),
url(r'^download-material/(?P<material_key>[a-zA-Z0-9\_\.]+)/$', views.std_material_download, name='download_material'),
url(r'^sims/$', views.std_sim_view, name='sims_view'),
url(r'^download-sim/(?P<sim_key>[a-zA-Z0-9\_\.]+)/$', views.std_sim_download, name='download_sim'),
url(r'^contact/$', views.std_contact_view, name='std_contact'),
url(r'^logout/$', views.user_logout, name='user_logout')
]
student_app/views.py
from django.contrib.auth import logout
from django.shortcuts import redirect
...
def user_logout(request):
logout(request)
return redirect('index')
student_app/templates/student_area.html
...
Logout
...
I am lost in this problem, thank you in advance.
Your video_detail URL pattern matches /logout/. Django stops as soon as it finds a match, so requests for /logout/ will be handled by the std_video_detail_view view instead of the user_logout view.
You can fix this by either changing the regex for the video_detail URL so that it doesn't clash (for example you could use ^videos/(?P<video_key>[a-zA-Z0-9\_\.]+)/$), or by moving the logout URL pattern above the video detail pattern.

How to connect with Django REST framework to front-end

I'm new on Django REST Framework. I have an index.html where I have simple form for adding items and back-end with Django. I can't understand, how I can connect index.html to Django REST Framework.
I have the next code-files:
models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
category = models.CharField(max_length=100)
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from .models import Book
from rest_framework import viewsets
from .serializers import BookSerializer
class Index(TemplateView):
template_name = "index.html"
def get_context_data(self):
context = super(Index, self).get_context_data()
return context
class BookViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Book.objects.all().order_by('title')
serializer_class = BookSerializer
urls.py
from django.conf.urls import url, include
from rest_framework import routers
from myapp import views
router = routers.DefaultRouter()
router.register(r'books', views.BookViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
]
serializers.py
from .models import Book
from rest_framework import serializers
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Book
fields = ('title','category')
And if I run localhost:8000/index I get an error 'Page not found'. I can't understand how correct I should include my html pages to the django code. Should I use a router.register for this?
Let's start by defining what django-rest-framework is and what it is not.
It is a nice toolkit to build web APIs. This means that you can define several endpoints (urls) that will handle incoming requests and will return a response in JSON or XML format.
It is not an html rendering tool though. This means that you can't return a response that contains html code to be rendered as a page in the browser. It will return pure json or xml data.
Now, your questions consists of 2 problems:
You can't access the index.html page.
You don't know how to connect this page with the books endpoint.
Regarding problem 1
Check the TEMPLATES settings. Where is your index.html placed? Does django know where to find it? Check out the TEMPLATES setting and assure you have set it up correctly.
Regarding problem 2
Because of the fact that the django-rest-framework endpoint handles incoming requests, you need to generate such a request. But if you will simply access the endpoint in your browser, the page will load/reload and you will see the data from your endpoint in json form on your page.
For your page to remain the same, but at the same time to make a request to your endpoint, you need to use ajax (Asynchronous JavaScript and XML) from within your index.html page. You can emit an ajax request by using one of the following:
With pure JavaScript, by means of XMLHttpRequest class. See this SO question and answers to see how this is made.
If you use jQuery, it has a jQuery.ajax() method to make an ajax request.
If you use any other frontend framework (angular, backbone, ember, etc.), all they have an implementation of ajax calls. Check their documentation for that.
And basically that's it. Good luck!
Could you try putting the api url after your index like this?
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
url(r'^', include(router.urls)),
]
Or why not use /api/ for your REST Api urls:
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.Index, name='index'),
url(r'^api/', include(router.urls)),
]
And be sure that you have added 'rest_framework', to INSTALLED_APPS
EDIT:
To access /index/ you must fix your urls.py:
urlpatterns = [
url(r'^index/$', views.Index, name='index'),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

Django - custom admin page not related to a model

I am using Django 1.7 with Mezzanine. I would like to have some page in admin, where the staff can call some actions (management commands etc.) with buttons and other control elements.
I would also like to avoid creating new model, or manually create a template and add link to it (if possible).
What is the most common/clean ways how to achieve that?
Actually it is simpler. Just before urlpatterns in urls.py patch admin urls like that:
def get_admin_urls(urls):
def get_urls():
my_urls = patterns('',
url(r'^$', YourCustomView,name='home'),
)
return my_urls + urls
return get_urls
admin.autodiscover()
admin_urls = get_admin_urls(admin.site.get_urls())
admin.site.get_urls = admin_urls
ModelAdmin.get_urls let you add a url to the admin url's. So you can add your own view like this:
class MyModelAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
my_urls = patterns('',
(r'^my_view/$', self.my_view)
)
return my_urls + urls
def my_view(self, request):
# custom view which should return an HttpResponse
pass
https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_urls
I didn't try this out, but it seems to me that you can subclass a build-in admin view and let your custom template extend the build-in admin templates.

Categories

Resources