Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Datetime received a naive datetime whereas I precised before the timezone
I am working a Django project. Here is my code : today = datetime.datetime.now() currentperiod = Day.objects.get(enddate__gte=today.date(), startdate__lte=today.date()) And I got that message : RuntimeWarning: DateTimeField Day.startdate received a naive datetime (2021-10-04 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s.%s received a naive datetime " So I tried that : today = datetime.datetime.now() today = pytz.timezone("Europe/Paris").localize(today, is_dst=None) currentperiod = Period.objects.get(enddate__gte=today.date(), startdate__lte=today.date()) But it does not work whereas I used pytz, I suppose it comes from today.date() but I don't know how to proceed further ... Could you help me please ? Thank you very much ! -
Django add to many to many field working without save
What's the difference between group.reportedBy.add(request.user) group.save() AND group.reportedBy.add(request.user) It gets saved to the DB even without me doing .save() -
want to return dictionaries in lists Python Django
I want to return dictionaries of lists. With total, grand total, tax amount and name in each list. ''' #branches tax report and total - FBR and NFBR def branch_report(request, params): branch = Order.value('name', 'sub_total', 'grand_total', 'tax_amount') report = report[''] for name in Order.find_all('name'): info = { "name": branch.get('name'), "sub_total": branch.get('sub_total'), "grand_total": branch.get('grand_total'), "tax_amount": branch.get('tax_amount'), } report.append(info) return response_format(SUCCESS_CODE, SUCCESSFUL_RESPONSE_MESSAGE, report) ''' I want a result like this: ''' { "code": 200, "message": "Request was Successfull", "data": { "branches": [ { [ { "name": "Bedian 1", "id": 13, "sub_total": null, "tax_amount": null, "grand_total": null, "with_fbr_sub_total": null, "with_fbr_tax_amount": null, "with_fbr_grand_total": null, "without_fbr_sub_total": null, "without_fbr_tax_amount": null, "without_fbr_grand_total": null } ] } ''' -
Why is django not able to display Images and videos in AMP-story player
I have been stack on weeks trying to resolve this issue, I don't know why the AMP Story wouldn't load images that I post through the Django database, but somehow i have observed a very strange behavior of it being able to load images and videos which are not been requested from the database and also if images are been loaded from the asset directory i have to add the image format like JPG, PNG etc.. in order for it to display in the AMP Player. My major concern now is : 1.How do I request images and videos from the Django database to be able to work in the amp story player? 2.Since the player needs me to specify the file format of the image eg, JPG,PNG,JPNG etc.. How do i go about it? Here is a sample code of what i did, This is the player! {% extends "base.html" %} {% block content %} {% for a in amp %} <amp-story standalone title="Joy of Pets" publisher="AMP tutorials" publisher-logo-src="assets/AMP-Brand-White-Icon.svg" poster-portrait-src="assets/cover.jpg"> <amp-story-page id="cover"> <amp-story-grid-layer template="fill"> <amp-img srcset="{{ a.images.url }}" width="720" height="1280" layout="responsive" amp-story-player-poster-img> </amp-img> </amp-story-grid-layer> <amp-story-grid-layer template="vertical"> <h1>{{ a.title }}</h1> <p>{{ a.description }} </p> </amp-story-grid-layer> </amp-story-page> <!-- Page 1 (Cat): … -
How do I build a points based voting system (Django)
I have designed a system with five tables. Two tables are of users, buyers and sellers. And the remaining two tables are of products and companies. The buyers can have a relationship with the products and sellers can have relationships with products. The sellers and products also have relationships with the companies. Please note that the product can change companies at any time. Also, seller, product and buyer are all people (I labeled them that way for clarity) Now where I need help, I need to know how to design this part of the system based on this requirement. I need to create a points based rating system that will rate like a quiz, in such a way that; Every seller can rate product. Every product can rate seller. Both buyer and seller can rate company Company can rate product and seller Admin of the rate can rate companies and sellers SUMMARY Existing Relationships Buyer - products seller - products sellers - company product - company Goal Sellers will have 3 set of ratings from (buyers, company, product) each set with different unique parameters to rate. Product will have ratings from sellers alone Companies will have 3 sets of ratings … -
TinyMCE: Django admin custom HTML field displays incorrectly in HTML page
I use Django on backend and VueJS on frontend. I use tinymce for creation custom HTML field. description = CustomHTMLField('Description', blank=True, null=True) Settings for tinymce: TINYMCE_DEFAULT_CONFIG = { 'plugins': 'print preview textcolor importcss searchreplace autolink autosave save directionality visualblocks visualchars fullscreen image link media codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists wordcount textpattern noneditable help charmap emoticons', 'toolbar': 'insert | undo redo | formatselect | bold italic backcolor forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help', 'cleanup_on_startup': True, 'custom_undo_redo_levels': 10, 'width': 'auto', 'language': 'ru', } TINYMCE_FILEBROWSER = True Code of CustomHTMLField: from contextlib import suppress from tinymce import HTMLField class CustomHTMLField(HTMLField): def pre_save(self, model_instance, add): if not add: return super(CustomHTMLField, self).pre_save(model_instance, self.attname) html_field: str = getattr(model_instance, self.attname, "") with suppress(AttributeError): return html_field.replace('../../../../', '../../../../../') I need to add some text with list into this field. On Django admin page I have indent: But on frontend I don't have the indent: How can I fix the problem? -
i need help to convert this code from django to nodejs
i need help to convert this code from django to nodejs def post(self, request): path = '/achievements/achievements.json' base = str(settings.BASE_DIR) try: with open(base+path) as f: achievements = json.load(f) except: return Response(status=status.HTTP_404_NOT_FOUND) for achievement in achievements: self.find_or_create(achievement) return Response({'data': achievements}, status=status.HTTP_200_OK) -
Django : How to get month data in week wise format in django
class Car(models.Model): name= models.CharField() model = models.CharField() date = models.DateTimeField(default=datetime.now) This is my Model ( Car ) If I pass date params ( 2021-07-09 ), I need last 1 month of data from this date. ( Eg : 2021-07-9 - 30 DAYS ). I'm using Django Rest framework. I need 30 days of data's in week format ( 7 days data in one set like wise..) can anyone help me to come out of this situation.. Thank you...!! -
Filter django model using Dictionary Comprehension
I have a model, called cards, which contains a number of elements I want to loop through. So I was trying to use some dictionary comprehension as follows: cards = Card.objects.filter(device=device) output = { c.id : [c.generateData(), c.sensor.getLatestTime()] for c in cards} While running that code, it breaks on the output statement with the following error: The QuerySet value for an exact lookup must be limited to one result using slicing. Most of the pre-existing answers I found for that exact error were for cases where the queryset is being confused with a single field, as in 1, 2. However in my case, I am expecting, and handling it as a queryset by looping through it. I have also seen a question that is similar in here about using dictionary comprehension on the models, however as far as I can see, my format is almost the same (Unless the list as a second parameter is causing an issue somehow?) -
daphne run in supervisor returns an error django.core.exceptions.ImproperlyConfigured
why daphne returns an error to me via supervisor django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure () before accessing settings. But when I run it out of supervisorctl, it works. I have a system variable defined. Is it a mistake to run it in venv?. supervisor conf [fcgi-program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:8099 # Directory where your site's project files are located directory=/srv/app/ # Each process needs to have a separate socket file, so we use process_num # Make sure to update "mysite.asgi" to match your project name command=/srv/venv/bin/daphne -u /srv/run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers mysite.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=1 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # Choose where you want your log to go stdout_logfile=/srv/log/daphne.log redirect_stderr=true -
Django-filer upload location change
How do I access image URLs for Filer-fields also how to change the upload location Class CustomFilters(models.Model): input_file = models.ImageField( upload_to='input/images/', blank=True, null=True) bg_image_one = FilerFileField(null = True,on_delete = models.CASCADE) name = models.CharField(max_length=50) action = models.CharField(max_length=150, choices=ACTION_CHOICES) is_active = models.BooleanField(default=False) Currently, i am trying this bg_image_one.image.url -
What is the best WAY to create a django model instance with a model form with blank and null set true on certain fields?
I have the following model: class Foo(models.Model): field1 = models.CharField(max_length=100) field2 = models.ForeignKey(AnotherModel, on_delete=models.CASCADE) field3 = models.ImageField(blank=True, null=True) field4 = models.CharField(max_length=15, blank=True, null=True) And here is my view: def myView(request): form = FooForm(request.POST or None) if form.is_valid(): # What is the best to extract to filled fields by the user # so that I will know what to pass the objects.create() method field2 = form.cleaned_data.get('field1) # how to know if that's empty since it is not required Foo.objects.create(field1="do not want it to be empty" ) What is the best way to check if the value of the fields is not empty and pass it to the create method? -
I get this django error 421, b'service not available (connection refused, too many connections when signing up for my account, i dont really know?
SMTPConnectError at /investor/signup (421, b'service not available (connection refused, too many connections)') This Error has been delaying for days now, i'm really stuck while sending email with django and i'm a beginner in django that why i do not have many idea on how to solve this issue please can anyone help? Setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxxxxxxxxxxxxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxxxxxxxxxx!?' EMAIL_USE_TLS = True -
buffer = _builtin_open(filename, 'rb') PermissionError: [Errno 13] Permission denied: 'C:/Users/Users/OneDrive/Desktop/projects/Barracuda'
Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1483, in _exec pydev_imports.execfile(file, globals, locals) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 11, in execfile stream = tokenize.open(file) # @UndefinedVariable File "C:\Users\bbuug\AppData\Local\Programs\Python\Python39\lib\tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') PermissionError: [Errno 13] Permission denied: 'C:/Users/bbuug/OneDrive/Desktop/projects/Barracuda' Process finished with exit code 1 -
On what level in the django MTV architecture does the Django Rest Framework work?
I understand that django is an MTV architecture. I also understand that M is models, T is templates (which are views in MVC) and V is views (which are controllers in MVC). I want to understand if the django serializers and views are views or templates according to the MTV when using Django Rest Framework. -
Django StreamHttpRequest running multiple cameras
I am building an App using opencv and django with multiple cameras attached. I intend to build a preview feature which allows to open 1 camera after another to check their focus. However, I have tried with streamhttpresponse and does not find a way to close the stream manually, in which case even if I close the window and try to open another camera, it always failed. I will have to refresh the webpage and open a new camera. The question is, can I turn off the streamhttpresponse? (afaik it might not be possible) Or as an alternative way, open a new response that can somehow replace the existing one. Hope someone can help. Thanks. -
Django websocket ValueError [closed]
When I access a websocket on a non-existent put, django raises an error Is this normal behavior or should I handle this case? Traceback (most recent call last): File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/dgd/'.``` -
Django api function for total of branches in POS
Below is my code for an api function, I want to return each branch of a bakery with their sub total, tax amount and grand total. I've been given this task to do this function only. The other parts like models etc are already completed. ''' #branches tax report and total - FBR def branch_report(request, params): try: orders = Order.objects.filter(is_removed=False).values_list('id') branch = BusinessBranch.objects.filter(is_removed=False).values_list('id') for each in branch: total = int(orders.objects.aggregate(total=sum('sub_total'))['total']) g_total = int(orders.objects.aggregate(g_total=sum('grand_total'))['g_total']) fbr_tax = int(orders.objects.aggregate(fbr_tax=sum('tax_amount'))['fbr_tax']) ctx['g_total'] = g_total ctx['fbr_tax'] = fbr_tax ctx['total'] = total for each in branch: return response_format(SUCCESS_CODE, SUCCESSFUL_RESPONSE_MESSAGE, g_total, fbr_tax, total) except Exception as e: return response_format(ERR_GENERIC, str(e)) ''' -
Got error when implementing two jquery plugins? please, help me to work this function
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> <title>Hello, world!</title> <!--Slick--> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css"> <link rel="stylesheet" type="text/css" href="http://kenwheeler.github.io/slick/slick/slick-theme.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css"> <style> .slider-item { width:50%; } .slider-nav { width:50%; } </style> </head> <body style="background-color: rgb(151, 148, 144);"> <h1>Hello, world!</h1> <div class="col-md-6"> <div class="d-flex flex-column align-content-center justify-content-center"> <div class="slider-for m-2"> <img src="product1.png" width="80" id="showcase"> <img src="product2.png" width="80" id="showcase1"> <img src="product3.png" width="80" id="showcase2"> <img src="product2.png" width="80" id="showcase3"> <img src="product3.png" width="80" id="showcase4"> <img src="product1.png" width="80" id="showcase5"> </div> <div class="ms-3 px-2 mt-5 d-flex justify-content-center"> <div class="slider-nav"> <div class="slider-item"><img src="product1.png" width="80"></div> <div class="slider-item"><img src="product2.png" width="80"></div> <div class="slider-item"><img src="product3.png" width="80"></div> <div class="slider-item"><img src="product2.png" width="80"></div> <div class="slider-item"><img src="product3.png" width="80"></div> <div class="slider-item"><img src="product1.png" width="80"></div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <!--Jquery--> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!--slick--> <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.js"></script> <!--zoom--> <script src="ddpowerzoomer.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('.slider-for').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: true, asNavFor: '.slider-nav' }); $('.slider-nav').slick({ slidesToShow: 3, slidesToScroll: 1, asNavFor: '.slider-for', dots: false, arrows: true, centerMode: false, focusOnSelect: true, }); }); jQuery(document).ready(function($){ //fire on DOM ready $('#showcase').addpowerzoom() //add zoom effect to images with CSS class … -
else function is not working in views.py django
My if condition is working but my else condition is not working. Even if we provide condition for else it is returning the response of except block. import json from owner.models import Owner @csrf_exempt def register(request): if request.method == 'POST': payload = json.loads(request.body) username = payload['username'] password = payload['password'] contact = payload['contact'] company_name = payload['company_name'] owner = Owner(username=username, password=password, contact=contact, company_name=company_name) global response response = 0 try: if Owner.objects.get(username__exact = username): response = json.dumps([{'Error': 'Username already taken'}]) else: owner.save() response = json.dumps([{'Success':'Owner added successfully'}]) except: response = json.dumps([{'Error': 'Owner could not be added!'}]) return HttpResponse(response, content_type='text/json') -
Django: Multiple Select Form (Widget)
I would like to create a form to a model with m2m relation to another one (~10k data). It's a multiple-choice field, so how to adjust the form to show already selected options? User should also has a possibility to remove one from any from the already selected options without deleting all of them. Any search bar is possible to be attached to that form? Currently it looks like: Form field Thanks in advance. -
Using multiprocessing in a django administration command script is yielding unexpected error
I am trying to build a custom administration command in my django project. I started using concurrent.futures.ThreadPoolExecutor() for executing my code parallely. This works well as shown here: def my_function(param_1=None): # this function needs to be executed parallely class Command(BaseCommand): def handle(self, *args, **options): status = True while status: my_model_data = my_model.objects.exclude( some_id__isnull=True ).exclude( some_id__exact='0' ).exclude( other_id__exact=0 ).filter( status="pending" )[0:2] if not my_model_data: continue with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for row_data in my_model_data: futures.append( executor.submit( my_function, param_1=row_data ) ) for future in concurrent.futures.as_completed(futures): try: print(future.result()) except Exception as e: print(e) I was looking for other alternatives for this, where I tried following 2 approaches: Approach 1: with Pool() as p: try: for row_data in my_model_data: p.starmap( my_function, list(row_data) ) except Exception as e: print(e) Approach 2 (Referred from here): def subprocess_setup(): django.setup() with ProcessPoolExecutor(max_workers=5, initializer=subprocess_setup) as executor: try: for row_data in my_model_data: executor.map( my_function, list(row_data) ) except Exception as e: print(e) In both these approaches I get the following error: 'my_model' object is not iterable Any help would be great! -
Django Virtual Environment - No module named 'gunicorn'
I've followed this guide (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04), but I'm presently seeing the following when trying to run gunicorn via the gunicorn service file (/etc/systemd/system/gunicorn.service): Oct 04 11:30:22 ukgcdeploy01 gunicorn[8095]: File "/opt/envs/automation-console-env/bin/gunicorn", line 5, in <module> Oct 04 11:30:22 ukgcdeploy01 gunicorn[8095]: from gunicorn.app.wsgiapp import run Oct 04 11:30:22 ukgcdeploy01 gunicorn[8095]: ModuleNotFoundError: No module named 'gunicorn' The gunicorn.service file contains the following: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/opt/envs/automation-console-env ExecStart=/opt/envs/automation-console-env/bin/gunicorn --timeout 600 --log-level debug --error-log /var/log/automation-console-env_error.log --access-logfile /var/log/automation-console-env_access.log --workers 3 --bind unix:/opt/envs/automation-console-env/automation-console-env.sock django_forms.wsgi:application [Install] WantedBy=multi-user.target Running gunicorn manually works fine: gunicorn --bind 0.0.0.0:8000 myproject.wsgi This was previously working before I had to upgrade my Python version from 3.5.2 to 3.9, and due to some issues I ended up having to recreate the virtual environment, so I don't think it's necessarily an issue with the service file, but rather my Python/Gunicorn installation. If anyone could offer some advice, it would be greatly appreciated :) -
What is the best way to pass django form data to javascript ajax call?
I have a form with a certain number of fields and using a ajax call to communicate with the server. And I was wondering what is the best way to pass the data that I get from the request.post of the form and pass it back to the javascript success property of the ajax. Here is an example: def ajaxView(request): form = MyForm(request.POST or None) if request.is_ajax() and form.is_valid(): #1 I used to use render_to_string and Parse it in the js #2 or get field by field using the request.POST.get method and return it return JsonResponse({}) return "" In the js file: function CreateAjax(e) { e.preventDefault(); $.ajax({ url: "/ajaxViewUrl/", type: "post", data: $("#idForm").serialize(), success: function (data) { // if the first option retreive fields by field after parse }, error: () => { } }); } Now this would not be an issue if the form has a small number of fields, my concern is when the form has a considerable number of fields and in any cases I would like to reduce repetition of getting the value of the inputs in the form. -
How to exclude deleted objects in a clean() function on a model/form using inline_formsety
I have a model with a custom clean function to make sure no two DateRange overlap: class MyModel(models.Model): date_range = DateRangeField() def clean(self): error_dict = {} if MyModel.objects.exclude(id=self.id).filter( date_range__overlap=self.date_range): error_dict['date_range'] = ValidationError( 'Range can not overlap with an existing period.', code='overlap_period') if error_dict: raise ValidationError(error_dict) This works, but if I use inline_formset to submit more than one record at a time and delete a record that would remove the conflict (whilst updating others), the ValidationError still raises. This is because the filter function is done on the existing records, not the new updated ones. How can I amend the filter to exclude deleted objects in the inline_formset? Should I be doing a clean on the form instead? If so, how do I reference deleted objects?