Common start for url in all paths in team - python

I'm just working on a project in Django 1.11.
I have a problem with how to make a common beginning of the url.
For example, after creating a team, the address for all members should look like this:
domain.com/name_of_team
domain.com/name_of_team/blog
domain.com/name_of_team/blog/title_of_post
Main url file in project:
urlpatterns = [
url(r'', include('blog.urls', namespace='blog')),
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^admin/', admin.site.urls),
]
Urls in blog:
url(r'^$', login_required(RedirectToHome.as_view()), name='redirect_home'),
url(r'^t/(?P<pk>[0-9]+)/$', login_required(BlogHome.as_view()), name='blog_list'),
url(r'create/$', login_required(BlogCreate.as_view()), name='blog_create'),
url(r'^(?P<pk>[0-9]+)/delete/$', login_required(BlogDelete.as_view()), name='blog_delete'),
url(r'^(?P<pk>[0-9]+)/update/$', login_required(BlogUpdate.as_view()), name='blog_update'),
url(r'^(?P<pk>\d+)?/?$', login_required(BlogDetail.as_view()), name='blog_detail'),
Maybe there are some good practices for dealing with url addresses?

To make the blog application specific to each team you could include it's URLs with;
url(r'^(?P<team_slug>[\w-]+)/', include('blog.urls', namespace='blog')),
This obviously assumes that your Team model has a slug field so that you can safely add it to the context & use it to form your URLs for the blog application.
You could then have a Mixin that could be shared by views in the blog or add something to a shared base view which loads the Team
from django.views.generic.base import ContextMixin
from .models import Team
class TeamMixin(ContextMixin):
def get_context_data(self, **kwargs):
context = super(TeamMixin, self).get_context_data(**kwargs)
context['team'] = Team.objects.get(slug=kwargs.get('team_slug'))
return context

Related

In django how to generate dynamic url after domain name for every page?

I am building a blog website where I set a unique title for every article. I want the article should have url domain_name/<article_title>/.
Suppose I have model A and Moel B:
class A(models.Model):
title = models.CharField(max_length=500,unique=True)
class B(models.Model):
title = models.CharField(max_length=500,unique=True)
app.urls.py file :
urlpatterns = [
path('',view.index,name="index"),
path('contact/', contact, name="contact"),
path('about/', about, name="about"),
path('terms-and-conditions/', terms, name="terms_and_conditions"),
path('privacy/', privacy, name="privacy"),
path('<str:title>/', article_details, name="article_details"),
]
I have view file as follows:
def article_details(request,title):
if 'title_in_model_A':
render 'some_page_A'
if 'title_in_model_B:
render 'some_page_B'
render(request,'app/404.html')
project.urls file:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('app.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
handler404 = 'app.views.view_404'
My question is:
Is this type of page rendering good or not?
Does 404 request handles correctly?
The way OP is doing is ok, but if one wills it's possible to simplify the article_details view by using the shortcut get_object_or_404, like
from django.shortcuts import get_object_or_404
def article_details(request,title):
article = get_object_or_404(A, title=title)
In order to customize the 404 view one can use handlers. Here's a good example in the docs.
Hard to say if OP's renders correctly because the question doesn't show that OP has a clothes app with a view_404 in views.py.
As per OP's new requirement, in the case of having two models and wanting to check the existence of instances that have the title matching a specific one, then OP can use exists() as follows
def article_details(request,title):
if A.objects.filter(title=title).exists():
# render page A
elif B.objects.filter(title=title).exists():
# render page A
else:
# 404
Note that this method is good if one doesn't need the model but are just checking the existence. If one does need it as well, then one can include inside of the condition the following (before the render)
my_model = MyModel.objects.get(title=title)

Unregister a viewset from drf router

I have two separate apps Product and Tag which i used another app Product_tags to connect them together. in this way, if one of them don't exists, another one will work fine. inside Product_tags, I created a new TagProductSerializer which inherits ProductSerializer and I just added a new field named tag in fields list. product_tags/serializers.py:
class TagProductSerializer(ProductSerializer):
tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all())
class Meta:
model = Product
fields = [
'title',
'tags',
]
#...
and I did the same with Product viewsetproduct_tags/views.py
class TagProductViewset(ProductViewset):
serializer_class = SocialProductSerializer
and in my product_tags/urls.py I imported my Product router and i wanted to register my product viewset again for router. and there is my problem:
product/urls.py
router = routers.DefaultRouter()
router.register('product', ProductViewset)
urlpatterns = [
path('', include(router.urls)),
]
product_tags/urls.py (PROBLEM)
from product.urls import router
from .views import TagProductViewset
router.unregister('product') # I'm looking for something like this
router.register('product',TagProductViewset)
NOTE: I want to show the tags when getting product and because of that, I don't want to use different url for getting tag (e.g "api/product/tags/")
First Try:I tried to register the 'product' again (router.register('product',SocialProductViewset)) but it doesn't works
I fixed my problem but i forgot to say that here. I just created new router in my product_tags/urls.py and then I added it in urlpatterns inside of project/urls.py at top of my original product router.
product_tags/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import TagProductViewset
router = DefaultRouter()
router.register('product',TagProductViewset)
urlpatterns = [
path('', include(router.urls)),
]
project/urls.py
from django.urls import path, include
urlpatterns = [
path('api/v1/', include("product_tags.urls")),
path('api/v1/', include("product.urls")),
]

how to read html file on Django

I started make a website for my school project, i use Django Frameworks
i want to make my homepage website, i already have html file, then what should i do to make Django read my homepage
enter image description here
this is my urls.py on main folder
urlpatterns = [
path('admin/', admin.site.urls),
path('katalog/', include('katalog.urls')),
path('', ) #what should i write here?
]
django doc: https://docs.djangoproject.com/en/3.0/topics/http/urls/#example, it offers the below example
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
You have to create in your apps views.py file a FBV or CBV, the easiest is a FBV like below:
def someview(request):
context={}#if you want to add objects to the front end
return render(request, 'yourhtmlfile', context)
and then import it in your urls.py:
from . import views
urlpatterns = [
path('home/', views.someview),

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 url not finding a template using CreateView in Class-Based Views

I have created a page where a user can add a new item (notes in this case) and I am making use of CBV which I have recently started learning.
This is my model form
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ('title', 'note', 'tags')
This is the view in views.py
class NoteCreate(CreateView):
model = Note
form_class = NoteForm
template_name = "add_note.html"
Then this is the url as I used in the urls.py of the app
from django.conf.urls import patterns, url
from . import views
from madNotes.views import NoteCreate, NoteIndex,
urlpatterns = patterns(
'',
url(r'^notes/add/$', NoteCreate.as_view(), name="new_note"),
url(r'^$', NoteIndex.as_view()),
url(r'^(?P<slug>\S+)/$', views.NoteDetail.as_view(), name="entry_detail"),
)
NB: I used the same url as the main page at 127.0.0.1:8000 in the projects urls.py file and it worked.
I have seen several tutorials and even the docs and can't seem to find what I am doing wrong. Will I also need to add a function in order for it to be saved in the db or the CBV will do it all?
EDit: The error I get is this
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/notes/add/
Here is the project's urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from MadNotez import settings
from registration.backends.default.views import RegistrationView
from madNotes.forms import ExRegistrationForm
if settings.DEBUG:
import debug_toolbar
urlpatterns = patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
url(r'accounts/register/$', RegistrationView.as_view(form_class = ExRegistrationForm), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^admin/', include(admin.site.urls)),
url('^markdown/', include('django_markdown.urls')),
url('^notes/', include('madNotes.urls')),
#url(r'^$', views.NoteCreate.as_view(), name="new note"), when I used it here it worked
)
you say that is the urls.py of the app, which means it is included by the project's urls.py.
As you show now, all the app's URIs go under the notes prefix:
url('^notes/', include('madNotes.urls')),
so as things stand at present the correct URI for the page is
http://127.0.0.1:8000/notes/notes/add/
In order to clean things up a bit, I'd suggest to modify the app's urls.py to
url(r'^add/$', NoteCreate.as_view(), name="new_note"),
so that the page can be reached at
http://127.0.0.1:8000/notes/add/
This way all the app's pages/services are available under the notes prefix and with a simple name that is consistent with their action (i.e. add, delete, etc)

Categories

Resources