Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
No validated date returned by serializer
I get all the devices from a user and pass them to my serializer. He should return a supplier in validated data, but doesn't. Probably because I give more objects than one. How do I get validated data if I give more than one object? view: serializer_class = AdminSiteDevicePatchSerializer serializer = serializer_class( devices, many=True, data=request.data, partial=True, ) serializer.is_valid(raise_exception=True) serializer: class AdminDeviceInfoSerializer(AdminDeviceSerializer): class Meta(AdminDeviceSerializer.Meta): fields = AdminDeviceSerializer.Meta.fields + [ "supplier", ] def to_representation(self, device): data = super().to_representation(device) if not device.supplier: data["supplier"] = None data["supplier"] = SupplierSerializer(device.supplier).data return data -
I don't know why the url is not found
I have added a new action to the MeView called slack_user. But the api is not working and it says not found 404 error. from rest_framework.views import APIView class MeView(APIView): """ 認証ユーザー /users/me/ /users/me/slack_user/ """ serializer_class = MyUserSerializer def get(self, request, *args, **kwargs): serializer = self.serializer_class(request.user, context={'request': request}) return Response(serializer.data) def put(self, request, *args, **kwargs): serializer = self.serializer_class(request.user, request.data, context={'request': request}) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) @action(methods=['get', 'post', 'delete'], detail=True) def slack_user(self, request, *args, **kwargs): obj = request.user ... if request.method == 'GET': slack_user = obj.get_slack_user() return Response({}) if request.method == 'DELETE': obj.slack_users.all().delete() return Response(status=status.HTTP_204_NO_CONTENT) urls.py urlpatterns = [ path('login/', views.LoginView.as_view()), path('me/', views.MeView.as_view()), ] /users/login and /users/me/ work but /users/me/slack_user says not found. could you please help me with this error? -
Websocket Disconnecting channels
I'm trying to run a program based on django channels. After connecting through the browser I receive such messages. Is it Redis' fault or consumers.py?enter image description here -
How to setup separate server for celery periodic tasks?
I am having an issue with celery, so I want to know how to set up a separate server for Celery periodic tasks. As I have one application in Django hosted on AWS, so I want that ec2 instance to handle APIs only not to run periodic tasks. django celery python So can you please share your knowledge on same how to setup separate server for celery periodic tasks? Any help would be highly appreciated. Thank you. -
Autocomplete with specific values in Django for entry field
I am new in Django and want to make the entry field to be autfilled by productname when a user enters productcode (model Products). the below is my code: models.py class NM(models.Model): name = models.CharField(max_length=150) class Products(models.Model): productcode=models.CharField(max_length=200) productname=models.CharField(max_length=500) forms.py class NMForm(forms.ModelForm): name = forms.CharField(max_length=150) class Meta: model = NM fields = ('name',) views.py def home(request): if request.method == "POST": form = NMForm(request.POST) if form.is_valid(): for_m = form.save(commit=False) name = for_m.name template.html {% block content %} {% if user.is_authenticated %} <form method="POST" > {% csrf_token %} {{ form}} <button type="submit">OK</button> </form> {% endif %} {% endblock content %} I know that Django has inbuilt autocomplete.I researched and found some info but they does not work for me. I tried so far to enter the below code in template.html {% for field in form.visible_fields %} {{ field.errors }} {{ field }} {% endfor %} However it does not work. It does nothing. I would appreciate your help and any advice. -
Need Suggestion(Django Permissions) [closed]
I'm developing web application using django. Admin panel provide by django is enough good for development purpose. For the reason of simplicity, I want to transform django model permission in tabular format but I do not have sufficient idea that how to achieve this.enter image description here -
How to align card images in bootstrap 4.4 so that all the cards have equal width and height.?
So basically while making a simple website with Django and bootstrap 4.4 I came up with this issue. I was using 'cards' to add images of books in a grid format like in a bookstore web application. But the cards are not having equal dimensions. How to align card images in bootstrap 4.4 so that all the cards have equal width and height while keeping it responsive to the window size change.?? html <div class="container"> <div class="row"> {% for book in object_list %} <div class="col s3"> <div class="card"> <img class="img-fluid" src="{{book.book_image}}" alt=""> <div class="card-body"> </div> </div> <p class="text-white">{{book.name}}</p> </div> {% endfor %} </div> </div> and .css body{ background: white url('images/webbg.jpg') no-repeat center center; background-size: cover; } -
Should I use both Django views and Rest Framework together and how?
I will create a web app that mostly depends on basic CRUD operations but may change in the future (like getting data from another web service). I also will create a mobile app for my web app as well in order to do the same CRUD ops and the mobile app will use the REST API of my web app. So the question is that which way should I follow to accomplish these plans? Should I first create the REST API and then use it in my regular Django templates? Or should I create both the Django template views (CBVs, i.e. CreateView, UpdateView, DeleteView, ListView) and also REST API views separately? I really confused as I don't know what people do for such apps. Can you help me to have a roadmap? What would you do and why? -
How to send file (docx) to the user end so that user can download that file in django?
Please check the image File is located in the main project directory where the manage.py file is located ? -
Merge 2 models (tables) in Django and show it in my template
I have 2 models one defines all the all the devices that I have, and the other stores the information that the devices are obtaining. The code of they is the following, class Device(models.Model): dev_eui = models.CharField(max_length=16, primary_key=True) producer = models.CharField(max_length=20, blank=True, null=True) model = models.CharField(max_length=20, blank=True, null=True) firmware = models.CharField(max_length=10, blank=True, null=True) dev_name = models.CharField(max_length=20, blank=True, null=True) description = models.CharField(max_length=40, blank=True, null=True) fixed = models.BooleanField() dev_lat = models.FloatField(null=True, blank=True) dev_lon = models.FloatField(null=True, blank=True) deco_name = models.CharField(max_length=20) fleet_id = models.IntegerField(null=True, blank=True) class DevData(models.Model): data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False) data_id = models.IntegerField() dev_eui = models.CharField(max_length=16) gateway = models.CharField(max_length=25) data_timestamp = models.DateTimeField() rssi = models.IntegerField() snr = models.IntegerField() datarate = models.CharField(max_length=15) frequency = models.IntegerField() seq = models.IntegerField() data_1 = models.FloatField() data_2 = models.FloatField(null=True, blank=True) data_3 = models.FloatField(null=True, blank=True) data_4 = models.FloatField(null=True, blank=True) data_5 = models.FloatField(null=True, blank=True) data_6 = models.FloatField(null=True, blank=True) data_7 = models.FloatField(null=True, blank=True) Actually what I want is show a table in my template, combining all the data from devData and adding the dev_name and fleet_id from devices. Now what I'm doing is obtaining all the data and in the template filtering it. But I'm sure it's better and easier doing this in the views.py, but I don't know how. Reading … -
Django REST Framework, different serializers in same GenericView
I have a question regarding using only 1 view or end-point to make multiple requests. We have a url defined as path('ap/', APIndex.as_view()) where we'd like to both get all our AP models as well as create a new one. We have checked the link here, mostly the answer where Mohammad Masoumi mentioned the get_serializer_class method and the use of generic views. This has not worked however as we get the following error message when doing a simple GET request on the above URL. AttributeError at /ap/ 'APIndex' object has no attribute 'action' This occurs in our views_ap.py file in the get_serializer_class method. I have not been able neither to print the self to see what object I had in there. You'll find below our views_ap.py and serializers_ap.py: views_ap.py: from rest_framework import generics from ..models.model_ap import AP from ..serializers.serializers_ap import * from ..serializers.serializers_user import * class APIndex(generics.ListCreateAPIView): """List all ap, or create a new ap.""" # serializer_classes = { # 'get': APIndexSerializer, # 'post': UserIDSerializer, # # ... other actions # } queryset = AP.objects.all().order_by('id') # mapping serializer into the action serializer_classes = { 'list': APIndexSerializer, 'create': APCreateSerializer } default_serializer_class = APIndexSerializer # Default serializer def get_serializer_class(self): print(self) return self.serializer_classes.get(self.action, …