Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count() outputs list and not a dictionary in django
I don't know what's happening this might be easy but I am stuck. I have the below queryset job_title = Employee.objects.filter().values('role__name').annotate(total=Count('id')) output I get [{'tole__name': 'Manager', 'total':2}, {'role__name': 'Director': 3}] now when I try to get the dictionary like {2, 3} using totals = job_title['total] I get an error -
how to setup 2 static files in nginx
am host a project in AWS . but static file is not access in the project. i have 2 app in my Django project. am set up the nginx . nginx have only set up the 1 static file. how am set 2 static file in the nginx -
Starbank Webhook not working with django and ngrok
I´ve trying to receive invoices with webhook in starbank webhook with django, but i don´t know what i´m doing wrong. In ngrok receive 502 BAD GATEWAY. Could anyone help me ? this is my coide in view: from django.http import HttpResponse from pypro.base.djangosdkstarkbank import webhook_extracting_and_sending_transfer ,sending_invoices_for_24_HRs import json from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST sending_invoices_for_24_HRs() # Create your views here. @csrf_exempt @require_POST def webhook_request(request): jsondata = request.body data_v = json.loads(jsondata) print(data_v) for answer in data_v['form_response']['answers']: # go through all the answers type_v = answer['type'] print(f'answer: {answer[type_v]}') type_u=f'answer: {answer[type_v]}'# print value of answers webhook_extracting_and_sending_transfer(type_u) return HttpResponse(200) and this is my code in djangostarkbank : import starkbank from datetime import datetime, timedelta import json from decouple import config from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST import time import names from random import randint private_key, public_key = starkbank.key.create("sample/destination/path") private_key_content = """""" # This is asecret key, you have to get one new_name = names.get_full_name() current_time = f'{(datetime.now())}' current_data_bank = current_time[0:9] new_avenue = f'Avenida {names.get_full_name()},{randint(0, 15000)}' new_zip_code = f"{randint(0, 99999)}-{randint(0, 999)}" new_tax_id = f'{randint(0, 999)}.{randint(0, 999)}.{randint(0, 999)}-{randint(0, 99)}' new_city = names.get_full_name() new_district = names.get_full_name() new_state = f"{names.get_full_name()}" new_simbol_state = f'{new_state[0:2]}'.upper() user = starkbank.Project( environment="sandbox", id="5933018535428096", private_key=private_key_content ) … -
One field in Django cannot retrieve the correct value when showing in template
models.py class Order(models.Model): PAYMENT_OPTIONS = ( ('VISA','VISA'), ('Master','Master'), ('Octopus','Octopus'), ('Cash','Cash'), ) STATUS = ( ('Pending','Pending'), ('Delivered','Delivered'), ('Collected','Collected'), ) METHODS = ( ('外賣自取','外賣自取'), ('送遞','送遞'), ) user = models.ForeignKey(User,models.CASCADE,null=True,blank=True) customer = models.CharField(max_length=200,null=True,blank=True) card_id = models.IntegerField(null=True,blank=True) mobile = models.IntegerField(null=True,blank=True) email = models.CharField(max_length=200,null=True,blank=True) total_price = models.DecimalField(decimal_places=2,max_digits=7) payment_method = models.CharField(max_length=50,choices=PAYMENT_OPTIONS,null=True,blank=True) status = models.CharField(max_length=50,choices=STATUS,default='Pending') take_method = models.CharField(max_length=50,choices=METHODS,null=True,blank=True) points_earned = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) address = models.CharField(max_length=350,null=True,blank=True) def __str__(self): return str(self.customer)+'\'s Order' views.py def checkout(request): global cartlist cartlist1 = cartlist total = 0 for unit in cartlist: total += int(unit[3]) grandtotal = total + 100 earnings = int(grandtotal/5) print(grandtotal) if request.method == 'POST': print(type(request.POST.get('customerPayment'))) print(request.POST.get('customerPayment')) print(request.POST.get('customerTakeaway')) customerName = request.POST.get('customerName','') customerID = request.POST.get('customerID','') customerMobile = request.POST.get('customerMobile','') customerEmail = request.POST.get('customerEmail','') customerPayment = request.POST.get('customerPayment'), customerTakeaway = request.POST.get('customerTakeaway'), customerAddress = request.POST.get('customerAddress','') new_order = Order.objects.create( user = User.objects.get(username=request.user), customer = customerName, card_id = customerID, mobile = customerMobile, email = customerEmail, total_price = grandtotal, payment_method = customerPayment, take_method = customerTakeaway, points_earned = earnings, address = customerAddress) account = User.objects.get(username=request.user) checkout.html <tr> <td style="width:160px;text-align:center;"> <strong>付款方式</strong> </td> <td style="width:200px;text-align:center;"> <input type="radio" name="customerPayment" value="VISA" id="customerPayment">VISA <input type="radio" name="customerPayment" value="Master" id="customerPayment">Master<br> <input type="radio" name="customerPayment" value="Octopus" id="customerPayment">Octopus <input type="radio" name="customerPayment" value="Cash" id="customerPayment">Cash </td> </tr> <tr> <td style="width:160px;text-align:center;"> <strong>領取方式</strong> </td> <td style="width:200px;text-align:center;"> <input type="radio" name="customerTakeaway" value="外賣自取" id="customerTakeaway">外賣自取 <input type="radio" … -
How to test downloading a path in a Django unittest?
How do you find the fully qualified URL for a static media file hosted by the test server inside a Django unittest? I'm trying to write a test for a custom process that downloads a media file and does some processing on it. The code must be able to download an arbitrary URL, not hosted by me, but for the sake of the test, I'm simply trying to test the download functionality with a local static file. However, attempts by the requests library to access any URLs allegedly being hosted by the test server return the error: HTTPConnectionPool(host='localhost', port=8082): Max retries exceeded with url: /static/mydata.zip (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe7a2ff8bb0>: Failed to establish a new connection: [Errno 111] Connection refused')) These answers suggest the URL I use can be http://testserver/static/mydata.zip or http:///localhost:8082/static/mydata.zip, but neither of these work. What am I doing wrong? What URL should I use? If I run the dev server from localhost:8000, then I can confirm the URL http://localhost:8000/static/mydata.zip works. To the file itself is setup to be correctly served. However, that URL is not accessible during the unittest. -
Cannot continue the bash script after creating a virtual environment using pipenv
I'm writing a bash script that automates the process of creating a django project and creating some folders and files that is necessary for a django project. The problem here is, when I create and activate the virtual environment using the pipenv shell command, The virtual environment is created and activated but the next command is not executed. The script just waits to exit the virtual environment and when I exit/deactivate the virtual environment, then the next lines of the bash script gets executed. My next line is pipenv install django. When this line is executed, django is installed in the virtual environment and again it waits for the user to exit the virtual environment and when I exit the environment, the next line is executed. But my next line is django-admin startproject myproject when this line is executed, I'm getting the error command not found. Yes I know why I'm getting this error. The environment is deactivated and it can't recognize the django-admin command. Also, I'm running this script as a superuser. I'm using wsl2. my code: mkdir "django_project" cd "django_project" pipenv shell pipenv install django read -p "Enter your project name: " PROJECT_NAME django-admin startproject "$PROJECT_NAME" cd "$PROJECT_NAME" … -
500 Error when debug=false Django. Works fine when DEBUG=true
also have s3 buckets set up and that works fine when debug=true. Not sure whats going on. allowed hosts are good and i also did python manage.py collectstatic. anyone know th problem?? from dotenv import load_dotenv load_dotenv() import os import dj_database_url from django.conf import settings import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY',) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = bool( os.environ.get('DEBUG', False) ) ALLOWED_HOSTS = ['quickthrift-andregrandon.herokuapp.com', '198.211.99.20', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'home', 'products', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'allauth'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # required by allauth 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mio.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { … -
Django Queryset order of evaluation
I have some confusion about how this snippet is evaluated class T(models.Model): person = models.CharField(max_length=10) location = models.CharField(max_length=10) error = models.BooleanField() T.objects.bulk_create([ T(person='P1', location='L1', error=False), T(person='P1', location='L1', error=True), T(person='P2', location='L2', error=False), T(person='P2', location='L2', error=False) ]) for t in T.objects.all().values('person', 'location').distinct().annotate(error=Sum('error')): print(t) When I asked about it on this thread: Combine rows on django queryset, It was explained to me that distinct().annotate(error=Sum('error')): is evaluated as its own unit, but I can't find any proof that this is true. To me, I would expect that the queryset is made to have only distinct values, then it is annotated which would have different effects than what I'm looking for. Any documentation that explains the order of evaluation would be appreciated. -
How to set Multi Level Foreign Key field in Django?
I have a model that looks like this # models.py from django.db import models class Level_0(models.Model): Kode = models.CharField(max_length=10, null=False, blank=False, default="") class Level_1(models.Model): Kode = models.CharField(max_length=10, null=False, blank=False, default="") Level_0= models.ForeignKey(Level_0, on_delete=models.CASCADE) class Level_2(models.Model): Kode = models.CharField(max_length=10, null=False, blank=False, default="") Level_1 = models.ForeignKey(Level_1, on_delete=models.CASCADE) # Level_0 = ???????????? # how do I create a connection to Level_0? a field that is automatically filled with Level_0? What I want to have is a field in Level_2 that automatically connects to Level_0 through Level_1. How do I add that field in my Level_2 model? -
How do i use django and python request to make a post request Properly
I am using django and python request to make a post request to this endpoint with the authorization header and body gotten from this website. i want your assist to get this difficulty proper and to make this code work. class RechargeData(models.Model, Main): user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) phone_number = models.CharField(validators=[Main.phone_regex], max_length=10) network = models.CharField(choices=Main.OPERATORS, max_length=15) plan = models.IntegerField(choices=Main.PLANS) amount = models.DecimalField(max_digits=10, decimal_places=2) i have the view.py file that contains the python request as follows import requests import json from .forms import RechargeForm def rechargedata(request): url = "http://127.0.0.1:8000/api/data/" payload = "{\"network\": network_id,\n\"mobile_number\": \"09037346247\",\n\"plan\": plan_id}" headers = {'Authorization': 'Token 5fd60vcdfddfxddsssfddff9a0a8742d','Content-Type': 'application/json'} response = requests.request("POST", url, headers=headers, data=payload) if request.method == "POST": form = RechargeForm(request.POST) if form.is_valid(): phone_number = form.cleaned_data['phone_number'] network = form.cleaned_data['network'] amount = form.cleaned_data['amount'] plan = form.cleaned_data['plan'] form.save context = RequestContext(request, { 'phone_number': responsedata.mobile_number, 'network': response.data.network_id, 'mobile_number': response.data.network_id, 'plan': response.data.plan_id, }) return render(request, 'embeds.html', {'context': context, 'form'; form}) else: form = RechargeForm() return render(request, 'index.html', {'context': context, 'form'; form}) This code is not working and am sure not to be getting something proper here. can someone help me out? -
One review per user in the current title
I am trying to make so that every user could only post one review per title (product). First idea was to do this through UniqueTogether, but it resulted unsuccessful. So now, I thought to complete it by validate in serializer. Right now I am getting the following error: TypeError: Review() got an unexpected keyword argument 'title'. But if you look at my code below I did not pass title argument to Review(). I even tried to make error on purpose to see what arguments I can pass to Review() and title was not there. django.core.exceptions.FieldError: Cannot resolve keyword 'title_d' into field. Choices are: author, author_id, comments, id, pub_date, score, text, title_id, title_id_id serializers.py class ReviewSerializer(serializers.ModelSerializer): author = serializers.SlugRelatedField( slug_field='username', default=serializers.CurrentUserDefault(), read_only=True ) class Meta: model = Review fields = ('id', 'text', 'author', 'score', 'pub_date') def validate(self, data): title_id = self.context['view'].kwargs['title_id'] author = self.context['request'].user if Review.objects.filter(title_id=title_id, author=author).exists(): raise serializers.ValidationError( 'You cannot post second review on same item.' ) return data models.py class Review(models.Model): title_id = models.ForeignKey( Title, on_delete=models.DO_NOTHING, related_name='reviews' ) text = models.TextField( 'Текст отзыва' ) author = models.ForeignKey( User, on_delete=models.DO_NOTHING, verbose_name='Автор', related_name='reviews' ) score = models.IntegerField( choices=SCORES ) pub_date = models.DateTimeField( 'Дата публикации', auto_now_add=True,) class Title(models.Model): name = models.CharField( max_length=255, … -
Table order messed in Firefox, but works fine in other browsers
I have a table that I sort by date, it works fine in EDGE and Chrome, but the order is messed in Firefox. A series of rows that should be on top got moved down to the bottom. HTML: <div class="row mt-4"> <div class="col-12"> <div class="card"> <h6 class="card-header">Change Log Items</h6> <div class="card-body"> <table id="changes" class="table table-striped table-hover table-bordered table-sm"> <thead class="table-dark"> <tr class="sticky"> <th>Title</th> <th>Component</th> <th>Date Committed</th> <th>Jira Link</th> <th>Details</th> </tr> </thead> <tbody> {% for log in logs %} <tr> <td>{{log.title}}</td> <td>{{log.component}}</td> <td>{{log.date_added}}</td> <td>{% if log.jira_number %}<a class="general" href="https://jira.kinaxis.com/browse/{{log.jira_number}}" target="_blank">{{log.jira_number}}{% endif %}</a></td> <td>{% if log.details %}{{log.details}}{% elif not log.details and log.jira_number %}See Jira ticket{% endif %}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> View: @login_required def change_log(request): logs = ChangeLog.objects.all().order_by('date_added') return render(request, 'help\changelog.html', {'logs': logs}) Any information helps! :) -
How to Fatch data from shutteratock api using django?
view.py: curl -X GET "https://api.shutterstock.com/v2/images/search" --header "Authorization: Bearer $SHUTTERSTOCK_API_TOKEN" -G --data-urlencode "query=hiking" --data-urlencode "image_type=photo" --data-urlencode "orientation=vertical" --data-urlencode "people_number=3" -
My python program can't find the path to insert a .ttf
I am using the FPDF library in python to create a report, it contains the Arial font, and it needs a .ttf to work correctly when generating the report. pdf = PDF(orientation = 'L', unit = 'mm', format = 'A4') pdf.add_font('Arial', '', "/var/www/johannasenvironment/JohannasEnviroment/JohannasEnviroment/treasuryEmails/mails/arial.ttf", uni=True) At the moment of executing the program, it does not find the arial.ttf file that is in the given path, I already tried with relative path and absolute path, and it still does not find the file. In windows it works correctly, I don't know what happens when you pass it to linux. I am doing something wrong? Should it be implemented differently when I work on linux? if so, how can i do it? I appreciate your collaboration -
Python/Django exclude running tests in subdirectory
I'm trying to run all tests in a Python project from a particular directory but need to exclude some test from a subdirectory. Would like input into how to exclude tests from a subdirectory. home/ --tests/ --views/ --/viewtest1.py --models/ --/modeltest1.py --test1.py I basically want to run everything under home except anything in tests/view. #This will execute all tests under home but would include views tests. ./manage.py test home EXCLUDE_DIRS from python is only ignoring top level directories and not a subdirectory. So this statement doesn't work. EXCLUDE_DIRS=views ./manage.py test home -
Problem PHP with Django, Take PHP like plain text
I have this code {% for h in lineas %} <tr> <?php> $hola=4 </?> <th scope="col"><a onclick="restar()">{{h}}</th> </tr> {% endfor %} but in the navigator i see the PHP code like Plain text: $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 $hola=4 i cant find the problem. Can you help me please? -
Could not resolve URL for hyperlinked relationship with Django REST Framework
I am building a project in Django Rest Framework to interact with my React app, enabling users to signup and create a profile. However, when I run python manage.py runserver and click on the url appearing on API Root Page I get the following error message: ImproperlyConfigured at /profiles/ Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Here is my models.py code: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True) location = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() My serializers.py: from rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('user', 'name', 'location', 'email', 'signup_confirmation') urls.py: from django.urls import path, include from rest_framework import routers from .import views router = routers.DefaultRouter() router.register(r'profiles', views.ProfileViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] and views.py from rest_framework import viewsets from .serializers import ProfileSerializer from .models … -
urlize colour change Django
I am using 'urlize' in django (4.0.1) as follows in a 'project description' field and it works great. <h6>{{ project.description | urlize }}</h6> Is there a simple way to include a different color style for the url that urlize identifies ? For example, standard text in black and the url in say blue Thank you. -
Django create file programatically on save
The goal with this is for the user to create an instance of the model where they populate a source URLField, and on save, it would fetch the URL and save it as a file. class ComicImage(UUIDModel): src = models.URLField('Comic URL', max_length=512, blank=True) img = models.FileField('Images', null=True, blank=True, upload_to='comics') def save(self, *args, **kwargs): img_data = BytesIO(requests.get(self.src).content) self.img.save(f'{self.hash}-i.webp', content=img_data) super().save(*args, **kwargs) But I keep getting an error ValueError: The 'img' attribute has no file associated with it. Which appears that it's not assigning a file to the field. Or rather, it doesn't until AFTER the model is saved. Alternatively: I also tried self.img.save(f'{self.hash}-i.webp', content=img_data, save=True) But it gets stuck in a loop of saving forever. If I set save=False, then it creates the model but not the file. Is there a way to create/populate/modify the file before it's saved? -
Filtering sequences of events in django
My django app stores the actions that players do during a game. One of the models is called Event, and it contains a list of all actions by players. It has the following 4 columns: game_id, player_name, action, turn. Turn is the number of the turn in which the action takes place. Now I want to count how often players behave in certain patterns. For example, I want to know how often a player takes decision A in turn 2 and that same player takes decision B in turn 3. I'm breaking my head over how I can do this. Can someone help? Note: Ideally the queries should be efficient, bearing in mind that some related queries are following. For example, after the above query I would want to know how often a player takes decision C in turn 4, after doing A and B in turns 2 and 3. (The goal is to predict the likelihood of each action, given the actions in the past.) -
making query for python with ajax
hey i want to make a query for a template.i have few buttons with names. as soon as I click this button, ajax ensures that I see the data behind these names. the ajax side is ready but python side fails. def check(request): is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest' if is_ajax: if request.method == 'GET': empinfo = Employe.objects.filter(id=is_ajax) return JsonResponse({'info': list(empinfo.values())}, safe=False, status=200) return HttpResponse("Ajax with Django Success!") index.html $(document).ready(function() { $(".info-employe").click(function(){ $.getJSON('/checks/', function(response) { for(var key in response.info) $('#name').append('<p> Name: ' + response.info[key].name + '</p>'); $('#surname').append('<p>Surname : ' + response.info[key].surname + '</p>'); $('#worknumber').append('<p> Work number: ' + response.info[key].work_number + '</p>'); $('#workplace').append('<p> Workplace: ' + response.info[key].workplace + '</p>'); $('#rank').append('<p> Rank: ' + response.info[key].rank + '</p>'); $('#email').append('<p> Email ' + response.info[key].email + '</p>'); }); }); }); main.js function checkEmp(id_s, action){ $.ajax({ url: "/checks/", type:"GET", headers: { "X-Requested-With": "XMLHttpRequest", 'X-CSRFToken': csrftoken, }, dataType: 'json', success: (data) => { console.log(data); } }) } -
ORM Query pulling objects outside date range due to Timezone change
I have a piece of legacy code that uses interpolated SQL with psycopg2 to perform a query. However I wanted to clean this up and make the code use the only the ORM. However I'm having an issue where my ORM query is pulling results outside of the given date range when the Timezone is set to non UTC. For example, given the following model: class Dinner(models.Model): eaten_at = models.DateTimeField() And giving the following arbitrary objects I have in my database: Dinner(id=1, eaten_at=2022-02-23 16:58:11+00:00) Dinner(id=2, eaten_at=2022-02-23 23:59:59+00:00) Dinner(id=3, eaten_at=2022-02-24 00:00:00+00:00) Dinner(id=4, eaten_at=2022-02-24 00:00:00+00:00) I wanted to run a query for Dinners eaten on or after 2022-02-24 eaten_after_date = datetime.datetime.combine(datetime.datetime.strptime("2022-02-24", "%Y-%m-%d"),datetime.time(0, 0, 0)) # datetime.datetime(2022, 2, 24, 0, 0) My Psycopg2 Code looked like this: cursor.execute("SELECT * FROM dinner WHERE dinner.eaten_at >= %s with time zone", eaten_after_date) As expected this results in two rows pulled with corresponding ID's 3 and 4. I've re-written this using purely the ORM as: Dinner.objects.filter(eaten_at__gte=eaten_after_date) And in some instances- this works. However- when I have the following in settings: TIME_ZONE = "Asia/Tokyo" I return objects before the 24th (in this specific example- it returns ALL rows). For instance getting the first result sorted returns an entry … -
Can't execute queries when insert multi related objects in Django migration file
I want to initiate basic data of 4 related model in migration file. This is list of my models: Test QuestionCategory(with `Test` FK) Question(with `QuestionCategory` and `Test` FK) And also this is my function that import data in migration file: def step3(apps, db_alias): import pandas as pd import os file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'initial_data/PyTest-BasicData.xlsx') questions_df = pd.read_excel(file_path, sheet_name='Questions', engine='openpyxl', ) questions_list = questions_df.T.to_dict().values() QuestionCategory = apps.get_model("PsyTest", "QuestionCategory") Question = apps.get_model("PsyTest", "Question") for item in questions_list: category_title = None if pd.isna(item["category_title"]) else item["category_title"] category_type_choice = None if pd.isna(item["category_type_choice"]) else item["category_type_choice"] category_reference_title = None if pd.isna(item["category_reference_title"]) else item["category_reference_title"] reference = None int_test_pk =int(item["test_pk"]) if category_reference_title: try: reference = QuestionCategory.objects.using(db_alias).get(test_id=int_test_pk, title=category_reference_title) except QuestionCategory.DoesNotExist: reference = QuestionCategory(test_id=int_test_pk, title=category_reference_title, category=1) reference.save() try: category = QuestionCategory.objects.using(db_alias).get(test_id=int_test_pk, title=category_title) except QuestionCategory.DoesNotExist: category = QuestionCategory(test_id=int_test_pk, title=category_title, category=int(category_type_choice), reference=reference) category.save() try: _ = Question.objects.using(db_alias).get(test_id=int_test_pk, title=item["title"]) except Question.DoesNotExist: question = Question(test_id=int_test_pk, title=item["title"], row=int(item["row"]), is_active=item["is_active"], category=category) question.save() In another function I imported Test objects in migration file and all things goes well, But when I use multi models and relations in migration file -like above function-, I got this error: raise TransactionManagementError( django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. How can … -
Django ModelsConditional ForeignKey
i have 4 Django Models (Team, Player, Game, Throw): class Team(models.Model): team_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class Player(models.Model): player_id = models.AutoField(primary_key=True) team_id = models.ForeignKey(Team, on_delete=models.DO_NOTHING) name = models.CharField(max_length=50) class Game(models.Model): game_id = models.AutoField(primary_key=True) team1_id = models.ForeignKey(Team, related_name='team1', on_delete=models.DO_NOTHING) team2_id = models.ForeignKey(Team, related_name='team2', on_delete=models.DO_NOTHING) class Throw(models.Model): throw_id = models.AutoField(primary_key=True) game_id = models.ForeignKey(Game, on_delete=models.CASCADE) player_id = models.ForeignKey(???) score = models.IntegerField() Is there any option for the Throw model to set a condition on field player_id = models.ForeignKey(???), so that i can only select the players from the two teams in the game model ? -
Django: How do I change an image type to WebP in upload?
I have a website that has a blog, and the upload images are served just right but the image format slows down the website and I wanted to make them all be converted to WebP, which loads faster, on upload, is there any way to do that? my image field: from django_resized import ResizedImageField class Post(models.Model) image = ResizedImageField(size=[600, 500], quality=100, upload_to ='media/', default = 'media/placeholder.png')