Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - Mutual relations between models: How to create instances?
With a model like class Restaurant: default_pizza = models.OneToOneField('Pizza', on_delete=models.PROTECT) class Pizza: served_in = models.ForeignKey(Restaurant, on_delete=models.CASCADE) how can I create a new restaurant object and a corresponding default_pizza object at the same time? A restaurant can serve many pizzas, but only one will be the default pizza. -
How can convert this sql query into django queryset
This is my DjangoQuery bills = BillMaster.objects.filter(pay_type=1, customer=2).values('order_id', 'customer_id', 'invoice_no', 'grand_total').annotate(paid_amount=Coalesce(Sum('creditpaymentdetail__amount'), 0)) bills = bills.values('customer_id').annotate(gt=Coalesce(Sum('grand_total'), 0)) which is equivalent to postgreSQL query : SELECT "bill_billmaster"."customer_id", COALESCE(SUM("bill_billmaster"."grand_total"), 0) AS "gt" FROM "bill_billmaster" LEFT OUTER JOIN "credit_management_creditpaymentdetail" ON ("bill_billmaster"."id" = "credit_management_creditpaymentdetail"."bill_master_id") WHERE "bill_billmaster"."pay_type" = 1 GROUP BY "bill_billmaster"."customer_id" But I want to achieve this postgreSQL query: select customer_id, sum(gt) gt from ( SELECT "bill_billmaster"."customer_id", "bill_billmaster"."grand_total" AS "gt" FROM "bill_billmaster" LEFT OUTER JOIN "credit_management_creditpaymentdetail" ON ("bill_billmaster"."id" = "credit_management_creditpaymentdetail"."bill_master_id") WHERE "bill_billmaster"."pay_type" = 1 GROUP BY "bill_billmaster"."customer_id", grand_total ) R group by customer_id -
Using Django's autoreloader for Celery worker, autoreloading doesn't get triggered for changes in some files
I am using this strategy to make the Celery worker respond file changes and reload itself. It works well. However, for some files, like one of the tasks.py module which contains a task for the Celery worker doesn't trigger the autoreload when changed, while another tasks.py in another app triggers. Both of these modules have identical lines: app1/tasks.py: from main import celery_app @celery_app.task(bind=True) def queue_update(self, json_obj): ... app2/tasks.py: from main import celery_app @celery_app.task(bind=True) def new_job(self, job_temporary_id): ... I make a change in the first file and it triggers autoreloading, but the second one doesn't. Celery discovers these tasks modules successfully as I see in the logs: my_celery_worker | . app1.tasks.queue_update my_celery_worker | . app2.tasks.new_job -
Python unit test assertEqual throwing assertionError in one machine but not in others
I've built a test case for a GraphQL mutation where I save inputs (priceOne and priceTwo) of type graphene.Decimal() into the model MyObj fields of type models.DecimalField and I return MyObj in the response. The code below returns OK, test successful in my machine, let's call Machine A, and it also works in Machine B, but doesn't work on Machine C. Machine A: Windows 10, python 3.7 => OK Machine B: Ubuntu, python 3.8.0 => OK Machine C: Ubuntu, python 3.8.5 => F import json from mixer.backend.django import mixer from core.schema import schema from my_app.models import MyObj from my_app.tests.utils import CustomGraphQLTestCase MY_MUTATION = ''' mutation MyMutation($input: MyInput!) { myMutation(input: $input) { success myObj { id price } } } ''' class TestMyMutation(CustomGraphQLTestCase): GRAPHQL_SCHEMA = schema def setUp(self): self.my_obj = mixer.blend(MyObj) self.input_data = { 'id': self.my_obj.id, 'priceOne': '2000.00', 'priceTwo': '0.10', } def test_my_mutation_success(self): response = self.query(MY_MUTATION, input_data=self.input_data) content = json.loads(response.content) self.assertResponseNoErrors(response) self.assertTrue(content['data']['myMutation']['success']) self.assertEqual(content['data']['myMutation']['myObj']['priceOne'], 2000.00) self.assertEqual(content['data']['myMutation']['myObj']['priceTwo'], 0.10) We fixed the issue by transforming both arguments of assertEqual to Decimal and for the 0.10 we had to use quantize. self.assertEqual(Decimal(content['data']['myMutation']['myObj']['priceOne']), 2000.00) self.assertEqual(Decimal(content['data']['myMutation']['myObj']['priceTwo']).quantize(Decimal(10)**(-2)), Decimal(0.10).quantize(Decimal(10)**(-2))) Question: Why doesn't it work on Machine C? The CustomGraphQLTestCase: import json from django.core.serializers.json import DjangoJSONEncoder from graphene_django.utils import GraphQLTestCase … -
how do i edit a post which would be in a mysql table in flask?
i have created a simple blog site using flask where a user login and create a blog and can edit it or delete it. the blog post are saved in a separate db. but idk how can a user edit the blog because in the backend we will require the id for that blog which isnt stored with the posted blog. I can pass the blog id using request.args.get() but that will send data in get method and that is not secure tbh. -
How to get visitors geolocation (country and city ) using django?
i have a django project and need get visitors location using HTML5 (navigator.geolocation) , since im new with django , how to use and save navigtor.geolocaiton data in django ? anybody could help please? -
Assign value to logged in user in Django
I have a Django app where I am trying to assign a bank variable to each user, set to 100 by default. I have the following model in models.py : class Wallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bank = models.FloatField(default=100) which is then used in views.py: class BitgainzView(View): def get(self, *args, **kwargs): user = User.objects.get(username=self.request.user) context = {'bank': user.wallet.bank} return render(self.request, "index.html", context) I then print bank in my html page. Two problems with this : if user is logged in : I get the error Exception Value: User has no wallet. which I think is because the schema for Wallet was created in relation to User, but never initialised for each user. if user is not logged in : Then the context in BitgainzView() cannot be loaded, and I am also getting an error. Should I make separate views in that case ? Or should I treat different cases inside this function ? Thank you in advance. -
when date is selected from datepicker then How to display date in html table cell using jQuery
When the user selects the particular date from datepicker, I want to display date in first cell of table and by default it should show current date. How can I fetch date from the datepicker ? Here top of table I am using Datepicker jQuery. Table +-----------+---------+---------+-------+ | Date | Day | Project | Task | +-----------+---------+---------+-------+ | 3/12/2021 | Friday | | | +-----------+---------+---------+-------+ -
Django read data from list of QuerySets
I have the following list [<QuerySet [{'number': 123}]>, <QuerySet []>, <QuerySet []>, <QuerySet [{'number': 21323}]>, <QuerySet []>] I want to extract the numbers in an other list with a for loop and skip the empty QuerySets, but was not successful yet. Is there an easy way? Tahnk you -
Django For Loop to print data in loop
I have a list of quizzes by category and class. I would like to use bootstrap description lsit alignment to print like Class XI Mathematics Quiz 1 Quiz 2 Quiz 3 Physics Quiz 3 Quiz 4 Class XII History Quiz 7 Quiz 8 using <dl class="row"> <dt class="col-sm-3">Class XI</dt> <dd class="col-sm-3">Mathematics</dd> <dd class="col-sm-3">Quiz 1</dd> </dl> How do I write my django for loop using regroup? Thank you for the help. -
SyntaxError: 'return' outside function occuring in code
Having 'return' outside of function in error in the following code. I'm using django rest framework for my project and this is the views.py file. It's pretty incomplete but I'm trying to work my way through. In the bolded line im facing the error. from django.http import HttpResponse from django.shortcuts import get_object_or_404 from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import client from .serializers import ClientSerializer class ClientList(APIView, UpdateModelMixin, DestroyModelMixin): if id: try: queryset = client.objects.get(id=id) except client.DoesNotExist: **return Response({'errors': 'This client item does not exist.'}, status=400)** read_serializer = ClientSerializer(queryset) else: queryset = client.objects.all() read_serializer = ClientSerializer(queryset, many=True) return Response(read_serializer.data) def post(self): pass -
defectdojo container can not connect to mysql container running on the same machine
I am having defectdojo containers running as follows: 1e2b1731c712 defectdojo/defectdojo-nginx:latest "/entrypoint-nginx.sh" 2 months ago Up 7 weeks 80/tcp, 0.0.0.0:9092->8080/tcp source_code_nginx_1 1898e39ba3d0 defectdojo/defectdojo-django:latest "/wait-for-it.sh mys…" 2 months ago Up 8 minutes source_code_celerybeat_1 a779d1d530ea defectdojo/defectdojo-django:latest "/wait-for-it.sh mys…" 2 months ago Up 7 weeks source_code_celeryworker_1 767cd3c089a9 defectdojo/defectdojo-django:latest "/wait-for-it.sh mys…" 2 months ago Up 7 weeks source_code_uwsgi_1 6ade7e946e18 rabbitmq:3.7.17 "docker-entrypoint.s…" 2 months ago Up 7 weeks 4369/tcp, 5671-5672/tcp, 25672/tcp source_code_rabbitmq_1 Here is my db container configuration that is also running : 116a8abcf8c7 mysql:5.7.27 "docker-entrypoint.s…" 10 months ago Up 12 minutes 33060/tcp, 0.0.0.0:33062->3306/tcp data2_mysql_1 I am having the following error in my docker container log for the container 1898e39ba3d0 which is the initializer container. subprocess.CalledProcessError: Command '['mysql', '--user=defectdojo', '--password=defectdojo', '--host=mysql', '--port=3306', 'defectdojo']' returned non-zero exit status 1 ERROR 2005 (HY000): Unknown MySQL server host 'mysql' (-2) Traceback (most recent call last): File "manage.py", line 11, in execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/dbshell.py", line 22, in handle connection.client.runshell() File "/usr/local/lib/python3.5/site-packages/django/db/backends/mysql/client.py", line 48, in runshell subprocess.check_call(args) File "/usr/local/lib/python3.5/subprocess.py", line 271, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['mysql', … -
Can't assign new value to django model field
I have a calculation = models.FloatField(default=0) field and I am trying to assign new value(according to debuger its 32) to it like this: points_sum = float(row[0].budgetOptions.points + row[0].techCompatibility.points + row[0].availableMen.points + row[0].degreeOfElaboration.points + row[0].geography.points + row[0].nonInHouseReady.points + row[0].existingItPartner.points + row[0].httpsAvailability.points + row[0].monthlyAdsBudget.points + row[0].mobilePageLoadSpeed.points + row[0].desktopPageLoadSpeed.points + row[0].organicTraficTrend.points + row[0].payedTraficTrend.points + row[0].techStackEquality.points + row[0].projectType.points + row[0].customerReadiness.points + row[0].servicesMeet.points) row[0].calculation = points_sum print(str(row[0].calculation)) row[0].save(update_fields=['calculation']) And when I print row[0].calculation value it gives me my default value 0,0. Any ideas on what I am doing wrong? -
How to filter/annotate prefetched objects in django (more efficiently)?
I would like to filter queryset, with prefetch_related objects. This code works, but I would like to write it more efficiently. Do you have any idea ? queryset = Song.objects.prefetch_related( Prefetch('harmonies', queryset=Harmony.objects.filter(someQuery))) for s in queryset: if s.harmonies.count() > 0: songs.append(s.id) queryset = queryset.filter(id__in=songs) I tried something like this, but it didn't work. queryset = queryset.annotate(h_count=Count('harmonies')).exclude(h_count=0) Thank you , for your help. -
Pandas corelation in Django
guys i am a beginner in programming and I desperately need your help. I am trying to develope a webapp using Django. I have created a HTML form in my index.html file. In my views.py I am trying to use the corr() fundtion of Pandas but every time it says Empty DataFrame index.html <form id='form' name='form' method="post" action=""> {% csrf_token %} <div class="row"> <div class="form-group col-md-2"> <label for="Col 1">col 1</label> <input type="text" class="form-control" id="col1" name="col1"> </div> <div class="form-group col-md-2"> <label for="Col 2">col 2</label> <input type="text" class="form-control" id="col2" name="col2"> </div> </div> <div class="row"> <div class="form-group col-md-2"> <label for="Col 3">col 3</label> <input type="text" class="form-control" id="col3" name="col3"> </div> <div class="form-group col-md-2"> <label for="Col 4">col 4</label> <input type="text" class="form-control" id="col4" name="col4"> </div> </div> <button class="btn btn-primary" id='predict' name='predict'>Run forecast</button> </form> views.py def index(request): if request.method == "POST": col1 = request.POST.get('col1') col2 = request.POST.get('col2') col3 = request.POST.get('col3') col4 = request.POST.get('col4') data = {'X':[col1, col2], 'Y':[col3, col4]} df = pd.DataFrame(data) x = df.corr() print(x) return render(request, 'corelation.html') else: return render(request,'index.html') Every time I run this code it returns Empty DataFrame in terminal. However if I replace col1, col2 with actual numbers it shows the desired result. -
Concept for secured app login: someone here has a better idea, something to add that we have overlooked?
Our Situation: we are in the process of developing a concept for a login screen, for a palette of different online apps. all online apps should be available via the same login, depending on the associated user group. available online apps should be listed after login. except for the security service, all apps are independent of each other, they can be hosted on separate servers, etc. the online applications are React apps (based on TypeScript). the backend runs with Django (based on Python). (the backend framework is fixed for specific technical reasons and will be django, we need no suggestions for a different backend framework) now we are looking for the best prectise and sefest method to prevent insights and attacks as much as possible. Our Conecpt: our idear for this is, to build the login apllication with react native, to render the frontend on server site. so, the maximum visible communication tranfair with the server, will be the user credentials to the server. Login Form (React Native): Login screen as standalone app for all restricted apps Server site website rendering Server site authentication (no API call) Login credentials: "username" and "password" List available apps after sucessfull authentication Redirect with … -
The field was declared with a lazy reference to 'app.model', but app doesn't provide model
Why am I getting errors trying to refer foreign keys? Four out of Six references are working fine. Why are the other two throwing errors? The models are in the same app and file itself. I have even listed the app under INSTALLED_APPS in settings.py. I have defined all the tables according to my ER diagram. Am I missing something? accounts/models.py from django.db import models from django.db.models.deletion import SET_NULL # Create your models here. class Department(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self) -> str: return self.name class UserTypeDepartment(): CATEGORY = ( ('Main Project Contact', 'Main Project Contact'), ('Technical Administrator', 'Technical Administrator'), ('End-User Requestor', 'End-User Requestor'), ) name = models.CharField(max_length=35, null=True, choices=CATEGORY) def __str__(self) -> str: return self.name class UserDepartment(models.Model): fname = models.CharField(max_length=50, null=True) lname = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=10, null=True) email = models.CharField(max_length=100, null=True) department = models.ForeignKey('Department', on_delete=models.CASCADE) userType = models.ForeignKey('UserTypeDepartment', on_delete=models.CASCADE) #THROWS ERROR def __str__(self) -> str: return self.fname + " " + self.lname class Vendor(models.Model): name = models.CharField(max_length=150, null=True) website = models.CharField(max_length=200, null=True) name = models.BooleanField(default=False) def __str__(self) -> str: return self.name class UserTypeVendor(): CATEGORY = ( ('Vendor Contact', 'Vendor Contact'), ('Vendor Technical Contact', 'Vendor Technical Contact'), ) name = models.CharField(max_length=35, null=True, choices=CATEGORY) def __str__(self) -> str: … -
How can use div when using django block
I'm using Django 3.1.7 in the backend and have a three-page 1.index(the home page) 2.Transhow I used block to reduce and reuse index code. I have a few pages and all pages need to use the same CSS but when I use block statement the div doesn't work. <div id="content"> <div id="header"> <div id="brand"> <h1><a href="#">حسابداری</a></h1> </div> <div id="searchbox"> <form action="search" method="get"> <input type="text" placeholder="حساب مورد نظر" class="text"> <input type="submit" value="جستجو" class="submit"> </form> </div> <div class="clear"> </div> </div> <div id="toolbar"> <ul> <li><a href="http://127.0.0.1:8000" class="active">خانه</a></li> <li><a href="Account_show">مدیریت حساب</a></li> <li><a href="Trans_show">مدیریت اسناد</a></li> <li><a href="Article_show">دفتر روزنامه</a></li> <li><a href="Category_show">گروه سرفصل</a></li> <li><a href="about_us">درباره ما</a></li> <li><a href="logout_page">خروج</a></li> </ul> </div> <div id="main"> {% block main %} {% endblock %} </div> <div id="footer"></div> </div> Tran page {%block main%} <table> <tr> <th>ردیف</th> <th>شماره سند</th> <th>تاریخ</th> <th>توضیحات</th> <th>عطف</th> <th>ویرایش</th> </tr> {%for record in records%} <tr> <td><a href="article/{{record.id}}">{{record.id}}</a></td> <td><a href="article/{{record.id}}">{{record.sanadno}}</a></td> <td><a href="article/{{record.id}}">{{record.tdate}}</a></td> <td><a href="article/{{record.id}}">{{record.tdesc}}</a></td> <td><a href="article/{{record.id}}">{{record.tres}}</a></td> <td><a href="edit/Tran_edit/{{record.id}}">ویرایش</a></td> </tr> {%endfor%} {% if records.has_previous %} <a href="?page=1">اولین</a> <a href="?page={{ records.previous_page_number }}">قبل</a> {% endif %} صفحه {{ records.number }} از {{ records.paginator.num_pages }}. {% if records.has_next %} <a href="?page={{ records.next_page_number }}">بعدی</a> <a href="?page={{ records.paginator.num_pages }}">قبلی</a> {% endif %} </table> {%endblock%} css page #content { width: 1050px; border: 1px solid grey; height: 100px; margin: … -
Django DRF - Access to field ForeignKey instance inside a custom serializer validator method
I'm currently having a bit of a conceptual headache over how best to reference the instance of a ForeignKey field inside a custom serializer validator method ... To give an overview of the system. I have the following "Candidate" model, the imporant fields for this question are the user, job* and status fields. from model_utils.fields import MonitorField, StatusField from model_utils import Choices class Candidate(models.Model): class Meta: ... STATUS = Choices( 'matched', 'approached', 'invite_rejected', 'invite_accepted', 'reviewed', 'interview_scheduled', 'hired', 'rejected' ) user = models.ForeignKey('users.User', on_delete=models.CASCADE) job = models.ForeignKey('jobs.Job', related_name='candidates', on_delete=models.CASCADE) ... status = StatusField(default='matched') ... def save(self, *args, **kwargs): super(Candidate, self).save(*args, **kwargs) The status field for the Candidate can only be "updated" to a given value based on who they are, and what they're attempting to update the status to. Effectively, my outlined logic is as follows inside the serializer: from rest_framework import serializers from .candidates.models import Candidate class CandidateSerializer(serializers.ModelSerializer): class Meta: model = Candidate fields = '__all__' def validate_status(self, value): user = self.context['request'].user if user.is_anonymous: raise serializers.ValidationError("The requester must be logged in to make a change to the status field") # Ensure status value is in valid list of statuses if value not in [ 'matched', 'approached', 'invite_rejected', 'invite_accepted', 'reviewed', 'interview_scheduled', … -
How to dynamically set different parameter in setting.py file while working with django multitenant?
I want to send verification email from different email per tenant but unable to override this. How can i set following parameter dynamically per tenant in setting.py file EMAIL_BACKEND EMAIL_HOST EMAIL_USE_TLS EMAIL_PORT EMAIL_HOST_USER EMAIL_HOST_PASSWORD ANYMAIL = { "MAILJET_API_KEY":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "MAILJET_SECRET_KEY": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", } EMAIL_BACKEND = "anymail.backends.xxx.EmailBackend" DEFAULT_FROM_EMAIL = 'dynamic@gmail.com' -
RelatedObjectDoesNotExist: User has no vendor
I'm trying to make a multi vendor website using django. But there is an issue that I have vendor object vendor but it says User has no vendor. Why is this happening and how may I solve this? #models.py from django.contrib.auth.models import User from django.db import models class Vendor(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name #views.py from django.shortcuts import render,redirect from django.contrib.auth import login from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from .models import Vendor def become_vendor(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) vendor = Vendor.objects.create(name=user.username, created_by=user) return redirect('frontpage') else: form = UserCreationForm() return render(request, 'vendor/become_vendor.html', {'form': form}) @login_required def vendor_admin(request): vendor = request.user.vendor return render(request, 'vendor/vendor_admin.html', {'vendor': vendor}) -
In Django, how to display time which updates every minute?
Using tag {% now %}, I can display the time, but the time is static and doesn't update every minute. Is there anyway to update this time? Is it possible to do this with javascript's setInterval and django's {% now %}? Tried this: <script> setInterval(function () { $("#current_time").text("{% now "jS F Y H: i " %}"); }, 60 * 1000); // 60 * 1000 milsec </script> But this doesnt work as django renders now value only once(when page loads) and it remains same all time -
How to do `itertools.product(queryset_a, queryset_b)` via Django ORM?
I have two queryset, and need the product. I could use this: itertools.product(queryset_a, queryset_b) BUT the result is too big, and I need to paginate it. This means, I need to avoid itertools.product() and use the Django ORM to create the product in the database. How to do itertools.product(queryset_a, queryset_b) via Django ORM? I use PostgreSQL. -
Django-crontab - ERROR: sh: line 1: /usr/bin/crontab: No such file or directory
I followed the documentation In my django project specific venv (myproject/venv) I installed django-crontab[0.7.1] using command: (venv) pip3 install django-crontab added to settings.py INSTALLED_APPS = ( ... 'django_crontab', ) CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'django.core.management.call_command', ['my_command']) ] Next when I run python manage.py crontab add I get Error: (venv) python manage.py crontab add /bin/sh: line 1: /usr/bin/crontab: No such file or directory adding cronjob: (b27648b2dab947d53fe7e8c052bcd9a7) -> ('*/1 * * * *', 'django.core.management.call_command', ['my_command']) sh: line 1: /usr/bin/crontab: No such file or directory But I checked manually /usr/bin/ and I see a file named crontab is present. After that when I run python manage.py crontab show there is no job added. At this point I don't know what should I do. Need Help. -
How to add list of unique models to a django model
I am developing a dashboard app for clients to manage their devices with django and mariadb database. I have a Client model (which is the extended user model) and Device model which represents single, unique device. One user can have multiple devices, but one device can be assigned to only one user. Now, what is the best way to create an entry in Client model, that will contain all his assigned devices. What is important, one device (represented by unique device id) can appear only once in all Client.devices tables. Here is the code to visualize my problem: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) devices = <?> class Device(models.Model): type = models.PositiveSmallIntegerField(default=0x00) id = models.PositiveSmallIntegerField(primary_key=True, default=0x00) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) I feel like the answer is out there, but I'm not sure that other similar topics would match my uniqueness