Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieve the human readable value of a a charfield with choices via get_F00_display in Django views.py
What I want to do : Display the human readable value of a charfield with choices via get_F00_display or other in views.py and then in template. I have a Leave model for leaves management et want to display a template with all the leaves associated with the authenticated user. What I have done : Of course, I've read Django documentation (4.1) and find something interesting with get_F00_display but cannot make it works fine. model.py (simplified) class Leave(CommonFields): LEAVES_TYPES = [ ('10', _('Type 1')), ('20', _('Type 2')), ('30', _('Type 3')), ] owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) type = models.CharField(max_length=3, choices=LEAVES_TYPES, null=True, default="10") def __str__(self): return self.owner.first_name + " " + self.owner.last_name + " : du " + self.begin_date.strftime("%d-%m-%Y") + " au " + self.end_date.strftime("%d-%m-%Y") views.py from django.shortcuts import render from django.utils.translation import gettext as _ from .models import Leave from django.views import generic class LeaveListView(generic.ListView): model = Leave context_object_name = 'leave_list' def get_queryset(self): return Leave.objects.filter(is_active=True).values('type', 'begin_date','end_date','range','comment','status') def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super(LeaveListView, self).get_context_data(**kwargs) # Create any data and add it to the context context['colHeaders'] = ['Type', 'From', 'To.', 'Range', 'Comment', 'Status',] return context leave_list.html {% extends "main/datatables.html" %} <!-- TABLE … -
Writable nested serializers for multiple items for same base class
I have been following the guide to write nested serializer. Previously, I had only one item in my json object which was CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents and I am able to save the data properly in the databae. I want to add NetIncomeLoss the same way but I am running into the issue below. Can someone please point me where my mistake is? I am unable to find documentation/example or an answer online TypeError: Basetable() got unexpected keyword arguments: 'NetIncomeLoss' Serializer: class PeriodSerializer(serializers.ModelSerializer): instant = serializers.CharField(required=False, max_length=255) startDate = serializers.CharField(required=False, max_length=255) endDate = serializers.CharField(required=False, max_length=255) class Meta: model = Period fields = "__all__" extra_kwargs = {'cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id': { 'required': False}, 'netincomeloss_id': { 'required': False}} class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents fields = ['decimals', 'unitRef', 'value', 'period'] class NetIncomeLossSerializer(serializers.ModelSerializer): period = PeriodSerializer(many=False) class Meta: model = Netincomeloss fields = ['decimals', 'unitRef', 'value', 'period'] class CashFlowSerializer(serializers.ModelSerializer): CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer( many=True) NetIncomeLoss = NetIncomeLossSerializer( many=True) class Meta: model = Basetable fields = "__all__" def create(self, validated_data): itemOneData = validated_data.pop( 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents') cashflow = Basetable.objects.create(**validated_data) for data in itemOneData: period_data = data.pop("period") my_long_named_obj = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents.objects.create( basetable_id=cashflow, **data) period_object = Period.objects.create( cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id=my_long_named_obj, **period_data ) itemTwoData = validated_data.pop( 'NetIncomeLoss') cashflow = Basetable.objects.create(**validated_data) for data in itemTwoData: period_data … -
Set same color as prev row if data matches otherwise different color when rows are dynamically created
I need to set same color as previous row if data matches otherwise use a different color when rows . The code works if the rows, cells and text within cells are hardcoded as here https://codereview.stackexchange.com/questions/121593/set-same-color-as-prev-row-if-data-matches-otherwise-different-color but produces alternating colouring when the rows, cells and text are dynamically generated. $(document).ready(function () { var c = 0; $("#tblExport tbody tr").each(function () { var $item = $("td:first", this); var $prev = $(this).prev().find('td:first'); if ($prev.length && $prev.text().trim() != $item.text().trim()) { c = 1 - c; } $(this).addClass(['zebra-even', 'zebra-odd'][c]); }); }); #tblExport>tbody { font: normal medium/1.4 sans-serif; } #tblExport { border-collapse: collapse; width: 100%; } #tblExport th,td { padding: 0.25rem; text-align: left; border: 1px solid #ccc; } #tblExport th { background: #bfbfbf; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> {% for product in products %} <tr> <td>{{product.name}}</td> <td>{{product.price}}</td> </tr> -
Django Forms - Declarative Fields Meta class is not iterable
Why django throws me an error TypeError at /primary argument of type DeclarativeFieldsMetaclass is not iterable. I'm trying to work with django-forms for the first time, after i added this into my forms.py file, it keeps showing me the error message saying: TypeError at /primary argument of type 'DeclarativeFieldsMetaclass' is not iterable, how can i solve this problem? Forms.py from django import forms from .models import Primary, PrimaryAlbum, Secondary, SecondaryAlbum from jsignature.forms import JSignatureField from jsignature.widgets import JSignatureWidget class PrimaryForms(forms.Form): signature_of_student = JSignatureField( widget=JSignatureWidget( jsignature_attrs={'color':'#e0b642', 'height':'200px'} ) ) class Meta: model = Primary fields = ['admission_number', 'profile_picture', 'first_name', 'last_name', 'gender', 'address_of_student', 'class_Of_student', 'signature_of_student'] Views.py from .forms import PrimaryForms class CreatePrimaryStudent(LoginRequiredMixin, CreateView): model = Primary fields = PrimaryForms template_name = 'create_primary_student_information.html' success_url = reverse_lazy('Home') def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['year_of_graduation'].queryset = PrimaryAlbum.objects.filter(user=self.request.user) return form def form_valid(self, form): form.instance.user = self.request.user return super(CreatePrimaryStudent, self).form_valid(form) -
I need to insert data in table SQLite Django
I am new to Django. I think it's really easy one for Django expert, so I wish I could get help from you. I have two tables in SQLite DB-namely Process and ScrapedData. While migrating models I have several error so I just create these two tables manually by Navicat. Following shows models. class Process(models.Model): PLATFORM=( ('Instagram','Instagram'), ('Facebook','Facebook'), ('LinkedIn','LinkedIn'), ('TikTok','TikTok'), ('Youtube','Youtube'), ('Twitter','Twitter') ) hashtag=models.CharField(max_length=300) platform=models.CharField(choices=PLATFORM,max_length=9) date=models.DateField(auto_now_add=True) class ScrapedData(models.Model): homepage=models.CharField(max_length=500) email=models.CharField(max_length=100) process_id=models.ForeignKey( Process, on_delete=models.CASCADE, verbose_name="the related Process") Then I tried to insert data into these two tables then I got following error. File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: table info_scrapeddata has no column named process_id_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\task\scrapping\scraping for google api\College-ERP\info\views.py", line 116, in attendance_search ScrapedData.objects.create(homepage=url.strip(),email=email, process_id=new_process) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) File … -
Celery basic scheduling with apply_async is extremely slow
Scheduling tasks from Django endpoints are very slow. .delay / .apply_async of any (even dummy) task takes about 150-200ms which is terrible. Redis is up and running in docker, task is being scheduled to worker without any retries, but it takes ~200 ms just to deliver task to queue. Maybe i am missing some configuration options? My setup: Python 3.10 Django 4 Celery 5.2.7 Eager execution is disabled, celery configs are pretty much default. Attached is a profiler output where simple task eats twice a time of a heavy DB-load operations (see marked (!)): Line # Hits Time Per Hit % Time Line Contents ============================================================== 339 @profile 340 def handle_single_transition( 341 self, 342 *, 343 cr: CR, 344 user: User, 345 taxonomy_data: dict, 346 cr_metadata: dict, 347 attachments: list[InMemoryUploadedFile] = None, 348 ) -> CR: 350 1 0.0 0.0 0.0 target_state_id = cr_metadata.get("target_state_id") 351 1 0.0 0.0 0.0 action_id = cr_metadata.get("action_id") 352 354 1 0.0 0.0 0.0 if target_state_id is None or (cr.state_id == target_state_id): 355 return cr 356 357 1 28.0 28.0 6.1 transition = cr.workflow.get_transition( 358 1 0.0 0.0 0.0 target_state_id=target_state_id, 359 1 0.0 0.0 0.0 action_id=action_id, 360 ) 361 363 1 0.1 0.1 0.0 if taxonomy_data and … -
CORS Issues with Nginx as Reverse Proxy for Django
I am running Nginx as my webserver to server the static frontend files and as a reverse proxy for my Django Server. The Problem is that i am having CORS Issues, when doing request from the frontend. My Design-Plan was to use the Apex Domain example.com for the frontend and all API Calls go to api.example.com. I already did a tone of research and tried to catch OPTIONS request etc. but i still have CORS Errors. Also Django has the django-cors package installed and Axios is using .withDefaultCredentials = true. My current nginx config looks like this: server { listen 80; listen [::]:80; server_name $DOMAIN_HOSTNAME; root /var/www/example.com/dist; location /media { alias /var/www/example.com/media/; } location / { try_files $uri $uri/ /index.html =404; } } upstream djangoserver { server django:8000; } server { listen 80; listen [::]:80; server_name $API_DOMAIN_HOSTNAME; location / { proxy_pass http://djangoserver; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header 'Access-Control-Allow-Origin' $http_origin; proxy_set_header 'Access-Control-Allow-Credentials' 'true'; proxy_redirect off; add_header 'Access-Control-Allow-Origin' 'https://example.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Allow-Credentials' 'true'; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' 'https://example.com'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Allow-Credentials' 'true'; return 204; } } } Also so … -
Server refusing to run in Pycharm giving the following error: OSError: [WinError 127] The specified procedure could not be found
OSError: [WinError 127] The specified procedure could not be found The app was working fine until after I pip installed django-sms. I have since uninstalled django-sms but still getting the same error. Contro panel output -
Django Request input from User
I'm having a Django stack process issue and am wondering if there's a way to request user input. To start with, the user is loading Sample data (Oxygen, CHL, Nutrients, etc.) which typically comes from an excel file. The user clicks on a button indicating what type of sample is being loaded on the webpage and gets a dialog to choose the file to load. The webpage passes the file to python via VueJS/Django where python passes the file down to the appropriate parser to read that specific sample type. The file is processed and sample data is written to a database. Issues (I.E sample ID is outside an expected range of IDs because it was keyed in wrong when the sample was taken) get passed back to the webpage as well as written to the database to tell the user when something happened: (E.g "No Bottle exists for sample with ID 495619, expected range is 495169 - 495176" or "356 is an unreasonable salinity, check data for sample 495169"). Maybe there's fifty samples without bottle IDs because the required bottle file wasn't loaded before the sample data. Generally you have one big 10L bottle with water in it, the … -
How to migrate from StaticBlock to StructBlock?
I have to change an already existing StaticBlock to a StructBlock: class SomeBlock(blocks.StaticBlock): pass class Meta: ... to: class SomeBlock(blocks.StructBlock): ... class Meta: ... However if the wagtail page has already SomeBlock configured in it, I receive the error: NoneType is not iterable Since I don't have anything inside the StaticBlock. I need to write a custom data migration for this. Based on Schema Operations listed, I couldn't find a way to change the actual block type. How do I approach this? -
Using for loop to Html Form in Django Template
I am facing problems handling forms in Django template for loop. <form method="post" id="infoloop{{forloop.counter}}"> {% csrf_token %} <div class="form-group"> <button type="submit" name="infobutton" class="btn btn-warning float-right {% if subs%} {% else %}disabled{% endif %}">update</button> </div> </form> I want to create this form my all employees, but seems doesn't work. Only first loop can create form tag so i can't update second employee info's. Can anyone help me? -
URL Parameters to CreateView and automatic select value in a dropdown
I need, from a listview table, with an js button, open the createview and pass with parameter the id about an specific row that, in the createview form, select automatically the value in a dropdown. I imagine that, it would be with a parameter in the url of the createview and, in the createview, select in the post def the dropdown's row with the value of the parameter. Sorry if my explication it's very complicated. Examples. I have one model, Projects and I have a second model, Phases of these Projects. When I have listed the projects, from a button in one Project's row, I would need that to open the phases's createview and in the form, to select automatically the value of the dropdown's row. Projects form (the icons are bad): projects form When I click on the button with the url path('phases/add/', phasesCreateView.as_view(), name='phases_create'),, I need that in the destiny form phases form, the first dropdown would be completed automatically. -
When to run tests in dockerized django application?
I'm building a CI/CD for a django application. We dockerized the application and now our goal is to automate the building process triggered by push on a github repository. We are now building the GitHub Actions side. The project requires all containers to be running. I'm wondering where I should be running tests. Running them in the docker file seems useless as there are several tests that would fail if the other containers are not running (postgres container for example, or rabbitmq ). The approach I was thinking was to maybe setup a job in GitHub actions, build and start all containers with compose and then run the tests ? What is the recommended approach ? -
how to create celery periodic task in django rest framework Views?
I use django rest framework. I want the celery task to execute an operation once on the date that the user enters... this is my celery conf: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Bimsanj.settings') celery_app = Celery('Bimsanj') celery_app.conf.task_queues = ( Queue('default', routing_key='default'), Queue('reminder', routing_key='reminder'), ) celery_app.conf.task_default_queue = 'default' celery_app.conf.task_routes = { 'send_reminder_message_task' : {'queue' : 'reminder'}, } # Load task modules from all registered Django apps. celery_app.autodiscover_tasks() celery_app.conf.broker_url = BROKER_URL celery_app.conf.result_backend = RESULT_BACKEND and this is my View: class InsuranceReminderView(GenericViewSet, CreateModelMixin): serializer_class = InsuranceReminderSerializer model = InsuranceReminder def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) clocked = ClockedSchedule.objects.create(serializer.validated_data['due_date']) PeriodicTask.objects.create( clocked=clocked, name=str(uuid4()), one_off=True, task="apps.insurance.tasks.send_message_insurance_reminder", args=([serializer.validated_data['title'], serializer.validated_data['mobile'], serializer.validated_data['due_date']]) ) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) and this is my task: logger = get_task_logger(__name__) @celery_app.task(name="apps.insurance.tasks.send_message_insurance_reminder") def send_message_insurance_reminder(title, mobile, due_date): logger.info('send message insurance reminder') # return send_reminder_message(title, mobile, due_date) return f'{title} _ {mobile} _ {due_date}' What is the correct way to create a periodic task and execute the task at the date that the user enters? Thanks. -
ERROR: Encountered errors while bringing up the project. DJANGO Docker
Successfully built 112f09badeb6 Successfully tagged be-django-nw_nginx:latest be-django-nw_db_1 is up-to-date Recreating cb0d468ab8a2_be-django-nw_web_1 ... error ERROR: for cb0d468ab8a2_be-django-nw_web_1 Cannot start service web: failed to create shim: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/opt/BE-Django-Nw/.env" to rootfs at "/backendPeti/backendPeti/.env": mount /opt/BE-Django-Nw/.env:/backendPeti/backendPeti/.env (via /proc/self/fd/6), flags: 0x5000: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type ERROR: for web Cannot start service web: failed to create shim: OCI runtime create failed: runc create failed: unable to start container process: error during container init: error mounting "/opt/BE-Django-Nw/.env" to rootfs at "/backendPeti/backendPeti/.env": mount /opt/BE-Django-Nw/.env:/backendPeti/backendPeti/.env (via /proc/self/fd/6), flags: 0x5000: not a directory: unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type ERROR: Encountered errors while bringing up the project. i try docker image prune, docker system prune and i remove .env and i make it again but doesnt work. what should i do?? -
Int object is not callable in the code ${{order.get_cart_total}}
I have the following code in the model, while calling the get_cart_total int not callable or unsupported operand type(s) for +: 'int' and 'method'appaers I am expecting to get total from get_cart_total class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total @property def get_cart_total(self): items = self.get_cart_items() for item in items: total += item.get_total() return total class OrderItem(models.Model): ORDER_ITEM_TYPE = ( ('type1', 'Collection1'), ('type2', 'Collection2'), ) order = models.ForeignKey(Order, on_delete=models.CASCADE) collection_type = models.CharField(max_length=255, choices=ORDER_ITEM_TYPE) collection1 = models.ForeignKey(Collection1, on_delete=models.SET_NULL, null=True, blank=True) collection2 = models.ForeignKey(Collection2, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField() def get_total(self): if self.collection_type == "type1": return self.collection1.price * self.quantity elif self.collection_type == "type2": return self.collection2.price * self.quantity -
Is there a way to isolate a foreign key from its related model using django?
I am building a django website that displays the prices of items in a shop. Each item belongs to a category so I mande category a foreign key that can have one or more items. `class Category(models.Model): category = models.CharField(max_length=64) def __str__(self): return self.category class ShopItem(models.Model): itemName = models.CharField(max_length=64) price = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.itemName` However, in the html, I am unable to obtain both the category and the shop item I tried the following... `---snip--- {% used_category = [] %} {% for item in shopitem_list %} {% if item.category not in used_category %} <tr> <td>item.category</td> <td></td> <td></td> </tr> <tr> {% for rel_item in shopitem_list %} {% if rel_item.category == item.category %} <td></td> <td>rel_item.itemName</td> <td>rel_item.category</td> {% endif %} {% enfor %} </tr> {% endif %} {% endfor %}` I was hoping this would help me create a table where all the items are sorted below their respective categories but I got an error instead: TemplateSyntaxError at / Invalid block tag on line 18: 'used_category', expected 'endblock'. Did you forget to register or load this tag? -
Upload file into a model that contains foreignkeys
I have successfully created a template, view and path that allows users to upload data from a csv file directly into a model. I'm experiencing issues however with a model that contains a foreignkey. I was expecting this to be a problem but am sure there's a workaround. So I have a model called VendorItem: class VendorItem(models.Model): sku = models.CharField("SKU", max_length=32, blank=True, null=True) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, verbose_name="Vendor name", related_name="vendor") vendor_sku = models.CharField("Vendor's SKU", max_length=32) model = models.CharField("Model number", max_length=32, blank=True, null=True) description = models.CharField("Description", max_length=64, blank=True, null=True) pq = models.DecimalField('Pack quantity', max_digits=7, decimal_places=2, default=1) price = models.DecimalField("Price", max_digits=10, decimal_places=2) upc = models.IntegerField("UPC", blank=True, null=True) # 12-digit numeric barcode ian = models.CharField("IAN", max_length=13, blank=True, null=True) # 13-digit alphanumeric international barcode status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=1) # Model metadata class Meta: unique_together = ["sku", "vendor"] unique_together = ["sku", "vendor_sku"] verbose_name_plural = "Vendor items" # Display below in admin def __str__(self): return f"{self.vendor_sku}" The vendor field is retrieved from the Vendor model (which is from another app might I add): class Vendor(models.Model): number = models.IntegerField("Vendor number", unique=True, blank=True, null=True) name = models.CharField("Vendor name", max_length=64, unique=True) region = models.CharField("Vendor region", max_length=64, blank=True, null=True) status = models.CharField(max_length=20, choices=VENDORSTATUS_CHOICES, default=1) # Display below in admin … -
Django reset password error from django.auth 'TypeError at /password_reset/'
I override default django reset password html and i want to send instruction to user email When im trying to send instruction to registered user email i have an error "path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not NoneType" setting.py EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" EMAIL_HOST = 'tech.unica-eng.ru' <- thats my company smtp server but i tried mail.ru smtp server and still not working EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_mail@tech.unica-eng.ru' EMAIL_HOST_PASSWORD = 'my_password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False SERVER_EMAIL = 'tech.unica-eng.ru' -
how to add new language in django 3
I want to add new language. it is turkmen (tm) I spent a lot of time but I can't resolve it please help me to resolve it PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) gettext = lambda s:s LANGUAGES = ( ('ru', gettext('Russia')), ('tm', gettext('Turkmen')), ) EXTRA_LANG_INFO = { 'tm': { 'bidi': False, 'code': 'tm', 'name': 'Turkmen', 'name_local': u"Turkmence", }, } import django.conf.locale from django.conf import global_settings import django.conf.locale LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO global_settings.LANGUAGES = global_settings.LANGUAGES + [("tm", 'Turkmenche')] -
why would you separate a celery worker and django container?
I am building a django app with celery. I tried composing a docker-compose without a container for the worker. In my Dockerfile for django, an entrypoint running the celery worker and django app: ... python manage.py migrate celery -A api worker -l INFO --detach python manage.py runserver 0.0.0.0:8000 The celery will run using this order but not django runserver. I have seen in tutorials that they separated the django container from woker container or vice-versa. I do not see the explanation for this separation. I also observed that the two python container (django, worker) has the same volume. How can celery add tasks if it has a different environment with django? In my mind there would be two django apps (the same volume) for two containers only 1 running the runserver, and the other one running the celery worker. I do not understand the separation. -
How to raise 404 as a status code in Serializer Validate function in DRF?
I have written a validate() function inside my serializer. By default, Serializer Errors return 400 as a status code. But I want to return 404. I tried this: class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass fields = "__all__" def validate(self, data): current_user = self.context.get("request").user user = data.get("user") if user!=current_user: raise ValidationError({'detail': 'Not found.'}, code=404) return data But it still returns 400 as a response in status code. How to do it? -
Keep getting 404 on some URLs
Having followed the guide to setup django, postgres and nginx in digitalocean, am get different results for different urls. Am using ubuntu 20 and python 3.10 <IP>:8000 => is working perfectly well <IP> => 404 Not Found <https://DomainName> => Showing the html page but Not showing the static files <https://www.DomainName> => 404 Not Found Where am I messing up?? -
The 'image' attribute has no file associated with it django
I am doing an ecommerce project for deployment in pythonanywhere.com, some error is coming I would really appreciate if any one could help me to find out the problem as I am a basic learner TIA I have two MySQL tables and i tried to add more records error -
Send data from list application to create new customer django
I have a problem, I would like to transfer the appropriate field parameters from one list to the form for creating something else. The names of the fields match but they are not the same in both and I would like to send only those that are the same. Example - I have a list of requests and on this list I have a button next to each request to be able to immediately add a customer from this request and send the appropriate fields to this form. How i need to do that? I tried to work in templates and forms and views but I couldn't do it anywhere