Django: Testing LoginView throwing AssertionError - django

Quesiton
I'm building a testing suite for my login process and immediately ran into a hiccup. I believe the issue is that LoginView is a 'class' while the code is testing it as a function. What is the proper way to assert that the URL resolved to the LoginView?
urls.py
from . import views
from users.views import *
from django.urls import path
from django.contrib.auth.views import LoginView, LogoutView
from users.forms import LoginForm
urlpatterns = [
path('', views.user_home_view, name='user_home'),
path('sign_up', views.SignUpView.as_view()),
path('login', LoginView.as_view(authentication_form=LoginForm), name='login'),
path('logout', LogoutView.as_view(), name='logout')
]
tests.py
from django.test import SimpleTestCase
from django.urls import reverse, resolve
from django.contrib.auth.views import LoginView, LogoutView
from users.forms import LoginForm
from users.views import *
# Create your tests here.
class UrlTestCase(SimpleTestCase):
def test_login_url_resolved(self):
url = reverse('login')
self.assertEquals(resolve(url).func, LoginView)
Testing Results (./manage.py test)
AssertionError: <function LoginView at 0x7f970ca05320> != <class 'django.contrib.auth.views.LoginView'>

This is because you are not getting back instance of LoginView class but appropriate method through as_view() entry point method
You can access class through attribute view_class which is set in as_view() method as documented
The returned view has view_class and view_initkwargs attributes.

Solution
self.assertEquals(resolve(url).func.view_class, LoginView)
See this: django how to assert url pattern resolves to correct class based view function

Related

Django is unable to find the view used for query params the other views are working perfectly

#urls.py
from django.urls import include,path
from rest_framework import routers
from . import views
router=routers.DefaultRouter()
router.register(r'banks',views.BanksViewSet)
router.register(r'branches',views.BranchesViewSet)
router.register(r'branches/autocomplete/',views.BranchAutocompleteViewSet, basename='branches')
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
#views.py
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import BanksSerializer,BranchesSerializer
from .models import Banks,Branches
class BanksViewSet(viewsets.ModelViewSet):
queryset=Banks.objects.all().order_by('id')
serializer_class= BanksSerializer
class BranchesViewSet(viewsets.ModelViewSet):
queryset=Branches.objects.all().order_by('ifsc')
serializer_class=BranchesSerializer
class BranchAutocompleteViewSet(viewsets.ModelViewSet):
serializer_class=BranchesSerializer
def get_queryset(self):
branchName=self.request.query_params.get("q")
limit=self.request.query_params.get("limit")
offset=self.request.query_params.get("offset")
queryset=Branches.objects.filter(branch__startswith=branchName).order_by('ifsc')[offset:limit]
return queryset
the BanksViewSet and BranchesViewSet are working fine but the other one is not working
the problem might be the basename in urls.py as changing it doesn't do anything even when left as an empty string.
this is what the console has:
Django version 3.1.5, using settings 'bankApi.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Not Found: /branches/autocomplete/
[19/Jan/2021 18:30:04] "GET /branches/autocomplete/?q=A&limit=5&offset=0 HTTP/1.1" 404 12148
Make sure your root url branches registered last like this:
...
router.register(r'banks',views.BanksViewSet)
router.register(r'branches/autocomplete/',views.BranchAutocompleteViewSet, basename='branches')
router.register(r'branches',views.BranchesViewSet) # root of 'branches' is last
...

Pass a file path as a URL parameter in Django

I'm using Django to create a webapp. When a user press on a certain button, it needs to pass a file path as parameter and a string parameter to one of my views. I can't simply use the parameter in the URL since the path contains several '/'. The way I have it setup right now is as follows:
parameters.py
class FilePathConverter:
regex = '^[/]'
def to_python(self, value):
value=str(value)
return value.replace("?", "/")
def to_url(self, value):
value=str(value)
return value.replace("/", "?")
urls.py
from django.urls import path
from . import views
from django.contrib import admin
from django.views import generic
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FilePathConverter, 'filepath')
urlpatterns = [
path('', views.index, name='webpanel-index'),
path('controlserver/<filepath:server_path>/<str:control>', views.index, name='controlserver'),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Server
from django.contrib.auth.decorators import login_required
import subprocess
def controlserver(request, server_path, control):
if request.POST:
subprocess.call(['bash', server_path, control])
return render(request, 'index.html')
However, with this method, I get this error:
Reverse for 'controlserver' with keyword arguments '{'server_path': 'rien/', 'control': 'start'}' not found. 1 pattern(s) tried: ['controlserver/(?P<server_path>[^/]+)/(?P<control>[^/]+)$']
you can use Slug to resolve this patterns by :
from django.utils.text import slugify
path('controlserver/use slug .....', views.index, name='controlserver'),
but you need to put slug at views and templates So check this list of slug and pk :
https://github.com/salah-cpu/migration/blob/master/PATH_slug_pk

ERROR:- as_view() takes 1 positional argument but 2 were given

After running the server i am getting error as as_view() takes 1 positional argument but 2 were given please have a look on below code and suggest me.
views.py
from django.views.generic import View
import json
class JsonCBV(View):
def get(self,request,*args, **kwargs):
emp_data=
{'eno':100,'ename':'pankhu','esal':300000,'eaddr':'pune'}
return JsonResponse(emp_data)
urls.py
from django.contrib import admin
from django.urls import path
from testapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('jsonapi3/', views.JsonCBV.as_view),
]
test.py
import requests
BASE_URL='http://127.0.0.1:8000/'
ENDPOINT='jsonapi3'
resp =requests.get(BASE_URL+ENDPOINT)
data=resp.json()
print('Data from django application')
print('#'*50)
print('Employee number:',data['eno'])
print('Employee name:',data['ename'])
print('Employee salary:',data['esal'])
print('Employee address:',data['eaddr'])
in your urls you have to write parentheses after .as_view()
path('jsonapi3/', views.JsonCBV.as_view())

page not found error in Django using a filter query {return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')}

I am making my first django practice project I have a view called PostListview :
from django.shortcuts import render
from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from blog.models import Post, Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.views.generic import(TemplateView,ListView,DetailView,CreateView,UpdateView,
DeleteView)
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
I have this in in the urls:
from django.conf.urls import url
from blog import views
urlpatterns = [
url(r'^$',views.PostListView.as_view(), name= 'post_list'),
And this is the template which is calling this view.
<li class="navbar-brand bigbrand" >My Tech Blog</li>
This view is also set as the default home view and it opens fine at the time i open the site url (localhost) but when I am clicking "My Tech blog " it gives a 404 error.
This is the main urls.py :
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.contrib.auth import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
url(r'accounts/login/$',views.login, name = 'login'),
url(r'accounts/logout/$',views.logout, name = 'logout',kwargs={'next_page':'/'}),
]
Just change
url(r'^$',views.PostListView.as_view(), name= 'post_list'),
with
url(r'',views.PostListView.as_view(), name= 'post_list'),

Not able to map a view with url

I am facing some problem while mapping a view with URL
Project name-Hero
app name-Movie
Hero/url.py:
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns=[
url(r'^admin/',admin.site.urls),
url(r'^',include('Movie.urls'))
]
Movie/urls.py:
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$',views.index,name='Movie'),
]
views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1>Hello friends ,Welcome to Django Project</h1>")
These are my urls and views configurations.I am getting a 404 page.
Please help me out.. Thanks
Try with below code, only changes in Hero/url.py
Hero/url.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns=[
url(r'^admin/',admin.site.urls),
url(r'',include('Movie.urls')) # Do not add caret sign if further urls contains caret.
]