Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to design and implement a django app with user and activity period models.of using python and django
"periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" },ok": true, "members": [{ "id": "W012A3CDE", "real_name": "Egon Spengler", "tz": "America/Los_Angeles", "activity_ { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] }, { "id": "W07QCRPA4", "real_name": "Glinda Southgood", "tz": "Asia/Kolkata", "activity_periods": [{ "start_time": "Feb 1 2020 1:33PM", "end_time": "Feb 1 2020 1:54PM" }, { "start_time": "Mar 1 2020 11:11AM", "end_time": "Mar 1 2020 2:00PM" }, { "start_time": "Mar 16 2020 5:33PM", "end_time": "Mar 16 2020 8:02PM" } ] } ] } -
Splitting Posts Based on Category in Django
I'm currently in the process of adding a forum to my website, but I'm having trouble splitting posts up based on their category. This is how the forum will look and I hope to have the relevant posts in their relevant sections: This is the model and category choices I have added: CAT_CHOICES = ( ('General Discussion', 'General Discussion'), ('Events', 'Events'), ('Marketing', 'Marketing'), ) class Post(models.Model): """ A single forum post """ title = models.CharField(max_length=200) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True, null=True, default=timezone.now) views = models.IntegerField(default=0) category = models.CharField(choices=CAT_CHOICES, max_length=30,blank=True, null=True) image = models.ImageField(upload_to="img", blank=True, null=True) def __str__(self): return self.title Could anyone guide me on the next steps? -
How to set many to many field optional in django admin form
I want to make optional m2m field and implement setting values in django admin form using horizontal filter. In order to make it optional, I added some optional parameters in ManyToManyField class constructor. I set null param and blank param like the following. night = models.ManyToManyField(Recipe, related_name = "night", null = True, blank = True, verbose_name = 'Night Snack') But in add page, There's no horizontal filter like this image for setting night field values because it's optional. I want it to appear even when it's optional, so I can add some recipes or nothing into it. Could anyone solve this problem? -
I got error in the data insertion in Django
I'm trying to do the MySQL insertion in Django. I run the 'migration' command, I got 'django.db.utils.operationalError'enter image description here -
Override queryset 'only' method | Django
For reducing the number of queries when people access frequently queried foreign key references, I've created a custom manager which includes select_related always for the foreign key relation. Now that there are places in code where people have used only on this same model when creating a query set. How can I override only query set method to include this foreign key relation always. class CustomManager(models.Manager): def get_queryset(self): return super(CustomManager, self).get_queryset().select_related('user') When this model is used as below, I run into an error which says Field cannot be both deferred and traversed using select_related at the same time. Model.objects.only('id','field_1').get(pk=1) Anyway to mitigate this? I've to use select_related as above, since it will save lot of queries. -
How to customize stripe amount field from static to dynamic in django
My Website contains three books, each book has different price tags, lets say 500, 1000 and 2000 INR. The amount field working fine when i specify amount directly (as shown in code below i used 500 INR). But i want to make the amount field dynamic. So that i can provide different price tags for other books. views.py from django.shortcuts import render from django.views.generic.base import TemplateView from django.views.generic import DetailView from django.conf import settings from books.models import Book import stripe stripe.api_key = settings.STRIPE_SECRET_KEY class PaymentsPage(DetailView): model = Book template_name = 'payments.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context def charge(request): # will handle our payments (via tokens) if request.method == 'POST': charge = stripe.Charge.create( amount=500, currency='inr', description='A Django charge', source=request.POST['stripeToken'] ) payment_intent = stripe.PaymentIntent.create( amount=1099, currency='inr', description='Software development services', ) customer = stripe.Customer.create( name='Jenny Rosen', address={ 'line1': 'Delhi', 'postal_code': '110059', 'city': 'delhi', 'state': 'New Delhi', 'country': 'INDIA', }, ) return render(request, 'charge.html') -
Connect to MongoDB atlas from Django
I set up MongoDB on my Django project and i currently have a database hosted on MongoDB Atlas. I added MongoDB to my settings.py using Djongo, it works but the problem is that, instead of connecting to the database hosted on atlas, my code will look for a database with the same name on my local machine, what am i doing wrong? Here is how i set it up: 'secondDB': { 'ENGINE': 'djongo', 'NAME': 'one', 'HOST': 'mongodb+srv://myusername:mypass@test-2liju.mongodb.net/test?retryWrites=true&w=majority', } -
How to slice list items in Django Template using javascript (or similar)
everyone! I'm using chartJs with some data that I want the user to be able to dynamically change the number of items charted. Currently, I'm working on Django template with data calculated in a view in Python/Django that comes in a plain list (data: [5133.85, 1103.59, 1837.62, 378.90, 467.29, 107.35, 147.17, 0, ], for instance) The Django template code for the data of a dataset of my chart is as follows (which is listing the last 3 values of the list) and is working fine: data: [{% for data in list|slice:'-3:' %}{{ data|unlocalize }}, {% endfor %}] (the way this is written could be improved, I guess, but that's not the purpose of this post) My question is: I want the user to be able to change the number of items of the list, therefore, the number of columns of the chart, ie, that slice parameter above (-3). How can I do that using a javascript function? Something like <a href='' onClick='changeColumnsTo(5)'>Last 5 values</a> changing the parameter of the slice command in {% for data in list|slice:'-3:' %}{{ data|unlocalize }}, {% endfor %} I know I could solve the problem getting Django's views.py calculate the list with the N values … -
Comparing Two Urls Using Reverse And HTTP_REFERER
I am wanting to prevent a user from accessing a certain page unless they have been redirected. In order to do this I thought id do this: if(request.META.get('HTTP_REFERER') != reverse('some_page')): return redirect('some_page') This works almost perfectly except that request.META.get('HTTP_REFERER') returns the whole url address, while reverse('some_page') returns the abbreviated url. For example request.META.get('HTTP_REFERER') returnshttp://127.0.0.1:8000/page_one/some_page/ reverse('some_page') returns/page_one/some_page/ How can I either add the (sorry but I dont know the correct term) first part of the url (http://127.0.0.1:8000) to reverse('some_page'), or remove it from request.META.get('HTTP_REFERER') so they can be both compared in the if statement please? Thank you. -
Why my ViewSet keeps on looping after using for loop ang using get_object_or_404?
I am using extra actions for my image_tags endpoint for my images. I want to POST and DELETE for each image's image_tags. I was also able to use image_id for accessing each image using lookup_field in my Image. I have this endpoint for example, for an image IMG_123's image_tags: localhost:8000/my_app/images/IMG_123/image_tags This is my code: #models.py class ImageTag(models.Model): name = models.CharField() description = models.CharField() class Image(models.Model): image_id = models.CharField(unique=True) image_tags = models.ManyToManyField(ImageTag, blank=True) ... #serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' class ImageTagSerializer(serializers.ModelSerializer): image_tags = serializers.StringRelatedField(many=True) class Meta: model = Image fields = ('image_tags',) #views.py class ImageExtraAction(viewsets.ModelViewSet): @action(detail=True, methods=['get', 'post', 'delete']) def image_tags(self, request, capture_id=None): print("REQ", request.data) capture = self.get_object() data = request.data.copy() image_tags = request.data.get('image_tags') print("IMG", image_tags) #print("LEN", len(image_tags)) if image_tags: print("HERE") for tag in image_tags: obj_ = get_object_or_404(ImageTag, name=tag) data['image_tags'].append(obj_) print("DATA", data) serializer = ImageTagSerializer(capture, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ImageViewSet(ImageExtraAction, viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer lookup_field = 'image_id' ... #urls.py router.register(r'images', ImageViewSet, basename='image') When I post: {"image_tags": ["Urban", "Vegetation"]} I expect them to be added to image_tags field. However I am having problem since it keeps on looping at the codeblock: for tag in image_tags: obj_ … -
How to export filtered data from django-filters in csv fromat
I have a model like this: class Location(models.Model): name = models.CharField(max_length=100) name_short_code = models.CharField(max_length=50) address = models.CharField(max_length=100) and implemented django-filters like this: from django_filters import rest_framework as filters from api.models import Location class LocationFilter(filters.FilterSet): id = filters.NumberFilter(lookup_expr='icontains') name = filters.CharFilter(lookup_expr='icontains') address = filters.CharFilter(lookup_expr='icontains') class Meta: model = Location fields = ['id', 'name', 'address',] In views.py: from api.filter import LocationFilter class LocationViewSet(viewsets.ModelViewSet): queryset = Location.objects.all() serializer_class = LocationSerializer filter_backends = [filters.DjangoFilterBackend] filterset_class = LocationFilter URL-http://127.0.0.1:8000/api/location/?id=&name=Cafe&address= return the all data consisting location named cafe or any other filtered data How do i export it to CSV file? -
Storing file from dictionary in Django
So I've been working on a project and I'm facing a weird problem. So in my project I'm making a dictionary of data of user uploaded files and then sending the Json stringify data to Django backend. But at the end I'm getting this error: 'dict' object has no attribute '_committed'. Below is my full code: JS: var file = []; var files = {}; var jsonarr = []; var arr = []; file.push($('#lecturefile').prop('files')[0]); for(var i = 0; i < file.length; i++){ files = { 'lastMod' : file[i].lastModified, 'lastModDate': file[i].lastModifiedDate, 'name' : file[i].name, 'size' : file[i].size, 'type' : file[i].type, } arr.push(files) } for(i=0;i<content.length;i++){ jsonarr.push({'content': content[i], 'lecture': lecttitle, 'files': arr}) } $('#coursecont').val(JSON.stringify(jsonarr)) views.py coursecont = request.POST.get('coursecont') l = json.loads(coursecont) for i in range(len(l)): for j in range(len(l[i]['files'])): con = CourseContent.objects.latest('id') lecture = CourseLecture(file = l[i]['files'][j]) lecture.save() I know that uploading file data like this is causing the problem but do anyone knows a work around? -
Hospital Management System Project
I am newbie in django world and made some basic project like blogging site. Q1) I want to make project like this I but i am not getting how to differentiate HR,receptionist from doctor , patient and not letting them to register. Q2) In video we see that when Hr opens doctor profile some extra fields appear should i create Employee model with foreign Key relation doctor model and also Hr can't delete doctor but can edit . -
Why ThreadedProcessPoolExecutor stucks?
I am running a Django server in which I am running a function in ThreadedProcessPoolExecutor for parallelism but after some time of perfectly running it stuck! I did some research on it and now I think its a deadlock, tried changing kinda everything but none works Below is that piece of code. import json import os from time import sleep import shutil from HardCode.scripts import BL0 from HardCode.scripts.cibil.Analysis import analyse from HardCode.scripts.cibil.apicreditdata import convert_to_df from analysisnode.settings import PROCESSING_DOCS, CHECKSUM_KEY, FINAL_RESULT from threadedprocess import ThreadedProcessPoolExecutor from analysisnode import Checksum import requests def parallel_proccess_user_records(user_id): user_data = json.load(open(PROCESSING_DOCS + str(user_id) + '/user_data.json')) cibil_df = {'status': False, 'data': None, 'message': 'None'} if os.path.exists(PROCESSING_DOCS + str(user_id) + '/experian_cibil.xml'): response_parser = convert_to_df(open(PROCESSING_DOCS + str(user_id) + '/experian_cibil.xml')) cibil_df = response_parser sms_json = json.load(open(PROCESSING_DOCS + str(user_id) + '/sms_data.json', 'rb')) try: if len(sms_json) == 0: limit = analyse(user_id=user_id, current_loan=user_data['current_loan_amount'], cibil_df=cibil_df, new_user=user_data['new_user'], cibil_score=user_data['cibil_score']) response_bl0 = { "cust_id": user_id, "status": True, "message": "No messages found in sms_json", "result": { "loan_salary": -9, "loan": -9, "salary": -9, "cibil": limit } } else: response_bl0 = BL0.bl0(cibil_xml=cibil_df, cibil_score=user_data['cibil_score'], user_id=int(user_id) , new_user=user_data['new_user'], list_loans=user_data['all_loan_amount'], current_loan=user_data['current_loan_amount'], sms_json=sms_json) shutil.rmtree(PROCESSING_DOCS + str(user_id)) try: os.makedirs(FINAL_RESULT + str(user_id)) except FileExistsError: pass except Exception as e: print(f"error in middleware {e}") limit = analyse(user_id=user_id, … -
How can I add a Django constraint that limits the number of foreign keys based on a column value?
Consider the following code: (Using Python 3.7 and Django 2.2) from django.core.validators import MinValueValidator from django.db import models class Parent(models.Model): limit = models.IntegerField(validators=[MinValueValidator(1)]) class Child(models.Model): parent = models.ForeignKey(Parent, related_name='children') Is it possible to add a CheckConstraint such that the number of allowed Child's for each Parent is limited by the limit field on the Parent. For example something like the following on the Parent table: models.CheckConstraint( check=models.Q(limit__gte=models.Count('children')), name='children_limit', ) To clarify: I would really prefer to do this a database constraint, I know how to do it in Python land. -
Modifying file extension in django
I'm doing a form to upload some files to my system and then work with it. First, upload the file is working well but when I want to change the extension of my uploaded file crashes. Below I show my function, from django.core.files.storage import FileSystemStorage import os def uploadKMZ(request): if request.method == 'POST': # Save the file updated uploaded_file = request.FILES['document'] name = uploaded_file.name fs = FileSystemStorage() fs.save(uploaded_file.name, uploaded_file) # Modify the extension (NOT WORKING) thisFile = uploaded_file.name name, ext = os.path.splitext(thisFile) os.rename(thisFile, name + ".zip") return render(request, 'data_app/kmzTemplate.html') The error is FileNotFoundError, why is not founding it if the file is the same but just changing the extension? Thank you very much! -
Pycharm debugger getting error when break point is kept
In my project, I am using Django==2.1.5 on Pycharm IDE 2019.2 and I'm facing this error 1) I have tried to fix this problem by removing the .idea folder and reconfigured, the problem was not solved. 2) I have tried uninstalling the python and re-installed, the problem was not solved. 3) I have updated the Pycharm and tried, the problem was not solved the same error is throwing. Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace object at 0x0576E6F0> Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2019.2\helpers\pydev_pydevd_bundle\pydevd_constants.py", line 328, in get_current_thread_id AttributeError: '_DummyThread' object has no attribute 'pydevd_id' During handling of the above exception, another exception occurred: SystemError: ..\Objects\codeobject.c:851: bad argument to internal function The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2019.2\helpers\pydev_pydev_bundle\pydev_monkey.py", line 718, in call File "C:\Program Files\JetBrains\PyCharm 2019.2\helpers\pydev_pydevd_bundle\pydevd_constants.py", line 335, in get_current_thread_id File "C:\Program Files\JetBrains\PyCharm 2019.2\helpers\pydev_pydevd_bundle\pydevd_constants.py", line 302, in _get_or_compute_thread_id_with_lock SystemError: returned a result with an error set -
Django GPU server pricing
I have developed an Android app based on machine learning. The user can select an image that is sent to a Django app that does some heavy machine learning calculations and returns the result. I would like to know if it is posible to host my Django app in a way that I only pay GPU for the actual use of the GPU, that is, when a user sends a petition. I mean, I need my Django app to be always available but don’t want to be paying hourly for GPU inactivity time. -
Add something to another template block
Django 3.0.6 base.html {% load static %} {% include 'general/header.html' %} <body> <div class="content"> {% block content %} {% add_to_script jquery %} {% endblock content %} </div> {% include 'general/footer.html' %} footer.html {% block scripts %} {% endblock %} </body> </html> Problem Could you tell me whether it is possible to write {% add_to_script jquery %} that adds <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> to scripts block? -
Modifying the values of a Django model instance without overwriting the original values on the database
I have a model in my Django app, whose instance fields are entered by the users through a form. Afterwards, when the user entry is done, the users would need to recall the instance created and either: a) pass it on as it is (no problem here) b) modifying a couple of values and pass it on with the values modified (however, the new values should not be saved on the database, as the instance should remain the original one) What would be the best practice to alter a couple of values without actually overwrite the original instance on the database? Thanks a lot. -
How can i write custom Lint rules for my code editor?
How can i create my own lint rules for code editor which is web based. I am working on python Django, and want to write a own lint rules for RISC-V Assembly language in order to detect errors in code editor while writing RISC-V Assembly. For Example: As you can see in image there are expected 3 arguments when i write two arg its shows red line and when i take courser on it, it shows the what type of error this is. I want to make something like this with my own lint rules. Write Own lint rules. Then make a plugin type thing that can integrate with my web based editor by using java script or anything else. If anyone can tell me the path to how to create own lint rules or provide a quick start or provide any guide line for it. I don't care about the language in the end there should be plugin type thing that will integrate with my web based code editor. Thanks in advance. -
Should return statement in a view go to end or in middle?
I tried to find some sort of consistent rule on this but couldn't find one, so I turn to StackOverflow In Django views, what is considered a better practice: a return statement in middle of view (for example, if-else statement) or at the end of the few? For comparison, consider following hypothethical situation, where the response type needs to change based on some arbitary condition: def example(request): response = HttpResponse(content='500 Server error', status=403) if request.user.username == 'wolf': response = HttpResponse(content='No, bad wolf, no access', status=503) elif request.method == 'GET': response = render(request, 'barn/barn.html') else: data, status = get_barn_data(request.POST) response = JsonResponse(data=data, status=status) return response vs def example(request): if request.user.username == 'wolf': return HttpResponse(content='No, bad wolf, no access', status=403) elif request.method == 'GET': return render(request, 'barn/barn.html') data, status = get_barn_data(request.POST) return JsonResponse(data=data, status=status) Which one of these would be preferred? Django tutorials seem to jump between two variants. -
Supervisor/Gunicorn/Django: supervisor unable to RUN gunicorn ('fixed' on STARTING)
I try to deploy my Django project using Nginx/Gunicorn and supervisor. When I run gunicorn directly it works: (envCov) zebra@zebra:~/intensecov_app/intensecov$ gunicorn coverage.wsgi:application [2020-05-27 09:41:59 +0000] [45637] [INFO] Starting gunicorn 20.0.4 [2020-05-27 09:41:59 +0000] [45637] [INFO] Listening at: http://127.0.0.1:8000 (45637) [2020-05-27 09:41:59 +0000] [45637] [INFO] Using worker: sync [2020-05-27 09:41:59 +0000] [45639] [INFO] Booting worker with pid: 45639 Issue came when I try to used supervisor after config (see below). I run this 3 command: (envCov) zebra@zebra:~/intensecov_app/intensecov$ sudo supervisorctl reread intensecov-gunicorn: available (envCov) zebra@zebra:~/intensecov_app/intensecov$ sudo supervisorctl update intensecov-gunicorn: added process group (envCov) zebra@zebra:~/intensecov_app/intensecov$ sudo supervisorctl status intensecov-gunicorn STARTING As you can see, gunciron programm is STARTING but never RUNNING I try to 'manually' restart but git an error : (envCov) zebra@zebra:~/intensecov_app/intensecov$ sudo supervisorctl restart intensecov-gunicorn intensecov-gunicorn: stopped intensecov-gunicorn: ERROR (spawn error) /etc/supervisor/conf.d/intensecov-gunicorn.conf [program:intensecov-gunicorn] command = /home/zebra/envs/envCov/bin/gunicorn coverage.wsgi:application user = zebra directory = /home/zebra/intensecov_app autostart = true autorestart = true -
Trying to run background task while simultaneously updating the view in django
I'm working on a project analysing real time data and plotting it in a graph that updates every 10 seconds. I've been trying to make a django web app of this little program but I'm not sure how to: Run a background task, continuously analysing data. Every 10 seconds, push this new data onto the view. Or render this data in the view, without breaking the function than needs to be analysing continuously. What could I look into? Thank you. -
How can I debug my Django models to see what the properties contain?
I created a model in a Django application. Let's say I have a model class Car in models.py. This class has a method called refuel() that interacts with the class' properties. I want to write a Python script that imports models.py, instanciates the class and calls refuel() so to then debug the class using Breakpoints with my IDE. However, for some reason, I cannot import the model file in another script. When I use this syntax to import the file: from .models import Car I get this error: ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package Note that the script I import the model in is located in the same folder as models.py. What's the way of solving this problem, or, more broadly, what's the best way of debugging my model file ? Thanks.