Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to resolve django : ImportError: cannot import name 'parse_header' from 'django.http.multipartparser'
My application was running fine till few days back, but now all of a sudden i'm seeing this error and not sure what it means, please help. Error: File "/myproj/myapp/urls.py", line 8, in <module> from rest_framework import routers File "/usr/local/lib/python3.8/site-packages/rest_framework/routers.py", line 22, in <module> from rest_framework import views File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 15, in <module> from rest_framework.request import Request File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 17, in <module> from django.http.multipartparser import parse_header ImportError: cannot import name 'parse_header' from 'django.http.multipartparser' (/usr/local/lib/python3.8/site-packages/django/http/multipartparser.py) my line 8 of urls.py is: from rest_framework import routers and i could see the parse_header method in the multipartparser.py file PFA multipartparser file -
Google file picker API giving error Javascript
I am trying to implement a google file picker in my Django Project. Currently when I try to create an HTML page with Google file picker integrated I am facing 500 Something went wrong error. This happens after I authorize my app and create access token. First I was thinking that access token generation must be having some issues, but I tried listing files using the access token generated and I was able to successfully list down files in my Google drive as can be seen in the browser console. Help will be greatly appreciated. Below is my HTML code. <!DOCTYPE html> <html> <head> <title>Picker API Quickstart</title> <meta charset="utf-8" /> </head> <body> <p>Picker API API Quickstart</p> <!--Add buttons to initiate auth sequence and sign out--> <button id="authorize_button" onclick="handleAuthClick()">Authorize</button> <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button> <pre id="content" style="white-space: pre-wrap;"></pre> <script type="text/javascript"> /* exported gapiLoaded */ /* exported gisLoaded */ /* exported handleAuthClick */ /* exported handleSignoutClick */ // Authorization scopes required by the API; multiple scopes can be // included, separated by spaces. const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'; // TODO(developer): Set to client ID and API key from the Developer Console const CLIENT_ID = '<YOUR_CLIENT_ID>'; const API_KEY = '<YOUR_API_KEY>'; // TODO(developer): Replace with your … -
Django 3.2 CITEXT and unique_together
I'm using Django 3.2 and postgreSql 12. I've added a new text field that should be case-insensitive, i.e if the value 'ab' exists, I want the DB to fail the request if someone is inserting 'Ab'. But this field shouldn't be unique all over the table, but unique with another field (unique_together). I've tried creating the field as 'CITEXT' and since it's deprecated in Django 4.2 I've used the Collation migration as recommended. The migrations passed, and when testing it I see that I can create two objects with the same letters, and different cases. Am I doing something wrong or this implementation of case-insensitive shouldn't work with 'unique_together'? The collation migration: operations = [ CreateCollation( "case_insensitive", provider="icu", locale="und-u-ks-level2-kn-true", deterministic=True, ), ] The model changes: class MyItem(models.Model): identifier = models.CharField(db_collation="case_insensitive", db_index=True, max_length=100, null=True) container = models.ForeignKey(Container, related_name='my_items', on_delete=models.CASCADE, null=True) class Meta: unique_together = ('identifier', 'container_id') After running the migrations, I've successfully created two MyItems with the same container and identifier='ab' and 'Ab' -
I am Facing issue in mysql
while using this command - pip install mysql I am facing issue in code error: subprocess-exited-with-error note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. I try pip3 install mysql -
"'xml.etree.ElementTree.Element' object has no attribute 'getiterator'" when I try to make markdown filter for my blog
Thanks for any of your answers! My question is: I learn Django with book "Django By Example". Now I'm learning "Custom template filters" chapter. And I do everything what author is telling to do. But there is a problem. I get error, witch look like this: "'xml.etree.ElementTree.Element' object has no attribute 'getiterator'" I tried to write function in this way: @register.filter(name='markdown') def markdown_format(text): return mark_safe(markdown.markdown(text)) and my list.html file looks like this: {% extends "blog/base.html" %} {% load blog_tags %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% if tag %} <h2>Posts tagged with "{{ tag.name }}"</h2> {% endif %} {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="tags"> Tags: {% for tag in post.tags.all %} <a href="{% url "blog:post_list_by_tag" tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|markdown|truncatewords_html:30 }} {% endfor %} {% include "pagination.html" with page=posts %} {% endblock %} Full version of the previous code you can find here: https://github.com/PacktPublishing/Django-3-by-Example/tree/master/Chapter03/mysite -
Django create create GET url in template
I want to make get request on the django site page, {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ url 'clothes:designer' }}?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{{ url 'clothes:designer' }}?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> {% endif %} i dont want to hardcode href url can i create GET request url like {{ url 'page' method='get' **kwargs }}? i tried to find in django docs, but i have not found -
django.db.utils.OperationalError [Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection
I am using mssql server as my database in Django, hosted on Heroku. I am having trouble connecting to that database with ODBC Driver 17 for SQL Server. #requirements.txt asgiref Django==4.0 pytz sqlparse djangorestframework gunicorn python-dotenv django-mssql-backend whitenoise pyodbc Config Vars . . . ENGINE: sql_server.pyodbc MSSQL version: Microsoft SQL Server 2014 settings.py 'default': { 'ENGINE': os.getenv('ENGINE'), 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': os.getenv('DATABASE_HOST'), "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", } }, Aptfile: unixodbc unixodbc-dev As for the compatibility check, the SQL server is in-fact compatible with Driver 17. https://learn.microsoft.com/en-us/sql/connect/odbc/windows/system-requirements-installation-and-driver-files?view=sql-server-ver16 Complete error: File "/app/.heroku/python/lib/python3.11/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.11/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection conn = Database.connect(connstr, ^^^^^^^^^^^^^^^^^^^^^^^^^ pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection (0) (SQLDriverConnect)') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/app/.heroku/python/lib/python3.11/site-packages/django/db/models/sql/compiler.py", … -
How to auto update data in react
Using react, I want to update chart data every 2 seconds from Django database but each 2 seconds charts component keeps recreating. how to prevent that from happening? In zoneActions.js : export const getZonesList = (cname) => async (dispatch, getState) => { try { dispatch({ type: ZONE_LIST_REQUEST }); const { userLogin: { userInfo }, } = getState(); const config = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${userInfo.token}`, }, }; const { data } = await axios.get( `http://127.0.0.1:8000/zones/get/${cname}/`, config ); dispatch({ type: ZONE_LIST_SUCCESS, payload: data, }); } catch (error) { dispatch({ type: ZONE_LIST_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }); } }; dashboard.js : const { cname } = useParams(); const zoneList = useSelector((state) => state.zoneList); const { zones } = zoneList; useEffect(() => { dispatch(getZonesList(cname)); const interval = setInterval(() => { dispatch(getZonesList(cname)); }, 2000); return () => clearInterval(interval); }, [dispatch]); -
UserSignupForm.custom_signup() takes 2 positional arguments but 3 were given
I extended django-allauth's UserSignUpForm for a custom form upon signup but I got an error when I signed up in my local development server. UserSignupForm.custom_signup() takes 2 positional arguments but 3 were given Here's my form class UserSignupForm(SignupForm): type = forms.ChoiceField(choices=[("RECRUITER", "Recruiter"), ("SEEKER", "Seeker")]) def custom_signup(self, user): user.type = self.cleaned_data['type'] user.save() I expect it to be working since this isnt the first time I implemented this kind of signup form but I got lost in the rabbit hole. -
how can i extend barcode image to write caption and text?
I need to generate a barcode image like that one enter image description here like this I generated this one enter image description here -
Model has no attribute '_meta'
We're creating a API Documentation generation using drf_yasg. We Encountered a problem that says Model has no attribute '_meta'. I'm thinking of it as a model problem has anyone encountered similar error? Error Message Models.pu class TermsAndCondition(TimeStampedModel): company = models.ForeignKey(Company, related_name='terms_and_conditions', on_delete=models.CASCADE, blank=True, null=True) pdfUpload = models.FileField(upload_to=pdf_path, max_length=None, blank=True, null=True) def __str__(self): return self.company.name class Meta: app_label = "applicationname" The API Documentation supposed to be running at localhost/docs/ but since because of the problem it won't show -
Google App Engine deployment error 502: Bad Gateway with Django and Gunicorn
I am trying to deploy a Django application on Google App Engine using Gunicorn as the WSGI server. The application works well locally, but when deployed to App Engine, I encounter a 502: Bad Gateway error. I have checked the logs in Google Cloud Console and can't find any relevant errors. Here is my app.yaml configuration file: runtime: python311 entrypoint: gunicorn -b :$PORT --timeout 120 LyAnt.wsgi:application env_variables: DJANGO_SETTINGS_MODULE: "LyAnt.settings" ENV: "PRODUCTION" handlers: - url: /static static_dir: static/ - url: /.* script: auto automatic_scaling: min_idle_instances: 1 max_idle_instances: 2 min_pending_latency: 30ms max_pending_latency: automatic I tried running Gunicorn locally, but it does not work due to the "ModuleNotFoundError: No module named 'fcntl'" error. I understand that Gunicorn is not recommended for Windows environments, so I tested my application locally using Waitress, and it works fine. I expected my application to work on Google App Engine after deployment, but I am encountering a 502 error instead. -
How to convert Django Queryset into a list in template?
Here is my model : class Building(models.Model): Building_code = models.CharField(primary_key=True, max_length=255) Building_name = models.CharField(max_length=255) @property def BuildingFullName(self): fullname = '{} | {}'.format(self.Building_code, self.Building_name) return fullname def __str__(self): return self.Building_code What i do in my template : <tbody> {% for hira in hiras %} <tr> <td>{{ hira.Activity }}</td> <td>{{ hira.Hazard.Hazard }}</td> <td>{{ hira.PBS.Code }}</td> {% with allbuilding=hira.Building.all %} <td>{{ allbuilding }}</td> {% endwith %} <td>{{ hira.Building.Function_Mode }}</td> {% endfor %} </tbody> This is what I am getting : here But I would like the building list to be displayed without this "<Queryset". For the first row, it would be "13, 14". -
Local gulp not found inside docker container
I am trying to rebuild a past project regarding Django and gulp.js. Gulp is used to build the static assets from Django. I am now dockerizing this project. In order to do it, I am using a python and node combo image from this hub. I install the necessary packages both from Django and node. I copy the source code into the container. Run gulp and ./manage.py runserver. When I run gulp, I get an error that the local gulp cannot be found in the directory. app | [06:49:46] Local gulp not found in /usr/src/app app | [06:49:46] Try running: yarn add gulp I have this directory tree. The src/ holds the source codes and I copy this to the container. It holds the gulpfile.js and manage.py. . └── project/ ├── dockerfiles/ │ └── app.Dockerfile ├── src/ │ ├── apps/ │ ├── entrypoints/ │ │ └── entrypoint-local.sh │ ├── gulpfile.js │ ├── manage.py │ ├── package.json │ └── package-lock.json ├── .local.env └── docker-compose.yml Here is my docker-compose file. version: "3.9" app: container_name: app build: dockerfile: ./dockerfiles/app.Dockerfile entrypoint: ./entrypoints/entrypoint-local.sh volumes: - ./src:/usr/src/app - static:/static ports: - "8000:8000" env_file: - .local.env Here is how I build the app container. # syntax=docker/dockerfile:1 FROM … -
DRF Query optimization for nested_serializer with select_related queryset
This is My Model class PropertyBasic(Model): pass class ManagementProperty(Model): propertybasic = models.ForeignKey(PropertyBasic) class PropertyUnit(Model): management_property = models.ForeignKey(ManagementProperty) This is My queryset in view class PropertyUnitListView(ListAPIView): def get_queryset(self): return PropertyUnit.objects.all().select_related('management_property__propertybasic') This is My Serializer class PropertyUnitSerializer(serializers.ModelSerializer): property_basic = PropertyBasicSerializer(source='management_property.propertybasic') ... But why does similar query occur? The strangest part is that even if I don't load property_basic from serializer, the similar query is not lost. What can I do to remove these similar queries...? -
Django forms's logic for a form in a base template
I'm trying to figure out how to deal with this situation. I have three views: def view0(request): ... return render(request, 'home.html') def view1(request): ... return render(request, 'about.html') Both view templates extends a template called 'base.html', in which there is a contact form. What I'm wondering is: do I need to write python code in both views to handle all the logic inherent in the form's operation? Or can I create a view whose only job is to handle the logic of this specific form? I tried to create a separate view, assigning it a url to which the 'action' attribute of the form refers: def base_view(request): if request.method == 'POST' contact_form = Form(request.POST) #logic here else: contact_form = Form() context = {'contact_form': contact_form} return render (request, 'base.html', context) def view0(request): ... return render(request, 'home.html') def view1(request): ... return render(request, 'about.html') 'base.html' has the following code for the form: ..... <form action="{% url 'base_view_url' %}" method="post"> {% csrf_token %} {{contact_form}} <input type="submit" value="Invia"> </form> ..... With this code the contact form does not work. -
I want to print my django views.py before my async api calls..but this is not happened My middleware is not work Asyncio is not run in async mode
first I make a django middleware.py for django (Package) from dapycorelogger.api import api import datetime class Middleware: def __init__(self, get_response): self.get_response= get_response def __call__(self, request): response= self.get_response(request) if request.encoding == None: request.encoding= "encoding" else: request.encoding if request.content_params == {}: request.content_params= "empty" else: request.content_params body= str(request.body) content= str(response.content) header= str(response.headers) api_request = { "url_scheme": request.scheme, "request_path": request.path, "request_path_information" : request.path_info, "request_method": request.method, "request_cookies": request.COOKIES, "request_encoding": request.encoding, "request_content_type": request.content_type, "request_content_params": request.content_params, "host": request.get_host(), "request_body": body, 'response_code': response.status_code, "response_headers": header, "response_content": content, 'response_length_byte': len(content) } api(api_request) return response ----------then make an python core api.py (Package)----------------------- from dapycorelogger.server_info import Server import asyncio import httpx import aiohttp server1= Server() url= "http://stage.linqer.in/" api_response= server1.get_info() def api(data): async def call_api(url): print("test3") api_response.update(data) await asyncio.sleep(10) async with httpx.AsyncClient() as client: response= await client.get(url, params=api_response) print("test2") print(response.url) asyncio.new_event_loop().run_until_complete(call_api(url)) ---------------After that make a Python project for print Views.py-------- async def index(request): return HttpResponse("Hello, world. You're at the polls index.") -------Then add a middleware in setting.py---- I want to call my django views.py before my async api.py calls..Asynchonous means a unit of work run separately from the primary application. -
How to Edit the Django User Verification Email Link
My Django User Verification Email Link starts "http" below is example http://examplesitexxx.com/accounts/confirm-email/MTA:1poGIh:x7zOj4350ZP6uLhT0wUEp1CRE13jWrvRanofpFgTBkw/ I want to change the Verification URL that starts with 'https'. So I access the file "allauth/templates/account/email/email_confirmation_message.txt" In this file I see "{{ activate_url }}" It should be a source of Verification Email URL but I can't figure out how to change the activate_url that start from "https" from "http" I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Database Optimization of a Giveaway Website Using Django
Hello everything is fine? So, the old project that is a "raffle" site has a chronic problem which is the use of up to 1000% of the CPU that is an AMD Ryzen 9 with 16 cores at high peaks of site usage. The total responsible for this enormous use is the database due to its lack of architecture/optimization. The challenge is: Solve this and make the site fast and accessible. For that, I'll use Django and thought of some ways to solve this, among them, here's a possible solution. models.py from the app raffle class Raffle(models.Model): ... amount_of_numbers = models,PositiveInteger(default=100000) The system will define the total number of tickets or the user and with these numbers, in the save method I will create 50-100 .txt files with numbers from 1 to 100000 without repetitions to avoid adding repeated numbers and causing " harmful queries" import fcntl with open('arquivo.txt', 'r') as arquivo: fcntl.flock(arquivo, fcntl.LOCK_EX) ... fcntl.flock(arquivo, fcntl.LOCK_UN) I will use the a lib fcntl to guarantee that only one user has access to that list of numbers (that's why several lists) and avoid having to check repeated numbers in the database and after finishing the process, I will release the … -
cx_Oracle not found in RDP
I am trying to run the django in remote server where Internet access is not avaiable, I have copied the libaries/pacakages from my local to remote server and tried to run it and packages were accepted but cx_Oracle it is module not installed.I have already set the client libary path in environmental path. PS C:\Users\Administrator\Documents\HC_REST\HC_REST> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\oracle\base.py", line 52, in <module> import cx_Oracle as Database ModuleNotFoundError: No module named 'cx_Oracle' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Sysadm01\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", … -
Django models and null=True
I am creating an auction website. I have a Django model for Listings. It looks like this: class Listings(models.Model): price = models.FloatField() title = models.CharField(max_length=64) description = models.CharField(max_length=128) imageUrl = models.CharField(max_length=1000, default="") isActive = models.BooleanField(default=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True, related_name="category") watchlist = models.ManyToManyField(User, blank=True, null=True, related_name="watchlistListing") def __str__(self): return f"{self.id}: {self.title}, {self.description}, {self.price}, {self.imageUrl}" My problem is that whenever I create a listing and try to access its 'owner' attribute, it returns 'None'. However, I can access the current user perfectly fine by using 'request.user'. I tried removing the null=True and the blank=True parameters from the owner attribute. However this did not work and now whenever I try to access the owner attribute it just says the listing has no owner. type here -
Django: how to create a signal using django?
I have a bidding system and there is an ending date for the bidding, i want users to bid against themselves till the ending of the bidding date. The product creators are the ones to add the ending date which would be some date in the future, how can i write a django signal to check if the date that was added as the ending date is the current date, then i'll perform some operations like mark the highest bidder as winner. This is my model class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) price = models.DecimalField(max_digits=12, decimal_places=2, default=0.00) type = models.CharField(choices=PRODUCT_TYPE, max_length=10, default="regular") ending_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) ... class ProductBidders(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name="product_bidders") price = models.DecimalField(max_digits=12, decimal_places=2, default=1.00) date = models.DateTimeField(auto_now_add=True) -
Getting this error in DJANGO when trying to make a record inSQL
Not sure why I am getting this error when I try to call a function within my load_data() django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. However, when I run the crud_ops.py function it works fine and sets the records within the database load_data.py def publisher_data(listt, start): from reviews.models import Publisher check_list = [] query_list = [] for i in range(start + 1, len(listt)): if listt[i].__contains__("publisher"): check_list.append(listt[i]) else: query_list.append(listt[i]) if len(query_list) == len(check_list): print(query_list) publisher = Publisher(name=query_list[0], website=query_list[1], email=query_list[2]) publisher.save() query_list = [] if listt[i].__contains__("content"): break def load_data(): file_read = open("WebDevWithDjangoData.csv", "r") text = file_read.read().split(",") new_list = [x for x in text if x.strip() != ''] list_1 = [] start_index = None end_index = None for x in new_list: list_1.append(x.strip()) file_read.close() for x in range(len(list_1)): #print(list_1[x]) if list_1[x] == "content:Publisher": start_index = x publisher_data(list_1, start_index) crud_ops.py: def crud_ops(): from reviews.models import Publisher, Contributor publisher = Publisher(name='Packt Publishing', website='https://www.packtpub.com', email='info@packtpub.com') publisher.save() publisher.email = 'customersupport@packtpub.com' publisher.save() print(publisher.email) contributor = Contributor.objects.create(first_names="Rowel", last_names="Atienza", email="RowelAtienza@example.com") print(contributor) print('\n>>> END <<<') manage.py: import os import sys from crud_ops import * def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookr.settings') try: from django.core.management import execute_from_command_line … -
Problems with Django structuring when entering models, views and serializers in folders?
Hello I am learning to program in Django and I have a database of 22 tables, as you can see making all the models in a single class would be very cumbersome and messy to find or make corrections, the same thing happens to me with serializers and views. How would it be the right thing to create as separate modules to the base project or to make backend/api/models ... backend/api/views ... backend/api/serializers/init.py? enter image description here I created something basic serializer and view but when I join it to the urls.py I get compilation problems. I was told that inside each folder create the init.py and integrate there the from of what is created in that folder, but when I start to spread it to the other modules it generates error. Example: Folder Models Models/__init__.py from . import Service Folder Serializers Serializers/__init__.py from . import ServiceSerializer The default models, serializers and views files that are created by default are blank, is that the problem? Views/__init__.py from . import service_view Views/service_view.py from models.Service import Service from rest_framework import generics from rest_framework.response import Response from rest_framework.decorators import api_view from serializers.service_serializer import ServiceSerializer # Listar servicios class ServiceListApiView(generics.ListCreateAPIView): queryset = Service.objects.all() serializer_class … -
Does apply_async(retry=False) disable the task level retry
I have a task like such @shared_task(bind=True, max_retries=150) def payout_reconciliation_single_task(self, txn_id): try: txn = Transaction.objects.filter(pk=txn_id).select_for_update().get() except Transaction.DoesNotExist: self.retry(throw=False, countdown=10 * 60) return Now if I call the task like payout_reconciliation_single_task.apply_async((123,), countdown=10, retry=False) Will the self.retry inside the try-catch block inside the except block in the task still be honored?