Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return daily sales value for the current month in Django
With the model below, I want to create a function that returns the details of daily sales for the current month. The details will be the total number of sales for each day and sum of sales for each day. I've tried using ExtractDay and annotate but I'm not getting the desired output or maybe I'm not doing it right class Stamping(models.Model): created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Order(Stamping): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=300, unique=True) price = models.FloatField() quantity = models.IntegerField() In my location, the date is Tuesday, 2 November 2021. So the output should look like this <QuerySet [{'day': 1, 'count': 9, 'total': 100.0}, {'day': 2, 'count': 7, 'total': 80.0}]> And after today, I should also {'day': 3, 'count': 15, 'total': 200.0} and it keeps going till the end of the month then I'll start getting only the data for that month too -
How to use firebase authentication in django rest?
I have my user model like this. class User(AbstractUser): phone = models CharField(max_length=10, unique=True) name = models.CharField(max_length=50) The flow is: User on the mobile enters the name and phone and then signup. The users gets registered in the database. While login user only use phone number to login via firebase. Then how the django server will login this particular user ? -
Multiple ajax calls to populate fixed cell html table in django
———sorry for long question—— please share ajax-js-query-django code for the below requirement —-thanks a lot in advance… I have a functionality to achieve - its like giving a buyer ‘make your box’ kind of functionality - say a buyer lands in our ecom page with assorted items displayed along with radio-button having say 1. box-of-2 2. box-of-4 3. Box-of-6 So buyer selects box-of-2 and same page displays html box with just 2 cells. And below that all the items which can be clicked and this box-of-2 will be populated - say if buyer click item1 - then item1 gets placed in 1st cell of html table and then if he clicks on item2 then item2 gets placed in 2nd cell of html table. Now if buyer clicks on item3 - item3 gets placed in 1st cell of html table overwriting the item1 - so this way only two items will be in the html table. Now finally this box-of-2 is one commodity which can be added to cart by clicking on the add-to-cart button. Anyone can suggest some code snippets to achieve this with showing Empty box-of-n (html table) based on radio-button buyer selects Since the same page has all … -
How to add multiple model while registering new user?
I am using Django all-auth and Django rest-auth in my project. When registering new user i am sending user Info, personal info and location info data. Now I want to create those model after creating user model as well. How do i achieve that. -
How to do a subtraction in a html page on a pyhton variable?
I have this model: class Canva(models.Model): name = models.charfield(... year = models.IntegerField(... In my html page, When I use {{ canva.year }}, it shows me the year correctly. how can I see the year before, I tried {{ canva.year-1 }} or {{ canva.year }}-1 and it doesn't seem to work. -
Javascript not showing up on template in django
I do not understand why my javascript files are not being applied on my templates. Here is my base.html: <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Project</title> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/main.css' %}"> </head> <body> <div> {% include "navbar.html" %} {% block content %} {% endblock content %} </div> {% include "scripts.html" %} </body> </html> Here is my scripts.html: {% load static %} <script src="{% static 'js/main.js' %}"></script> <script src="{% static 'assets/js/jquery.min.js' %}"></script> <script src="{% static 'assets/js/jquery.dropotron.min.js' %}"></script> <script src="{% static 'assets/js/browser.min.js' %}"></script> <script src="{% static 'assets/js/breakpoints.min.js' %}"></script> <script src="{% static 'assets/js/util.js' %}"></script> <script src="{% static 'assets/js/main.js' %}"></script> However, they don't seem to affect the template. For example, the dropdown menu is in a weird format if I run the server. Another weird thing happening is that Main.js keeps being printed on the console. I believe this was initially because of the main.js file which had: console.log("Main.js"); However, even though I change it to the following: console.log("Something new for the console"); I still get Main.js printed out on the console. Moreover, if I put console.log("something") for my other javascript … -
Django - StatReloader not updating when change html file
I'm running into an issue I havn't had before. When I run python manage.py runserver I get default message: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 02, 2021 - 12:57:41 Django version 3.2.8, using settings 'core.settings' Starting development server at http://0.0.0.0:8000/ If I change some html and save changes, the changes are not shown in the browser. I have to quit the localserver and restart runserver to see the changes. This problem just appears out of nowhere - does anyone know how to fix or is there a package to fix this issue? -
Cyclical operations in Django Rest Framework
In my frontend application I have a panel which shows 6 the most popular products on my site. Searching for the most popular products each request by the number of views can be costly. I think that a good way to improve it will be to create a table in my data base which will store 6 the most popular products and the table will be refreshed for example every one minute. What should I looking for to do so cyclical operation on my django backend? -
remotely served Django service, does not return response for PATCH requests
I have deployed a Django rest framework service with multiple APIs on my Ubuntu 20.04 server with Gunicorn, everything works fine, but PATCH requests from outside the server do not receive a response, although the application receives the request and fully processes it. I have even tested it with Django runserver and the problem remains and has nothing to do with Gunicorn. Steps to reproduce: On the server we create a new Django application: ssh to_my@server python3 -m pip install django django-admin mytest cd mytest python3 manage.py runserver 0.0.0.0:9999 On the server trying to send requests to the application: ssh to_my@server curl --request GET localhost:9999/ # this works fine and we can see the response curl --request PATCH localhost:9999/ # this works fine too On another machine try these: # on my local machine curl --request GET IP:9999/ # this works fine curl --request PATCH IP:9999/ # **** this will get a `curl: (56) Recv failure: Connection reset by peer` after some times The response never arrives although in the console you can see that the request is fully received and Django has no problem: Invalid HTTP_HOST header: '207.154.246.122:9999'. You may need to add '207.154.246.122' to ALLOWED_HOSTS. Bad Request: / … -
How to hide field from Json response
I would like to hide from public api simple Serializer field (created without any model). How I can solve this? same_result = serializers.SerializerMethodField() -
Dropdown dependent problems with saving in the form part
I have a problem with dropdown dependent. in the frontend it works perfectly and filters me optimally but in the backend I have problems saving. Choose a valid option. The choice made does not appear among those available. This error is due to the fact that in form.py I cannot find 'gruppo_single' in self.data because it was excluded from the form to be dynamically passed from the view during the post. Can anyone help me with this problem? my models class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'gruppo') class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente') class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField(choices = giorni_settimana_scelta,default = '-') dati_gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'dati_gruppo') gruppi_scheda = models.ForeignKey(Schede,on_delete = models.CASCADE, related_name = 'gruppi_scheda') class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField(max_digits = 4,decimal_places = 1,blank = True,null = True) dati_esercizio = models.ForeignKey(Esercizi,on_delete = models.CASCADE,related_name = 'dati_esercizio') gruppo_single = models.ForeignKey(DatiGruppi, on_delete = models.CASCADE, related_name = 'gruppo_single') view for creating groups and exercises def creazione(request, nome): scheda = get_object_or_404(Schede, … -
Access control and input (json) validation in Django ajax views?
With a regular view we use decorators (e.g. login_required/user_passes_test/etc.) to do access control for a view and forms to validate user input. Is there anything similar for ajax views that take json as input (and output)? Doing it manually isawfully verbose.. def my_ajax_view(request): if not request.is_ajax(): return http.HttpResponseForbidden('cannot use this view directly') if request.user.is_anonymous(): return http.HttpResponseForbidden('must login') if not request.user.has_perm('can_foo'): return http.HttpResponseForbidden('no foo permission') try: data = json.loads(request.body) except json.decoder.JSONDecodeError: return http.HttpResponseForbidden('invalid input') # validate {"a": [list of int]} if not isinstance(data, dict): ..error if not 'a' in data.keys(): ..error if not isinstance(data['a'], list): ..error if not all(isinstance(val, int) for val in data['a']): ..error return http.JsonResponse({"length": len(data['a'])}) -
how to get selected item in <li> to views in django
please help !!! I have a code which get the data from db and display it in dropdown menu, the problem is : i can't get the selected item to insert it in an other table the html : <div class="template-demo" > <div class="mdc-select demo-width-class" data-mdc-auto-init="MDCSelect" > <i class="mdc-select__dropdown-icon"></i> <div class="mdc-select__selected-text"></div> <div class="mdc-select__menu mdc-menu-surface demo-width-class" > <ul class="mdc-list"> <li class="mdc-list-item mdc-list-item--selected" data-value="" aria-selected="true"> </li> {% for TypeFrais in typefrais %} <li class="mdc-list-item" > <input type="hidden" name="type_field"> {{TypeFrais.FRT_NAME}} </li> {% endfor%} </ul> </div> <span class="mdc-floating-label">Type de frais</span> <div class="mdc-line-ripple"> </div> </div> </div> views.py if request.method == 'POST': #iden = request.POST['id_field'] designation = request.POST['des_field'] date = request.POST['date_field'] montant = request.POST['montant_field'] type = request.POST['typefield'] GES_FRAIS = Frais(FR_TYPE_id=type,FR_DESIGNATION=designation,FR_MONTANT=montant,FR_DATE=date,FR_CODE=78) GES_FRAIS.save() return render(request, 'gesfrais.html',context) the error is : MultiValueDictKeyError at /dashboard/gesfrais/ 'typefield' -
models.AutoField not working for tables under new schemas
I am trying to save the file upload information in a table under a new schema, not 'public' in PostgreSQL database. I used id = models.AutoField(db_column="id", primary_key=True) in my model class definition because I want the id of each row to be automatically incremented. However, I get the error as shown in the screenshot below after uploading the image. The Autofield worked when I saved the data in a table under 'public' schema, but it doesn't work for a table under the separate schema. I couldn't find any solution to fix this problem. Any suggestion would be appreciated. -
how to fix Comodo SSL certificate on Django app not trusted?
I have a comodo positive SSL certificate. put it on my server and started my server using this: python manage.py runserver_plus --cert-file /my/cert --key-file /my/key 0.0.0.0:443 but it is not trusted in browsers yet. shows this: I passed my files that have same name with my domain to runserver_plus. I think maybe i used wrong files. now i want to know what is my problem? -
Django Celery. How do I run task at exact time?
How can I write a code that will run a task for example "everyday (or every 24 hours)at 3:20 a.m."? The main problem is "3:20" part, how do I make cron task at this exact time? -
Use of select_related in simple query in django
I have a model in Django in which a field has a fk relationship with the teacher model. I have came across select_related in django and want to use it in my view. However, I am not sure whether to use it in my query or not. My models: class Teacher(models.Model): name = models.OneToOneField(max_length=255, default="", blank=True) address = models.CharField(max_length=255, default="", blank=True) college_name = models.CharField(max_length=255, default="", blank=True) class OnlineClass(models.Model): teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE) My view: def get(self, request,*args, **kwargs): teacher = self.request.user.teacher classes = Class.objects.filter(teacher=teacher) #confusion is here.............. serializer_class = self.get_serializer_class() serializer = serializer_class(classes,many=True) return Response(serializer.data,status=status.HTTP_200_OK) I have commented on the line or the section of the problem. So I wanted to list all the classes of that teacher. Here I have used filter. But can we use select_related here?? What I understood is if I want to show another fields of teacher model as well, for eg name or college_name, then I have to use it. Otherwise the way I have done it is correct. Also, select_related is only used for get api not for post api, is that correct?? -
Django process running tasks instead of Celery
I'm running an app with Celery+redis for asynchronous tasks. I managed to get Celery see the list of tasks. However my tasks aren't executed by Celery workers but by Django process instead. I tried invoking the tasks with .delay() and .apply_async() without success (actually in these cases the call to the task gets blocked indefinitely and nothing is shown in the logs). I might be missing something very basic but cannot see where. Relevant settings follow: settings.py CELERY_REDIS_DB = os.environ.get("REDIS_DB_CELERY", 0) CELERY_REDIS_HOST = os.getenv("REDIS_HOSTNAME", "redis") CELERY_REDIS_PORT = 6379 CELERY_RESULT_BACKEND = BROKER_URL = ( f'redis://{CELERY_REDIS_HOST}:{CELERY_REDIS_PORT}/{CELERY_REDIS_DB}' ) CELERY_TIMEZONE = TIME_ZONE CELERY_RESULT_EXPIRES = 5 * 60 * 60 celery.py from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'maat.settings') app = Celery('maat') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() tasks.py @shared_task def remove_task( environment=None, payload=None, **kwargs, ): LOGGER.info('Received task, now removing') ... views.py class MyClass( LoginRequiredMixin, PermissionRequiredMixin, SingleObjectMixin, APIView ): return_403 = True model = models.Environment slug_field = 'name' slug_url_kwarg = 'environment' def delete(self, request, environment): tasks.remove_task(environment=environment, payload=request.data) … -
How to pass broker_url from Django settings.py to a Celery service
I have Celery running as a service on Ubuntu 20.04 with RabbitMQ as a broker. Celery repeatedly restarts because it cannot access the RabbitMQ url (RABBITMQ_BROKER), a variable held in a settings.py outside of the Django root directory. The same happens if I try to initiate celery via command line. I have confirmed that the variable is accessible from within Django from a views.py print statement. If I place the RABBITMQ_BROKER variable inside the settings.py within the Django root celery works. My question is, how do I get celery to recognise the variable RABBITMQ_BROKER when it is placed in the ? My celery.py file: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backoffice.settings') app = Celery('mydjangoproject') default_config = 'mydjangoproject.celery_config' app.config_from_object(default_config) app.autodiscover_tasks() My celery_config.py file: from django.conf import settings broker_url = settings.RABBITMQ_BROKER etc... The settings.py in /etc/opt/mydjangoproject/ (non relevant stuff deleted): from mydangoproject.settings import * RABBITMQ_BROKER = 'amqp://rabbitadmin:somepassword@somepassword@webserver:5672/mydangoproject' etc... My /etc/systemd/system/celery.service file: [Unit] Description=Celery Service After=network.target [Service] Type=forking User=DJANGO_USER Group=DJANGO_USER EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/opt/mydjangoproject ExecStart=/bin/sh -c '${CELERY_BIN} -A $CELERY_APP multi start $CELERYD_NODES \ --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} \ --loglevel="${CELERYD_LOG_LEVEL}" $CELERYD_OPTS' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait $CELERYD_NODES \ --pidfile=${CELERYD_PID_FILE} --loglevel="${CELERYD_LOG_LEVEL}"' ExecReload=/bin/sh -c '${CELERY_BIN} -A $CELERY_APP multi restart $CELERYD_NODES \ --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} \ --loglevel="${CELERYD_LOG_LEVEL}" $CELERYD_OPTS' Restart=always [Install] WantedBy=multi-user.target … -
Duplicate Entry on Django
I seem to get duplicate entry or Integrity error when trying to create or update my entries . I have tried using objects.get_or_create() and objects.update_or_create(). Creating seems to work well when there is no record yet but somehow updating is just throwing some duplicate entry error. here is my views.py: def evaluate(request): r = [] i = [] a = [] s = [] e = [] c = [] for id in range(1,43): score = float(request.POST.get(f'{id}')) question = RIASEC_Test.objects.get(pk=id) if question.category == 'R': r.append(score) if question.category == 'I': i.append(score) if question.category == 'A': a.append(score) if question.category == 'S': s.append(score) if question.category == 'E': e.append(score) if question.category == 'C': c.append(score) r = (sum(r)/7) * 100 i = (sum(i)/7) * 100 a = (sum(a)/7) * 100 s = (sum(s)/7) * 100 e = (sum(e)/7) * 100 c = (sum(c)/7) * 100 name=request.user try: User=Riasec_result.objects.get(user=request.user) Riasec_result.objects.update(user=User,reality=r, investigative=i, artistic=a, social=s,enterprising=e, conventional=c) except ObjectDoesNotExist: result=Riasec_result.objects.create(user=name,reality=r, investigative=i, artistic=a, social=s,enterprising=e, conventional=c) result.save() # if (Riasec_result.objects.get(user=name)): # Riasec_result.objects.update(user=name, reality=r, investigative=i, artistic=a, social=s, enterprising=e, # conventional=c) # else: # result = Riasec_result.objects.create(user=name, reality=r, investigative=i, artistic=a, social=s, # enterprising=e, conventional=c) # result.save() return HttpResponseRedirect(reverse('riasec:home')) and this is my models.py: class Riasec_result (models.Model): class Meta: verbose_name = _('RIASEC Result') verbose_name_plural … -
htmx swapping element but the style not included
I'm learning to use htmx with Django, so I just built a simple Twitter app with a form and the tweet body. when you submit the form, the new tweet appears on top. post_list.html {% block post %} {% include 'snippets/post_list_tweet_box.html' %} <div class="infinite-container"> <div id="post-content"> {% include 'snippets/post_list_body.html' %} </div> <div class="d-flex d-none position-fixed" style="top:35vh;left:46vw;"> <button class="btn btn-primary loading" style="display: none;"> <span class="spinner-border spinner-border-sm"></span> Loading tweet... </button> </div> {% if post_list.has_next %} <a class="infinite-more-link" href="?page={{ post_list.next_page_number }}"></a> {% endif %} </div> {% endblock post %} post_list_body.html <style> ... </style> {% for post in post_list %} <div class="tweet-wrap infinite-item"> ... </div> {% endfor %} my view : class PostListView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' def get(self, request, *args, **kwargs): print("GET-HOME") posts = Post.objects.filter( author__userfollow__followers__in=[request.user.id] #Fix later ) form = PostForm(request.POST, request.FILES) share_form = ShareForm() posts = Post.objects.all().order_by('-created_on') post_list = [] for post in posts: comment = Comment.objects.filter(post=post).count() user = UserProfile.objects.get(account=post.author) is_like = False if request.user in post.likes.all(): is_like = True post_list.append((post,comment,user,is_like)) page = request.GET.get('page', 1) paginator = Paginator(post_list,10) try: post_pagination = paginator.page(page) except PageNotAnInteger: post_pagination = paginator.page(1) except EmptyPage: post_pagination = paginator.page(paginator.num_pages) context = { 'post_list': post_pagination, 'shareform': share_form, 'form': form, } return render(request, 'post/post_list.html', context) def post(self, … -
Fixtures Dumpdata Unable to serialize database: 'charmap' codec can't encode characters in position 3979-3980
I am trying to dump local-level data into the production-level database. However, Before I could, I got a headache running the dumpdata command for hours: Whenever I run the command python manage.py dumpdata <app_name>.<app_model> --format json --indent 4 --exclude auth.permission --exclude contenttypes > data.json , This only dumps a portion of model data to data.json, but not all the model instances. click here to see what data.json looks like. I don't know why I always get this kind of data. click here for traceback. In models.py from django.db import models import readtime from EHub.models import * from django.utils.translation import gettext_lazy as _ from django.utils.text import slugify from django.contrib.auth.models import User from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey from taggit.managers import TaggableManager from ckeditor_uploader.fields import RichTextUploadingField def article_image_directory_path(): return 'Articles/' class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class IpModel(models.Model): ip=models.CharField(max_length=100,null=True) timestamp = models.DateTimeField(auto_now_add = True) def __str__(self): return str(self.ip) class Article(models.Model): options=( ('draft','Draft'), ('published','Published'), ) def get_absolute_url(self): return reverse('MArticles:article_detail',kwargs={'pk':self.id,'slug':self.slug}) visibilitymode=( ('private','Private'), ('public','Public'), ) class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(visibility = 'public' ,status = 'published') contenttype=models.CharField(default="Article", max_length=50) visibility = models.CharField(max_length=20 ,choices=visibilitymode, default="public", help_text="<p style='color:#b1b1b1;'>Private -> Only You can see this article.</p><p style='color:#b1b1b1;'>Public -> Anyone on the internet can … -
How to deploy label studio on Azure VM?
I want to deploy label studio annotation package to my azure VM. It is based on Django. I know how to deploy Django apps. But I was curious to know if there is any possible way to deploy it more efficiently. I am hesitant to try docker right now because I have one more Django app deployed on the same VM using Apache, and I fear using docker might break it. -
How to deal with nested serializer fields in Djnago rest framework?
I have nested serializer (AmountSerializer). I need field meal_name in one ViewSet. But when this field is nested i don't need it to be seen in endpoint(in MealSerializer). How to exclude field from nested serializer when is it actually nested? serializers.py: class AmountSerializer(serializers.ModelSerializer): ingredient_name= serializers.ReadOnlyField(source='ingredient_name.name') -->#meal_name = serializers.ReadOnlyField(source='meal.name') class Meta: model = IngredientAmount fields = ('ingredient_name','amount','meal_name') class MealSerializer(serializers.ModelSerializer): type_name= serializers.ReadOnlyField(source='type.name') ingredients = serializers.SlugRelatedField(read_only=True, slug_field='name', many=True) amount = AmountSerializer(read_only=True, many=True,source='meal_id') class Meta: model = Meal fields = ('id', 'name', 'type_name', 'recipe', 'photo', 'ingredients','amount') -
Django Admin one field required related on other field
I am using Django admin to save models my model is like bellow: class PurchaseItem(models.Model): product=models.ForeignKey("products.Product",on_delete=models.CASCADE,blank=True,null=True) product_attribute=models.ForeignKey("products.ProductAttribute",on_delete=models.CASCADE,blank=True,null=True) The goal is to save only one of the foreign keys for example : If the product is not null then the product attribute needs to be null Same thing for the product_attribute if its not null then the product must be null Note: product and product_attribute cannot be null at the same time . how to achieve this using the Django admin.