Django Localhost Redirecting too many times - python-3.x

Hi there I created a decorator to protect a certain view from unauthorized persons though I am using django allauth to handle my authentications so I've used its login url. On testing whether the authorization works instead of redirecting me to the login page Localhost gets stuck in a redirect loop
here is a look at my code
decorators.py
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
def seller_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='account_login'):
'''
Decorator for views that checks that the logged in user is a seller,
redirects to the log-in page if necessary.
'''
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_seller,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
views.py
from django.views.generic import CreateView,DetailView, ListView
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from .decorators import seller_required
#method_decorator( seller_required , name='dispatch')
class SellerDashBoardView(ListView):
model = Seller
template_name = 'seller_dashboard.html'
App level urls
from django.urls import path
from .views import SellerSignUpView, SellerDashBoardView
urlpatterns = [
path('seller_reg/', SellerSignUpView.as_view(), name='seller_reg'),
path('seller/', SellerDashBoardView.as_view(), name='seller_dash')
]
project level urls
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('user.urls')),
#path('users/', include('django.contrib.auth.urls')),
path('accounts/', include('allauth.urls')),
path('', include('pages.urls')),
path('store/', include('store.urls')),
#path("djangorave/", include("djangorave.urls", namespace="djangorave")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Related

NoReverseMatch at / 'learning_logs' is not a registered namespace

I think i tired everything in trying to solve this problem.
I'm getting a NoReverseMatch i understand its from my "urls" but that's basically it, I was using url() instead of path().at the end of it all i just made a mess of my code.
view.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Topic as TopicModel
from .forms import TopicForms
# Create your views here.
def index(request):
""""the home page for learning app"""
return render(request,'learning_logs/index.html')
def topics(request):
topics = TopicModel.objects.order_by('date_added')
context = {'topics' : topics}
return render(request, 'learning_logs/topics.html',context)
def topic(request, topic_id):
"""show a single topic ans all its entries"""
topic = TopicModel.objects.get(id=topic_id)
entries = topic.entry_set.order_by('date_added')
context = {'topic':topic, 'entries': entries}
return render(request,'learning_logs/topic.html',context)
def new_topic(request):
"""add a new topic"""
if request.method != 'POST':
#no data submitted ; create a black form
form = TopicForms
else:
#POST data submited ; process data
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_log:topics'))
context = {'form': form }
return render(request,'learning_log/new_topic.html', context)
urls.py
#defins URL patterns for learning log
from django.conf.urls import url
from . import views
from django.urls import path
app_name = 'learning_log'
urlpatterns = [
#home page
path('', views.index, name ='index'),
#url(r'^$', views.index, name='index.html'),
#show topics
path('topics/',views.topics, name ='topics'),
# url(r'^topics/$',views.topics, name='topics.html'),
path('topics/<topic_id>',views.topic, name = 'topic'),
#url(r'^topics/(?P<topic_id>\d+)\$',views.topic,name='topic.html'),
path('topics/',views.new_topic, name = 'new_topic'),
#url(r'^topics/$',views.new_topic, name='new_topic.html'),
]
main urls.py
from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path, include
urlpatterns = [
path('', include('learning_logs.urls')),
path('admin/',admin.site.urls),
]
please anything I'm doing wrong plus any books or tutorials i can read because i think the book im using is outdated
Your app_name inside the urls file is "learning_log" but it seems your html folders are in learning_logs. Maybe something to do with that? Also can you make sure the app_name exists in your INSTALLED_APPS?
I've done a Udemy course for Django which was good for me but they are not free if you want to learn more.
just add the include param called namespace in your main urls.py for the app.
from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path, include
urlpatterns = [
path('', include('learning_logs.urls', namespace="learning_log")),
path('admin/',admin.site.urls),
]
here you have the documentation of URLs namespaces: https://docs.djangoproject.com/en/3.2/topics/http/urls/#url-namespaces
If you don't want to set the namespace you must call the url like this: reverse('topics')

Django REST Framework API : How to save/upload images with the name given by user(e.g. username.jpg) at Django server

I want to upload image with the name (which is given by user) at Django server through rest API,but i am not be able to find out the solution for this.Please tell me how to upload image with given name.
here is my code(mainly):
IN API TASK ->URLS:
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
from django.conf import settings
from myapi import views
from django.conf.urls.static import static
#Define API Routes
router = routers.DefaultRouter()
router.register(r'myimage', views.myimageViewSet) #we have only on viewset
urlpatterns = [
url(r'^',include(router.urls)),
url(r'^admin/',admin.site.urls),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
IN My API
1. MODEL
from django.db import models
# Create your models here.
class myimage(models.Model):
my_name=models.CharField(max_length=50)
my_image=models.ImageField(upload_to='Images/',default='Images/None/No-img.jpg')
def __str__(self):
return self.my_name
2.SERIALIZERS
from rest_framework import serializers
from .models import myimage
class myimageserializer(serializers.ModelSerializer):
class Meta:
model =myimage
fields=('id','my_name','my_image')
3. VIEWS
from django.shortcuts import render
from .models import myimage
from rest_framework import viewsets
from .serializers import myimageserializer
from rest_framework import filters
import django_filters.rest_framework
class myimageViewSet(viewsets.ModelViewSet):
queryset = myimage.objects.all() #We use Filters for Ordering so remove order_by part
serializer_class = myimageserializer
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,filters.OrderingFilter,)
ordering = ('id','my_name',)
4.ADMIN
from django.contrib import admin
from .models import myimage
admin.site.register(myimage)
You need to use FileParser to be able to get your image details in the request data object. I recommend you to follow the example in DRF's FileParser Example
I changed my code as mentioned below and now its working for me if you have any better solution please suggest here #happycoding
1. views.py
from django.shortcuts import render
from .models import myimage
from rest_framework import views
from .serializers import myimageserializer
import django_filters.rest_framework
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class myimageView(APIView):
def get(self, request):
myimagelocal= myimage.objects.all()
serializer = myimageserializer(myimagelocal, many=True)
return Response(serializer.data)
def post(self, request):
myname=request.data['my_image'].name
myformat=""
for c in reversed(myname):
myformat+=c
if c=='.' :
break
myformat=myformat[: : -1]
request.FILES['my_image'].name=request.data['my_name']+myformat
serializer = myimageserializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
IN API_TASK->URLS:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls,name='admin'),
path('',include('myapi.urls'))
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
IN API_Task->myapi->url
from django.urls import path
from .views import myimagedetailsView, myimageView
urlpatterns = [
path('myimage/', myimageView.as_view(),name='myimageView'),
]
Rest files unchanged

How to write regex properly in re_path django 3

The problem with my code is that I keep getting a "page not found (404) error, the path 'post/...' does not match" when I try to click on a hyperlink on my posts page. I made 3 posts. Could it be the regex? Because I'm currently not good at regex.
How can I match the views.py to the correct path in urlpatterns?
My urls.py is:
from django.contrib import admin
from django.urls import path, re_path
from blog import views as blog_views
urlpatterns = [
path('post/', blog_views.post),
re_path(r'^post(.*)/$', blog_views.post),
path('about/'. blog_views.about),
path('', blog_views.index),
path('admin/', admin.site.urls)
]
My views.py is:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Post
def index(request):
posts = Post.objects.all()
return render(request,'index.html', {'posts': posts})
def post(request, slug):
print(slug)
return render ('post.html',{'post': get_object_or_404(Post, slug=slug)})
def about(request):
return render(request, 'about.html', {})
You could use something like:
re_path(r'post/(?P<slug>[\w-]+)/$', blog_views.posts),
Do you really need to use re_path here? It would be simpler to use path:
path('post/<slug:slug>/', blog_views.post),

How to change the default search query parameter in URL in Django REST framework?

In Django REST Framework. By default it uses - /?search= in URL while searching for anything.
For Example http://127.0.0.1:8000/api/branches/?search=RTGS
And this url successfully getting the result.
But I need to change the URL to http://127.0.0.1:8000/api/branches/autocomplete?q=RTGS
In the documentation, https://www.django-rest-framework.org/api-guide/settings/#search_param
It is given that it is set by default. https://www.django-rest-framework.org/api-guide/settings/#search_paramd we can change.
I am wondering how.
Thanks
https://www.django-rest-framework.org/api-guide/settings/#search_param
urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
# router.register('bank', views.BankView)
router.register('branches/autocomplete', views.BankDetailView)
# router.register('branches/list', views.BankAPIListView)
urlpatterns = [
path('api/', include(router.urls)),
]
views.py
from django.shortcuts import render, redirect
from rest_framework import viewsets
from .models import Branches
from .serializers import BranchesSerializer
from rest_framework import filters
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import PageNumberPagination
# from django_filters.rest_framework import DjangoFilterBackend
class BankDetailView(viewsets.ModelViewSet):
queryset = Branches.objects.all()
serializer_class = BranchesSerializer
filter_backends = [filters.SearchFilter, OrderingFilter]
# Partial Search with the field in branch
search_fields = ['^branch']
# Ordering Filter field by ifsc in ascending order
# filter_backends = [DjangoFilterBackend]
# filterset_fields = ['ifsc']
serializers.py
from rest_framework import serializers
from .models import Branches
class BranchesSerializer(serializers.HyperlinkedModelSerializer):
class Meta :
model = Branches
fields = ['url' ,'ifsc', 'bank_id', 'branch', 'address', 'city',
'district', 'state']
http://127.0.0.1:8000/api/branches/autocomplete?q=RTGS&limit=3&offset=0
From the docs:
By default, the search parameter is named 'search', but this may be overridden with the SEARCH_PARAM setting.
Thus, in your settings.py:
REST_FRAMEWORK = {
'SEARCH_PARAM': 'q'
}
EDIT:
Here you can see the actual code:
Settings: https://github.com/encode/django-rest-framework/blob/master/rest_framework/settings.py#L68
Filters: https://github.com/encode/django-rest-framework/blob/master/rest_framework/filters.py#L42
If you'd like to change query parameter key in only one view, you can extend SearchFilter and then add it to filter_backends of your view.
class CustomSearchFilter(SearchFilter):
search_param = "q"
class MyListView(ListAPIView):
# ...
filter_backends = [CustomSearchFilter]
# ...

How to fix "ImproperlyConfigured" erros in django rest_framework urls.py

I am trying to figure out how django rest framework works and write some code. But i am getting
django.core.exceptions.ImproperlyConfigured: The included URLconf 'tutorial.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import
what is circular import? I can't understand. I created a app called quickstart inside i create serializers.py file.
quickstart/serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
quickstart/views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
quickstar/urls.py
from rest_framework import routers
from .views import UserViewSet, GroupViewSet
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = router.urls
testing/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('quickstart.urls')),
# path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('admin/', admin.site.urls),
]
can you please describe why this error happened frequently?
Thank you!

Resources