Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OVERRIDING THE ORDER OF FIELDS IN SERIALIZER RESPONSE
class Meta: model = Order fields = ( 'brand', 'currency', 'order_id', 'reference_id', 'ordered_date', 'amount', 'quantity', 'order_status', 'app_code', 'vouchers') I need to change the ordering of field's on response. I have changed the ordering in class Meta. its not working i have tried to_representation method. -
Djang - 404 Error occurs only at specific time
I'm running my Django project in a docker container on AWS EC2 instance. There are some APIs and all of them have been working fine for several months. But since last week, APIs return 404 error only around 6pm everyday. <head><title>404 Not Found</title></head> <body> <center><h1>404 Not Found</h1></center> <hr><center>openresty/1.19.9.1</center> </body> </html> Is there any way to solve this error? Any comments would be appreciated. -
costum variable index inside a DJango template
I have a template in Django that is generated by a for loop like {% for test in test_list %} <!-- dome code here --> {% if not test.testInPausa %} <div class="progress-wrapper-{{ forloop.counter0 }}"> <div id="progress-bar-{{ forloop.counter0 }}" class="progress-bar-{{ forloop.counter0 }} progress-bar-striped" > &nbsp; </div> </div> <div id="progress-bar-message-{{ forloop.counter0 }}"> Waiting for progress to start... </div> {% endif %} {% endfor %} Now, I would like to count the time in which the code enter the if statement. I want to do so because, at the moment, the id and class inside the div are indexed by the forloop.counter, which, because it doesn't always enter the if statement, counts every for loop making the id and class jump index. Is there a way to have something {% for test in test_list %} {% my_index = 0 %} <!-- dome code here --> {% if not test.testInPausa %} <div class="progress-wrapper-{{ my_index }}"> <div id="progress-bar-{{ my_index }}" class="progress-bar-{{ my_index }} progress-bar-striped" > &nbsp; </div> </div> <div id="progress-bar-message-{{ my_index }}"> Waiting for progress to start... </div> {% my_index++ %} {% endif %} {% endfor %} -
Read data from dynamic table Django
I have automated batch processn creates tables in sqlite DB and update the table in one of the table defined by Django ORM. I would like to use Django ORM to select data from newly created DB. -
Charts not loading out data for my django project
So, I've been trying to get my charts to display packages created per hour, but it doesn't render out the data on the chart. The axes display though. When I use print statements in the view, it returns an empty array for the hours, despite the same code working for a different project def warehouse_dashboard(request): user = request.user if user.role == 'warehouse_admin': warehouse = user.warehouse_admin_field if warehouse: buses = Bus.objects.filter(warehouse=warehouse) # Filter items that are either assigned to a bus or have a delivery status of "Ready" packages_coming = Item.objects.filter( Q(station_to=warehouse, bus_number_plate__isnull=False) | Q(station_to=warehouse, delivery_status='Ready') ).exclude(delivery_status__in=['Canceled', 'Received', 'Ready']) packages_leaving = Item.objects.filter(station_from=warehouse).exclude(delivery_status='Canceled') packages_by_bus = {} for bus in buses: packages_from = Item.objects.filter( Q(station_from=warehouse) | Q(station_to=warehouse), bus_number_plate=bus ).exclude(delivery_status='Canceled') packages_by_bus[bus] = packages_from bus_count = buses.count() packages_count_coming = packages_coming.count() packages_count_leaving = packages_leaving.count() # Retrieve data for the graph (daily packages added) # Get the datetime for the start of the current day current_day_start = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) hourly_totals = Item.objects.filter( station_from=warehouse, creation_date__gte=current_day_start ).annotate(hour=ExtractHour('creation_date')).values('hour').annotate(total=Count('id')).order_by('hour') # Initialize an array to hold the data for each hour of the day chart_data = [0] * 24 for total in hourly_totals: hour = total['hour'] if hour is not None: chart_data[hour] = total['total'] print(chart_data[hour]) # Get the number of … -
Permission denied for ..../<id>/ CRUD ModelViewSet endpoints
I am trying to create a ModelViewSet for supporting CRUD operations on my address model. I am able to successfully use LIST and CREATE endpoints, but all the other 4 endpoints which require/id/ in their URL return me the error - { "detail": "You do not have permission to perform this action." } The address model should support the operations only by the Users who are marked NOT SELLER in the DB, hence the ~IsSeller custom permission is applied. The issue goes away when I remove this custom permission from permissions classes, but i need to keep this restriction of only non-seller users to be able to add the address. permissions.py from rest_framework.permissions import BasePermission class IsSeller(BasePermission): def has_permission(self, request, view): return (request.user and request.user.is_seller) Views.py class ManageAddressViewSet(viewsets.ModelViewSet): serializer_class = AddressSerializer permission_classes = [permissions.IsAuthenticated, (~IsSeller)] queryset = Address.objects.all() def get_queryset(self): return self.queryset.filter(user=self.request.user) def perform_create(self, serializer): return serializer.save(user=self.request.user) Serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = [ 'id', 'name', 'line_1', 'line_2', 'city', 'state', 'pincode', 'type' ] read_only_fields = ['id'] urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from user import views router = DefaultRouter() router.register('address', views.ManageAddressViewSet) urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('authenticate/', views.CreateTokenView.as_view(), name='authenticate'), path('my-profile/', views.ManageUserView.as_view(), … -
How to deploy my Django project into plesk server and run it , give me a step by step process please
I need to know how deploy my project into plesk , i never done this before. I search in Youtube but i can't fine a video for it . chat gpt also not give a clear steps i have a plesk panel credentials and i verify the python installed or not , it instaled and pip also there i created a virtual environment too , i upload the django folder to plesk server, i don't know what to do next, the problem is i want to upload my django project to pleask that i don't know -
Unable to get the date from tempusdominus bootstrap4 plugin to Django form
Here is my html code. <div class="col-md-3"> <label> Approved Date:</label> <div class="input-group date" id="{{ form.ApprovedDate.id_for_label }}" data-target-input="nearest"> <input type="text" class="form-control datetimepicker-input" id="{{ form.ApprovedDate.id_for_label }}" name="{{ form.ApprovedDate.id_for_label }}" data-target="#{{ form.ApprovedDate.id_for_label }}"/> <div class="input-group-append" data-target="#{{ form.ApprovedDate.id_for_label }}" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> </div> and here is the Script Jquery <script> $(function () { $('#{{ form.ApprovedDate.id_for_label }}').datetimepicker({ format: 'DD-MM-YYYY' }); }) </script> My problem is that this field is not being passed to my django form which is of this code. class ProjectForm(forms.ModelForm): #views.py class Meta: model = Project fields = '__all__' def save(self, commit=True): instance = super().save(commit=False) instance.created_on = timezone.now() # Import timezone if not already imported instance.createdBy = 0 if commit: instance.save() return instance def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) I simply want to read value of this field so the same can be saved to db. by this code in views.py def create_project(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() # Save to the database with the modified fields return redirect('projects:project_list') # Redirect to the list view else: form = ProjectForm() return render(request, 'create_project.html', {'form': form}) I have tried many solutions like importing tempusdominus package but I … -
python setup.py egg_info did not run successfully : when trying to install psycopg2
I am facing this issue when trying to run psycopg2, any one with solution would be helpful, thanx! Collecting psycopg2==2.8.6 (from -r requirements.txt (line 45)) Using cached psycopg2-2.8.6.tar.gz (383 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [37 lines of output] running egg_info creating /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info writing /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-kg2ft5p1/psycopg2.egg-info/SOURCES.txt' /home/lungsang/Desktop/Contextus/env/lib/python3.8/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg` !! parsed = self.parsers.get(option_name, lambda x: x)(value) Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed This error appears when i try to run psycopg2 and I upgraded setuptools, still not solved. -
copy to clipboard not working with django and js
Hi guys I created a basic copy to clipboard functionality using django and js, everything seems to be ok but when i try to copy my info i get this error This is the piece of code where I'm doing everything <table class="init-datatable display"> <thead> <tr> <th>Company</th> <th>Avt User Name</th> <th>Full Name</th> <th class="email-column">Email Address</th> <th>Expiration Date</th> <th>Avt Version</th> <th>License</th> <th>Generated User</th> <th>Copy information</th> </tr> </thead> <tbody> {% for item in object_list %} <tr> <td class="th-width">{{ item.user.company.name }}</td> <td class="th-width">{{ item.user.user_name }}</td> <td class="th-width">{{ item.user.full_name }}</td> <td class="th-width email-column">{{ item.user.email }}</td> <td class="th-width">{{ item.expire_date }}</td> <td class="th-width">{{ item.avt_version}}</td> <td class="th-width">{{ item.license_avt }}</td> <td class="th-width">{{ item.generated_user.username }}</td> <td class="th-width"> <button class="control button copy-btn btn" company-name="{{item.user.company.name}}" user-name="{{item.user.user_name}}" full-name="{{item.user.full_name}}" email="{{item.user.email}}" expire-date="{{item.expire_date}}">Copy information</button> </td> </tr> {% endfor %} </tbody> </table> <script> const copyBtns = [...document.getElementsByClassName("copy-btn")] copyBtns.forEach(btn => btn.addEventListener('click', ()=>{ const companyName = btn.getAttribute("company-name") const userName = btn.getAttribute("user-name") const fullName = btn.getAttribute("full-name") const email = btn.getAttribute("email") const expireDate = btn.getAttribute("expire-date") console.log(companyName) console.log(userName) console.log(fullName) console.log(email) console.log(expireDate) btn.textContent = "Copied" setTimeout(() => { btn.textContent = "Copy information" }, "1350"); navigator.clipboard.writeText(companyName) })) </script> If someone can tell me how to fix this or another way to tackle this feature of copying stuff from the HTML it would be … -
How to implement ForeignKey search in Django REST framework
When developing the API, I tried to implement a search system but encountered an error Unsupported lookup 'icontains' for ForeignKey or join on the field not permitted. Models class GroupTask(models.Model): UserToken = models.TextField(default="") NameGroupTask = models.TextField(null=True) StatusGroupTask= models.BooleanField(default=False) class Meta: ordering = ['NameGroupTask'] def __str__(self): return self.NameGroupTask[0:50] class TaskForGroup(models.Model): UserToken = models.TextField(default="") NameTaskForGroup= models.TextField(null=True) DescriptionTask = models.TextField(null=True) StatusTaskForGroup= models.BooleanField(default=False) Group = models.ForeignKey(GroupTask, on_delete = models.CASCADE) class Meta: ordering = ['NameTaskForGroup'] def __str__(self): return self.NameTaskForGroup[0:50] viewsets for output class TaskForGroupAPI(viewsets.ModelViewSet): # показываем что доступны все методы для работы с данными (post, get, put, delete запросы) queryset= TaskForGroup.objects.all() # указываем сериализатор serializer_class = TaskForGroupSerializer # устанавливаем классы для фильтрации filter_backends = (DjangoFilterBackend, SearchFilter) # указываем поле по которому проводить фильтрацию search_fields = ['Group',] def get_paginated_response(self, data): return Response(data) how am I trying to find the TaskForGroup I need http://127.0.0.1:8000/TaskForGroupAPI/TaskForGroupAPI/?search=5 -
Ajax Request is returning error with log: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
I have a Django application where I have an html page with two forms that I want to be submitted with two different ajax requests. The first request works perfectly fine, but for some reason the second request results in an error response I'm printing out to the console like this: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} abort : ƒ (a) always : ƒ () complete : ƒ () done : ƒ () error : ƒ () fail : ƒ () getAllResponseHeaders : ƒ () getResponseHeader : ƒ (a) overrideMimeType : ƒ (a) pipe : ƒ () progress : ƒ () promise : ƒ (a) readyState : 4 responseText : "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n setRequestHeader : ƒ (a,b) state : ƒ () status : 200 statusCode : ƒ (a) statusText : "OK" success : ƒ () then : ƒ () [[Prototype]] : Object I have no clue how to debug this... The first ajax request is just to partially fill the second form. The second form is a Model Form that is supposed to add an instance off my model in my view. View: def canadaTaxEntries(request): newest_record = LAWCHG.objects.aggregate(Max('control_number')) newest_control_number = newest_record["control_number__max"] print(newest_control_number) today = date.today().strftime("1%y%m%d") … -
How get Nearby place information's like school, hospital, malls and cinema hall in django
I am creating a real estate rental project and in that I want to show a property and nearby places to that particular property to the users using latitude and longitude of the property. I have no idea how to do that, so can you please tell all steps including what required files I need to install as well. Please show me complete guide with code. -
Why is DRF's router selectively not redirecting to a trailing slash?
Desired behavior For router endpoints to append a trailing slash if one is not provided. E.g. /api/customers would redirect to /api/customers/ Actual behavior A 404 is returned if a trailing slash isn't applied to the endpoint. E.g. /api/customers return a 404 response Additional context APPEND_SLASH is set to True CommonMiddleware is set The trailing slash works on non-DRF endpoints. E.g. /admin redirects to /admin/ The trailing slash works on one set of ViewSet endpoints. The user ViewSet works. E.g. /users redirects to /users/ The user app is the last app in the project alphabetically. None of the other ViewSets registered redirect to the trailing slash. Code project_name/urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework import routers from user.views import UserViewSet, LoginView, logout_view from customer.views import CustomerViewSet from intake.views import IntakeViewSet from extraction.views import ExtractionViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='users') router.register(r'customers', CustomerViewSet, basename='customers') router.register(r'intakes', IntakeViewSet, basename='intakes') router.register(r'extractions', ExtractionViewSet, basename='extractions') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('api/login/', LoginView.as_view()), path('api/logout/', logout_view), ] if settings.DEBUG: # Add dev static files urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Add debug toolbar patterns urlpatterns.append(path('__debug__/', include('debug_toolbar.urls'))) TLDR Only one set of endpoints registered to DRF's … -
How to manage List an Dict in Django views and Template?
When I iterate through a Query in Django my Dict only update the last item. Does anyone knows how to add all Query data on it. It is wierd because if I create a list with the same Query it does get all data (as you can see just bellow vendor number 5 has two opening_hours ins List but not in Dict): Query with a Dict: dict_today_open_hour = {} for t in v.today_opening_hours: dict_today_open_hour.update({t.vendor.id:{'today_from_hour': t.from_hour, 'today_to_hour': t.to_hour,}}) The Dict result is: {1: {'today_from_hour': '07:00', 'today_to_hour': '20:00'}, 5: {'today_from_hour': '22:00', 'today_to_hour': '23:00'}} Same Query with a List: list_today_open_hour = [] for t in v.today_opening_hours: list_today_open_hour.append({t.vendor.id:{'today_from_hour': t.from_hour, 'today_to_hour': t.to_hour,}}) List result: [{1: {'today_from_hour': '07:00', 'today_to_hour': '20:00'}}, {5: {'today_from_hour': '09:00', 'today_to_hour': '19:00'}}, {5: {'today_from_hour': '22:00', 'today_to_hour': '23:00'}}] As you can see in the List result I got all data from the Query but in the Dict result I only get the last item from vendor id number 5. Does anyone knows if it is possible: 1-) Get all data in the Dict Query like the data i got from List? If so how to do it? 2-) Is it possible to user the Query List Result in template and filter it with the … -
adding field to django user model - how to automatically create object instance?
I am attempting to add a field 'balance' to the default django user model, and i've done so with this code: class UserBalance(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) but my problem is that when I create a new user, I need to manually add a value for the balance in the django admin console otherwise I can't use it in html template tags, whereas I want it to just automatically be created and added as 0 to the user's profile once they create it. What is the easiest way to do this? User account that I manually added balance via admin console User account freshly created -
setting en-US.UTF-8 in pycharm until the end of times
I am having hell with the compilemessages in Django translation as every time I write that function it complains of the following: UnicodeEncodeError: 'latin-1' codec can't encode character '\u201c' in position 5: ordinal not in range(256) investigating on the matter I went in my terminal (inside my venv) python import locale locale.getdefaultlocale() and I was furious to be slapped with this: ('en_US', 'ISO8859-1') which means: ISO/IEC 8859-1 encodes what it refers to as "Latin alphabet no. 1", so, I went: locale.setlocale((locale.LC_ALL, 'en_US.UTF-8') and then verified again that it had changed to UTF-8 and it had. So, I opened another terminal (as I didn't want to close the python shell) and tried compilemessages and I got the same error because the default ISO8859-1 was still there. I went to the Pycharm settings and changed the interpreter to python 3.11 however, when I opened a python shell, it continued showing 3.9 Naturally this is driving me insane because it just bulks at whatever I say. To make matters worse, while I always get this long set of errors File "/home/alvaralexandrovich/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/alvaralexandrovich/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alvaralexandrovich/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/alvaralexandrovich/PycharmProjects/Carpeta9Abril/venv9Abril/lib/python3.9/site-packages/django/core/management/base.py", … -
Why Amazon S3 not serve images on my Django blog?
I have a blog app wrote in Django and deployed with Heroku. Now I want to keep the images that the users upload with the blog post and I have a default image if the user don't want a specific picture. When I used whitenoise the pictures were there, but after a logout, login they were disappeared and the default were there only. I tried set up an s3 storage to keep all the images, but now all images are gone. I don't know if I should delete whitenoise from middlewares. I changed the media and the statics url too to the s3 bucket. Here is the source of the page, the files are in the s3 storage theoreticaly But when I click one of the images link, I got an access denied: I have a favicon, a css and a javascript in the statics and they are working, so I think the setting of the s3 storage is ok and the problem is image format specific. When I execute collectstatic, it said that it uploaded the files to tmp. Is it ok? Here is my s3 bucket: I tried to manually upload my static folder, but did not serve … -
Why do I get "Failed to load PDF document" when I try to open a modified PDF?
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. I relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I get "Error Failed to load PDF document" in my browser. Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage import docx from pdf2docx import parse from docx2pdf import convert import time #remove # Create your views here. @csrf_protect def translateFile(request) : file = '' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path)) response = HttpResponse(file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response else: form = UploadFileForm() return render(request, 'translator_upload/upload.html', {'form': form}) def reConverter(inputDocxPath): return convert(inputDocxPath) def translateDocx(aDocx, stringOfDocPath): docx_file = stringOfDocPath myDoc = docx.Document(docx_file) #translation logic myDoc.save(stringOfDocPath) return reConverter(stringOfDocPath) #stringOfDocPath is used as convert() requires file path, not file object(myDoc) def converter(inputPdfPath): # convert pdf to docx pdf_file = inputPdfPath docx_file = inputPdfPath + '.docx' … -
Django - ModelForm does not update on form submission
I have a form for when a user makes a form submission an object with a bunch of fields are supposed to get updated in my application. Currently, when a user makes a form submission with this form a new object gets made and I don’t know why. I receive an error that says “get() returned more than one User_Info -- it returned 2!” How do my I make my current form on the myaccount_edit.html page update the object correctly with my current code? The fields that get updated in the object are based on the logged in user. I've tried many things but I'm kinda lost. The form is located on myaccount_edit.html. Where the form data display is on myaccount.html. That data displays correctly when there isn't an error. Screenshot attached. Any help is gladly appreciated. Thanks! Views: def account_view_myaccount(request): if request.user.is_authenticated: user_profile = User_Info.objects.filter(user=request.user) context = { 'user_profile': user_profile } return render(request, "myaccount.html", context) def account_view_myaccount_edit(request): form = HomeForm(request.POST or None, request.FILES or None) user_profile = User_Info.objects.filter(user=request.user) obj, created = User_Info.objects.update_or_create(user=request.user) user = request.user if request.method == "POST": # checking if request is POST or Not # if its a post request, then its checking if the form … -
Django can't update a related model field based on another model field in Django
Hello everyone I'm trying to update one of the table CashAdmin from fields cash_user based on my table PickUp based on fields is_finished and user as the foreign Key. But for some reason is not working. This is the code: Model of PickUp model.py from gc import is_finalized from django.db import models from django.contrib.auth.models import User class PickUp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_finished = models.BooleanField (default=False) quantity = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) Model of CashAdmin model.py from django.db import models from django.contrib import auth from django.contrib.auth.models import User class CashAdmin(models.Model): cash_user = models.FloatField() user = models.ForeignKey('auth.User', on_delete=models.CASCADE) The is the views file for PickUp. views.py from multiprocessing import context from django.shortcuts import render, redirect, HttpResponse from pickup.forms import CreatePenjemputanForm from pickup.models import PickUp from cash.models import CashADmin from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.core import serializers from django.contrib.auth.decorators import login_required from django.contrib import messages import datetime from django.views.decorators.csrf import csrf_exempt from PickUp.decorators import admin_only # Create your views here. def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' @admin_only def update_pickup(request, id): pick_up = PickUp.objects.get(pk=id) if pick_up.is_finished: pick_up.is_finished = False else: pickup.is_finished = True cash_user = pickup.quantity * 12500 if pick_up.is_finished else cash_user cash_admin, created = CashAdmin.objects.get_or_create(user=pick_up.user) cash_admin.cash_user = cash_admin.cash_user + … -
Can't save field with Djongo and AutoField
This Model generate id_num: class Docahdl(models.Model): id_num = models.AutoField(primary_key=True) data_alter_doca = models.CharField(max_length=20) data_input = models.CharField(max_length=16) handling = models.IntegerField() doca_id = models.CharField(max_length=20) user_id = models.CharField(max_length=80) def __str__(self): return str(self.id_num) But this don't generate id_num: class SlaCD(models.Model): id_num = models.AutoField(primary_key=True) negocio = models.CharField(max_length=10) tipo_sla = models.CharField(max_length=50) data_inicio = models.DateTimeField() data_fim = models.DateTimeField() quantidade = models.FloatField() umd = models.CharField(max_length=10) def __str__(self): return str(self.id_num) Can't have two or more AutoField using Djongo? When I create a instance and save Docahdl save the id_num on MongoDB, but SlaCD not. -
run a docker-compose from crontab
I have a command docker-compose -f docker-compose-deploy.yml run --rm app sh -c "python manage.py runcrons" that works if I run it from terminal. Now I want to run this command from a crontab but I am a bit at a loss of how I should write this. I have tried a bunch of things based on things I have found here: */5 * * * * cd /home/ec2-user/legend-of-solgard; docker-compose -f docker-compose-deploy.yml run --rm app sh -c "python manage runcrons” */5 * * * * /usr/bin/docker-compose -f /home/ec2-user/legend-of-solgard/docker-compose-deploy.yml exec -T app run --rm app sh -c "python manage runcrons” But nothing works. -
why docker raises 'chunked'Error while fetching server API version: HTTPConnection.request() got an unexpected keyword argument 'chunked'?
I have been trying to build a docker service which would run django. but keep getting docker.errors.DockerException: Error while fetching server API version: HTTPConnection.request() got an unexpected keyword argument 'chunked' Dockerfile FROM python:3.7-alpine USER root ENV pythonunbuffered 1 RUN mkdir app COPY ./new /app COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt WORKDIR /app RUN adduser -D user USER user cmd ['python','manage.py','runserver'] docker-compose version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - "./src:/app" command: > sh -c "python manage.py runserver 0.0.0.0:8000" Is there a connection error?why does this keep happening? -
com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None)
I am new to web development and trying to create a language translation app in Django that translates uploaded documents. It relies on a series of interconversions between pdf and docx. When my code ouputs the downloaded translated document I sometimes get a com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None). Here is the full error message: Exception Location: C:\Users\John\tutorial-env\Lib\site-packages\win32com\client\dynamic.py, line 86, in _GetGoodDispatch Raised during: translator_upload.views.translateFile Python Executable: C:\Users\John\tutorial-env\Scripts\python.exe Python Version: 3.11.4 Python Path: ['C:\\djangoProjects\\mysite', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\John\\tutorial-env', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32\\lib', 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\Pythonwin'] Here is my code: from django.shortcuts import render from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranslatedDocument from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage import docx from pdf2docx import parse from docx2pdf import convert import time #remove # Create your views here. @csrf_protect def translateFile(request) : file = '' if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path)) response = HttpResponse(file, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response else: form = UploadFileForm() return render(request, 'translator_upload/upload.html', {'form': form}) def reConverter(inputDocxPath): return convert(inputDocxPath) def translateDocx(aDocx, …