Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to submit a form with Django (Using UserCreationForm & ModelForm)
I've been trying to create a method to upload a profile picture for a user at the time of registration. In order to do so, I created a custom ModelForm with a file field and displayed this along with a UserCreationForm. However, it throws this error ValueError at /signup The UserProfile could not be created because the data didn't validate. Files :- models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) img=models.FileField(upload_to="profile/") def __str__(self): return self.user.username forms.py from django import forms from . models import UserProfile from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # Create your models here. class ImgForm(forms.ModelForm): class Meta: model=UserProfile fields=['img'] urls.py from django.urls import path from . import views urlpatterns = [ path('', views.signin, name="signin"), path('signup', views.signup, name="signup"), path('logout', views.logout, name="logout") ] views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth from django.http import HttpResponse from .forms import ImgForm from django.contrib.auth.forms import UserCreationForm # Create your views here. def signup(request): if request.method == 'POST': form=UserCreationForm(request.POST) imgform=ImgForm(request.POST, request.FILES) if form.is_valid() and imgform.is_valid(): #looks good user = form.save() img=imgform.save() img.user=user return redirect('/') else: html = "<html><body><script>alert('Invalid form')</script></body></html>" return HttpResponse(html) else: form=UserCreationForm() imgform=ImgForm() context={ 'form':form, 'imgform':imgform } return render(request, … -
Application error while deploying django webapp on Heroku
I tried a lot to solve this error but unable to solve it. I have searched a lot on every platform. Get Application Error: An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details. Heroku logs: 2020-03-24T14:33:58.867536+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 393, in stop 2020-03-24T14:33:58.867537+00:00 app[web.1]: time.sleep(0.1) 2020-03-24T14:33:58.867537+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 242, in handle_chld 2020-03-24T14:33:58.867537+00:00 app[web.1]: self.reap_workers() 2020-03-24T14:33:58.867538+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers 2020-03-24T14:33:58.867538+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2020-03-24T14:33:58.867539+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2020-03-24T14:33:58.969807+00:00 heroku[web.1]: State changed from starting to crashed 2020-03-24T14:33:58.952866+00:00 heroku[web.1]: Process exited with status 1 2020-03-24T14:34:13.000000+00:00 app[api]: Build started by user anil8826467317@gmail.com 2020-03-24T14:35:19.446665+00:00 heroku[web.1]: State changed from crashed to starting 2020-03-24T14:35:19.179491+00:00 app[api]: Deploy 939b3c20 by user anil8826467317@gmail.com 2020-03-24T14:35:19.179491+00:00 app[api]: Release v10 created by user anil8826467317@gmail.com 2020-03-24T14:35:25.763617+00:00 heroku[web.1]: Starting process with command `gunicorn naac_portal.wsgi` 2020-03-24T14:35:28.545775+00:00 app[web.1]: [2020-03-24 14:35:28 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-03-24T14:35:28.546436+00:00 app[web.1]: [2020-03-24 14:35:28 +0000] [4] [INFO] Listening at: http://0.0.0.0:29141 (4) 2020-03-24T14:35:28.546595+00:00 app[web.1]: [2020-03-24 14:35:28 +0000] [4] [INFO] Using worker: sync 2020-03-24T14:35:28.551237+00:00 app[web.1]: [2020-03-24 14:35:28 +0000] [10] [INFO] Booting worker with pid: 10 2020-03-24T14:35:28.603149+00:00 app[web.1]: [2020-03-24 … -
How to LIMIT number of different choices in my model that user can save? - Python Django
I have model UserDraft. Inside that model I have pick_id with different choices represented in numbers when u go into Django Admin. I want each choice to be limited to max 5 times for each user to be picked. For example in this code I want to have user1, 1, hero1, user1, 1, hero2, etc....Also i would love to restrict that you cant pick same hero twice. models.py from django.db import models from users.models import User from heroes.models import Hero from django.core.exceptions import ValidationError class UserDrafts(models.Model): FIRST = "1" SECOND = '2' THIRD = '3' PICK_ID = [ (FIRST, 1), (SECOND, 2), (THIRD, 3), ] user_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_id") pick_id = models.CharField(max_length=20, choices=PICK_ID) hero_id = models.ForeignKey(Hero, on_delete=models.CASCADE) def save(self, *args, **kwargs): if self.__class__.objects.filter(user_id=self.user_id).count() >= 5: raise ValidationError('Maximum five picks are allowed per user') return super().save(*args, **kwargs) def __str__(self): return self.user_id.username class Meta: verbose_name = "UserDraft" verbose_name_plural = "UserDrafts" This save method that I used only limits user to pick more then 5 times. But I also want to be able to restrict choices for each choice to be picked 5 times per 1 user...So maximum number of picks will be 15. 5 pick_id`s will be 1(FIRST), 5 will be … -
Django REST framework: How to use multiple PKs in URL with class based views/serializer
I have two models (examples): class Container(models.Model): name = models.CharField(max_length=100) class ObjInContainer(models.Model): Container = models.ForeignKey(Container, on_delete=models.CASCADE) A Container can have N number of ObjInContainer. I'm trying to write a REST API to do two things: First: See all ObjInContainer from a single Container: # urls.py url(r'^container/(?P<container_id>\d+)/objects_in_container/$', ContainerObjectsListAPIView.as_view(), name='container_objects_list'), # views.py class ContainerObjectsListAPIView(ListAPIView): queryset = ObjInContainer.objects.all() queryset = queryset.prefetch_related('container') serializer_class = ContainerObjectsListAPIView # serializer.py class ContainerObjectsListAPIView(ModelSerializer): container = SerializerMethodField() class Meta: model = ObjInContainer fields = [ 'id', 'container', ] def get_container(self, obj): return str(obj.container.name) But this lists all ObjInContainer from ALL Container. How do I tell REST Framework that the Container it needs to get the ObjInContainer from is the one in the URL from <container_id> ? I suppose in views.py where I declare queryset = ObjInContainer.objects.all(), should really be queryset = ObjInContainer.objects.filter(container_id=container_id), but how do I access the <container_id> part of the URL in the view class? Any my second issue is how to detail a single ObjInContainer, by using two different IDs in the URL? # urls.py url(r'^container/(?P<container_id>\d+)/objects_in_container/(?P<obj_in_container_id>\d+)/$', ContainerObjDetailAPIView.as_view(), name='container_object_detail'), # views.py class ContainerObjDetailAPIView(RetrieveAPIView): queryset = ObjInContainer.objects.all() serializer_class = ContainerObjDetailSerializer # serializer.py class ContainerObjDetailSerializer(ModelSerializer): container = SerializerMethodField() class Meta: model = ObjInContainer fields = [ 'id', 'container', ] … -
Accessing HTTP content from an HTTPS server || HTTP request blocked
My Django application currently runs on HTTPS in the server. Recently i added a new functionality for which it has access another link to get JSON object which is HTTP link. Its working fine in the localhost but when I deploy it in the server, it is showing the following error. Site was loaded over HTTPS, but requested an insecure resource http link. This request has been blocked; the content must be served over HTTPS. Can someone please suggest a workaround to bypass this so that the new functionality runs smooth. -
MultiValueDictKeyError at /login/ "uname,
im working on an ecommmerce site with python mysql and django.During login i'm getting MultiValueDictKeyError at /login/ can someone review this ... This is my login page error occurs on the name "uname": <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <center> <form action="/login/" method="POST"> {% csrf_token %} <input type="text" name="uname" placeholder="username"><br><br> <input type="text" name="pass" placeholder="password"><br><br> <input type="submit" value="Login"> </form> </center> </body> </html> This is my views.py using POST method: from django.shortcuts import render, redirect, HttpResponse from django.http import HttpResponse from . models import * def home(request): return render(request,'index.html') def fn_login(request): v_username = request.POST['uname'] v_password = request.POST['pass'] try: login_obj = Login.objects.get(username=v_username,password=v_password) if login_obj.password == v_password: return render(request,'index.html') return HttpResponse('incorrect password') except Exception as e: print(e) return HttpResponse('invalid username') This is myapp urls.py: from django.contrib import admin from django.urls import path # importing views from views..py from .import views urlpatterns = [ path('index/',views.home), path('login/',views.fn_login,), ] -
Pulling data from MongoDB existing databas with Django(Djongo)
So i am working on a proyect with mongodb and django(djongo) and i have to use an already existing database(MongoDB compass) and i cant find the way to pull or import the information from MongoDB, already try with: python manage.py inspectdb > models.py and python manage.py inspectdb and when create the models.py is not with the database instead it pulls the default MongoDb, already try the Documentation of django and nothing works. Anyone got some info about it? PD: my app is totally empty and already configured the settings.py as the documentation on Django instruct. Thanks in advance. -
Attribute error 'QueryDict' object has no attribute '_meta'
I'm trying to send a post request from PostMan into my Django view and I'm getting this error. "AttributeError: 'QueryDict' object has no attribute '_meta'" From what I've gathered it has something to do with the form.save() as seen in traceba I've searched all over to find a solution or even a better way to achieve an image post from a external web client to a Django server. All help is very much appreciated. Traceback Capture.PNG form is valid Internal Server Error: /getimg/ Traceback (most recent call last): File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\Gedit\Desktop\django\indivproj\getimg\api\views.py", line 21, in getimg form.save() File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", line 207, in save self.instance = self.update(self.instance, validated_data) File "C:\Users\Gedit\Desktop\django\virtualenv\lib\site-packages\rest_framework\serializers.py", … -
How to manually edit the usercreationforms dropdown menu in html?
I have used usercreationform in forms.py to create form in html page. It will automatically create field by using {{form. field}} that is fine, but I want to do manual dropdown list in html from forms.py that is I want to edit dropdown form field in html page. forms.py class SignupForm(UserCreationForm): username = forms.CharField(label="Roll No", help_text="Enter Valid RollNo") name = forms.CharField(label="Candidate Name", max_length=150) dob = forms.DateField(label="Date") email = forms.EmailField(max_length=100, help_text='Required') department = forms.CharField(label="Department", widget=forms.Select(choices=CHOICES)) edc = forms.ChoiceField(label="EDC", widget=forms.Select(choices=COURSE)) class Meta: model = User fields = ("username","name", "dob", "email","department",'password1','password2') signup.html is my html page {% block content %} <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> {{ form.username | as_crispy_field }} </div> <div class="form-group col-md-6"> {{ form.name|as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.dob | as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> {{ form.email | as_crispy_field }} </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.department | as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> **<p><label >EDC:</label> <select> {% for choices in form.edc %} <option value="{{choices}}">""</option> <option value="{{choices}}">{{choices}}</option> <option value="{{choices}}">{{choices}}</option> <option value="{{c}}">{{choices}}</option> {% endfor %} </select> </p>** </div> </div> <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.password1 | as_crispy_field }} </div> <div class="form-group col-md-4 mb-0"> … -
Error while updating multiple objects using django rest_framework serializers
I am making API for an order which can have multiple foods. I am able to create it successfully but when I try to update with food id, I am getting an error like NoneType object has no attribute 'get', please help me out with a solution. Here is my code models.py class Order(models.Model): order_no = models.PositiveIntegerField(blank=True,null=True) class VegFood(models.Model): name = models.CharField(max_length=25,blank=True,null=True) price = models.CharField(max_length=25,blank=True,null=True) order = models.ForeignKey(Order,on_delete=models.CASCADE,blank=True,null=True,related_name="order") serializers.py class VegFoodSerializer(serializers.ModelSerializer): class Meta: model = VegFood fields = ['name','price'] class OrderSerializer(serializers.ModelSerializer): """ for multiple add items importinf serializers in Order """ veg_foods = VegFoodSerializer(many=True,required=False) nonveg_foods = NonVegFoodSerializer(many=True,required=False) starters = StarterSerializer(many=True,required=False) deserts = DesertSerializer(many=True,required=False) class Meta: model = Order fields = ['order_no','veg_foods','nonveg_foods','starters','deserts'] def create(self, validated_data): veg_food_validated_data = validated_data.pop('veg_foods',None) if veg_food_validated_data: for veg_food in veg_food_validated_data: veg_food_obj = VegFood.objects.create(order=orders,**veg_food) return orders def update(self, instance, validated_data): instance.order_no = validated_data.pop('order_no', instance.order_no) veg_food_validated_data = validated_data.pop('veg_foods',None) if veg_food_validated_data: for veg_food in veg_food_validated_data: veg_food_id = veg_food.get('veg_food_id') print(veg_food_id) veg_foods, created = VegFood.objects.get_or_create(order_id=instance.id,id=veg_food_id) veg_foods.name = veg_food_id.get('name',None) veg_foods.price = veg_food_id.get('price',None) veg_foods.save() instance.save() return instance My JSON body is : { "order_no":1, "veg_foods":[ { "veg_food_id":1, "name":curry1, "price":150 }, { "veg_food_id":2, "name":curry2, "price":120 }, { "name":curry2, "price":120 } ] } So object1 & object2 I am passing id so it will update 1st … -
Django, Cant import Module from an App into project urls.py
Hi so i am trying to import a module from app my (views.py) into the project urls.py. It is not letting me import from my app though. I tried butting '''from project.AppFolder import views''' but it says no module found names that. I put a init.py in my project folder to try that and that still didnt work. the folder layout is -ProjectFolder ---ProjectFolder -----urls.py ---AppFolder -----views.py -
How can I custom 'startapp' command from django?
I want to custom startapp command to include some files like serializer and urls and overwriting existing model file, can someone help me to achive this? -
django on AWS with multiple settings file
Well, I had one setting file before and it was working perfectly both in local and AWS of course with both the database configuration in one setting file. When ever I use to push my code on AWS I would comment my local db configuration and then push. So for sure, that's annoying. I can't comment and uncomment constantly both the database configuration in one file. Therefore, I decided to have 2 setting files. one for the local and the other for AWS. Once I pulled the code into AWS server and run migrations python manage.py migrate --settings=settings.staging It worked and migrated. By the way, this is the setting file which resides my RDS configuration. Now the moment I hit the endpoints via postmant the output is as OperationalError at /account/v1/login could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? means it is still reading the default settings file. How come I make the server run this particular staging setting file. Do I have to declare it on nginx, supervisor or gunicorn? I'm using these 3 services as well. Below is my settings file for staging. from … -
How to fetch all data from firestore with python?
how can we get all data from firestore? is it possible in python? I have data like have 8 collections and each collections have 1 document and documents have 3 data like 'title' , 'content' and 'date'. So ı want to get all this data to use in my django project. I did a lot of research but didin't find any solutions. Is it impossible to get all data? can someone please explain? thanks in advance. Anyway , ı have a table in my web site and ı wan to put this data correctly but firstly ı need all data , ı can get each data like this: from google.cloud import firestore import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credentials.Certificate('firestore.json') default_app = firebase_admin.initialize_app(cred) db = firestore.client() doc_ref = db.collection(u'Title').document(u'Content') db.get try: doc = doc_ref.get() print(doc.to_dict()) except: print("ERROR") -
Django pass 2 variables from template to view using {%url%}
I am new in django so sorry if this is a dumb question. So I have 2 variables in a template - the song title and the song url. I know I can pass 1 variable using {%url '..path..' variable%} but when I try to pass 2 variables I get an error so I can't pass it like this: {%url '..path..' url title%}. How can I do this? -
Django 2.2.5, Multiple User Types with Django's built-in authentication system
I am creating a web application, there are 3 types of users superuser, taker and employer how could I implement this by using default authentication of Django. -
DJANGO TESTS: TypeError: test_suit_row_attributes() missing 1 required positional argument: 'request'
I want to resolve this error and finish the test: admin.py def suit_row_attributes(self, obj, request): """Add colours to the rows according to the status""" type_error = 'notSent' status_colours = {Transaction.STATUS_REJECTED: 'error', Transaction.STATUS_RECEIVED: 'received', Transaction.STATUS_PENDING: 'warning', Transaction.STATUS_ACCEPTED: 'success', type_error: 'notSent'} try: tt_status = Transaction.objects.get(txid=obj.numero).last_status except Transaction.DoesNotExist: tt_status = type_error return {'class': status_colours.get(tt_status, 'success')} in tests.py def test_suit_row_attributes(self): self.assertEqual(self.admin_instance.suit_row_attributes(self.errortr_obj), {'class': 'notSent'}) Can someone help me, please? -
How to get user object from request in django rest framework?
I want to get the password of curent user from request body and verify it. I am trying to get user object from request like this: class UserPasswordUpdateAsAdminViewSet(APIView): def patch(self, request, pk): serializer = ResetPasswordAsAdminSerializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) serializer.update_password() return Response(status=status.HTTP_200_OK, data={'success': True}) and below is my serializer: class ResetPasswordAsAdminSerializer(serializers.ModelSerializer): new_password = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True) def validate_password(self, attrs): self.user = None request = self.context.get("request") if request and hasattr(request, "user"): self.user = request.user if not self.user or not self.user.check_password(attrs['password']): raise CustomAPIException( status_code=status.HTTP_401_UNAUTHORIZED, message='Invalid password provided', error_code=None ) def validate_new_password(self, password): if not re.match(REGEX['password'], str(password)): raise CustomAPIException( status_code=status.HTTP_409_CONFLICT, message=None, error_code='password_policy_mismatch' ) return password def update_password(self): self.user.set_password(self.validated_data['new_password']) self.user.save() return class Meta: model = User fields = ('password', 'new_password') But on hitting the api, I am getting the following error: string indices must be integers What am I doing wrong? -
Google Storage - Django - How to provide access to video and image files based on Django User Authentication?
I have Django App where users can login with either Email, Google or Facebook accounts. Each user has media files stored in Google Storage. When I make Google Cloud bucket publicly available, it works as expected yet is there a way to make each Google Storage object accessible to only particular user ? What is the best proper way to achieve this ? -
Rowspan dynamically when the value repeat in django template
I want to make a table in Django html template. bBut I would like make a rowspan when the value is repeated. The information comes from a sql VIEWS.PY cursor=cnxn.cursor() cursor.execute(“ select * from itreporting”) ticketid = cursor.fetchall() cnxn.commit() ... documento=doc_externo.render({"ticketid":ticketid}) And I can show this table this way in HTML Template <table> <tr> <th>ticketid</th> <th>It component </th> </tr> {% for row in ticketid.0 %} <tr> <td>{{row.0}}</td> <td>{{row.4}}</td> </tr> {% endfor %} </table> And This is the result of the query ticketid | ItComponent SD-497 | AV543 PE SD-521 | AU232 CH SD-521 | SD233 CH SD-258 | SD456 CH SD-258 | AU234 CH But in the first column the date repete serverals time and I woul like to col span when it repete and the result I would like to obtain is this: <table border="1"> <tr> <th>ticketid</th> <th>It component </th> </tr> <tr> <td>SD-497</td> <td>AV543 PE</td> </tr> <tr> <td rowspan="2">SD-521</td> <td>AU232 CH</td> </tr> <tr> <td>SD233 CH</td> </tr> <tr> <td rowspan="2">SD-258</td> <td>SD456 CH</td> </tr> <tr> <td>AU234 CH</td> </tr> </table> I’ve been trying andding third column with the number of times the value column ticketid repeat, and I add this as a variable as call span <td callspan=”row.2”> {{row.0}}</td> But the result … -
Getting Error when creating another django project with same project name used earlier
D:\dj_proj>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, self._kwargs) File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 408, in check messages.extend(check_resolver(pattern)) File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Abhinav Anand\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 597, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the … -
Django xhtml2pdf download pdf instead open in browser
In my django project i have to create a pdf file from an html template and download it. After installing xhtml2pdf i create in my utils.py a function for render: utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None at this point in my url i call the relative method in views.py: @login_required def fatt_pdf(request, fat_num=None): template = 'pdf/doc-fattura.html' #Recall fat_det passing 'Y' at parameter is_pdf for returning dict instead render request context = fatt_det(request, fat_num, 'Y') pdf = render_to_pdf(template, context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice.pdf" content = "inline; filename='test.pdf'" download = request.GET.get("download") if download: content = "attachment; filename='test.pdf'" response['Content-Disposition'] = content return response return HttpResponse("Not found") all work done except for the fact that the pdf open in my browser and not automatically downloaded. I would to create the file "invoice.pdf" and automatically download it, someone can help me please So many thanks in advance -
Django Rest Framework ViewSet testing with JWT tokens
I'm trying to test my Django Rest Framework (DRF) views with a JWT token created by Firebase. I'm using a package called drf-firebase-auth to implement the actual authentication backend. Here're my current DRF settings: REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10, "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "drf_firebase_auth.authentication.FirebaseAuthentication", ], } When I use Postman to query the development API with the proper JWT token, everything seems to work fine. I get a response with a 200 code etc. and the payload contains what I know is in my development database. However, when I start writing tests for my views, I start getting 403 and 500 codes. Here's an example where I'm using DRF's RequestsClient client to do the actual testing: class UserViewsetTestCase(APITestCase): def setUp(self): self.token = get_firebase_id_token_v2() self.client = RequestsClient() self.base_url = "http://127.0.0.1:8000/api/users/" self.client.headers.update({"Authorization": f"JWT {self.token}"}) def test_user(self): response = self.client.get(self.base_url) self.assertEqual(response.status_code, 200) This leads to an assertion error noting that 500 != 200: ====================================================================== FAIL: test_user (organizations.tests.test_views.UserViewsetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Path/to/project/organizations/tests/test_views.py", line 32, in test_user self.assertEqual(response.status_code, 200) AssertionError: 500 != 200 Note that the utility function get_firebase_id_token_v2 returns the Firebase based JWT token for me on the server: def get_firebase_id_token_v2(): api_key = settings.FIREBASE_PUBLIC_API_KEY url … -
Django authentication not working for browser
I am trying to use django's inbuilt authentication system for my application. I'm able to authenticate a user during login but, for the following requests request.user.is_authenticated is coming as False login view: user_name = request_body['username'] password = request_body['password'] user = authenticate(username=user_name, password=password) if user is not None: login(request, user) request.session.set_expiry(86940) I've written a decorator to check authentication, the code is: from django.http import HttpResponse def authenticate_request(f): def check(request): if request.user.is_authenticated: #coming as false even after authenication is done return f(request) else: return HttpResponse(status=401) return check What am I missing while authenticating the request? -
What does mixin means in django?
Can you expalain what does following code does in detail and why get_context_data() neccesasary in this code? class UserRequiredMixin(SuccessMessageMixin, object): def dispatch(self, request, *args, **kwargs): usr = request.user if usr.is_authenticated: pass else: return redirect("eduapp:adminlogin") return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["org"] = Organization.objects.first() return context