Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django autocomplete-light with model's foreignkey shows select box not a textbox
I want to upload files in my server using POST method but when I make a form there are something problem. My problem is I want to make autocomplete but web shows only select box. Even there is no select options.(when I used it without autocomplete-light library I can choose options in uuids) even I followed autocomplete-light library official docs. The codes are my django code views, template, forms, models, urls #views.py class Auto_uuid(autocomplete.Select2QuerySetView): auto_class = Uuid def get_queryset(self): if not self.request.user.is_authenticated: return self.auto_class.objects.none() qs = self.auto_class.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class Class_stat(generic.View): form_class = StatForm def get(self, request): form = self.form_class() return render(request, "myapp/stat_input.html", {'form':form}) def post(self, request): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("myapp:home") return render(request, "myapp/stat_input.html", {'form':form}) #template stat_input.html {%extends 'base.html' %} {% block content %} <h2>Upload raw data</h2> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> {{form.uuid}} </div> <div> {{form.as_p}} </div> <button type="submit" class="btn btn-primary">upload</button> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% endblock %} #forms.py class StatForm(forms.ModelForm): class Meta: model = Stat_file fields = '__all__' widgets = { 'uuid': autocomplete.ModelSelect2(url="myapp:auto") } #models.py class Stat_file(models.Model): uuid = models.ForeignKey(Uuid, on_delete=models.CASCADE, default=None) myfile = models.FileField(upload_to=user_stat_directory_path,max_length=400) cellline = models.CharField(max_length=100, default=None) cohort = models.ForeignKey(Cohort, on_delete=models.CASCADE) perttype = models.ForeignKey(PertType, on_delete=models.CASCADE) class … -
How to create two databases in django app with docker-compose
I connect can to my pgadmin with db1 but impossible to connect in with db2. I got this error Unable to conect to server: ... (see picture). I have seen some post but none of them resolve my problem. version: "3.9" services: web: build: context: . dockerfile: ./Dockerfile entrypoint: /code/docker-entrypoint.sh restart: unless-stopped ports: - "8000:8000" depends_on: - db1 - db2 volumes: - .:/code db1: container_name: database1 image: postgres:14.4 restart: unless-stopped ports: - "5432:5432" environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres db2: container_name: database2 image: postgres:14.4 restart: unless-stopped ports: - "5433:5433" environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres pgadmin: container_name: pgadmin image: dpage/pgadmin4:6.20 restart: unless-stopped environment: PGADMIN_DEFAULT_EMAIL: admin@admin.com PGADMIN_DEFAULT_PASSWORD: admin PGADMIN_CONFIG_SERVER_MODE: 'False' volumes: - ./pgadmin:/var/lib/pgadmin ports: - '8001:80' depends_on: - db1 - db2 - web -
Not able to run selenium in headless mode on linux server
Error: Message: unknown error: Chrome failed to start: exited abnormally. (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) Description: I'm following this post and official document to install and setup Selenium in headless mode on my server. When I run it locally on my server, it works, but when I access it after setting up Nginx and a Service file for my Django site, it gives me the above error. After looking at several answers, I checked these points, and they exist in my project or in my system. google chrome browser (version - 111) selenium installed chrome driver (version - 111) added chrome driver in $PATH above points I've added if I'm missing somthing or any other information required please let me know. -
Error: PROJ: proj_create: unrecognized format / unknown name
I have installed Terria JS and Cartoview. when i upload layers in Cartoview then they are uploaded but the following errors come: Error Message: PROJ: proj_create_from_database: SQLite error on SELECT name, type, coordinate_system_auth_name, coordinate_system_code, datum_auth_name, datum_code, area_of_use_auth_name, area_of_use_code, text_definition, deprecated FROM geodetic_crs WHERE auth_name = ? AND code = ?: no such column: area_of_use_auth_name Error Message: PROJ: proj_create: unrecognized format / unknown name Error Message: Cannot find coordinate operations from ' to '> I installed gdal error handler and then was successful to get these error messages. can anyone kindly tell why they are coming? I have also heard that these errors are due to PROJ library. Please have a look. Thanks! -
Django admin inlines from second model when first model child has OneToOne relationship with other second model
Admin.py has GroupAdmin and GroupItemsInline but also want an extra inline with OrderItems groupped by item and total item_qty calculation as above. It could be possible add extra inline with aggregates from OrderItems In GroupAdmin? models.py from django.db import models #Order class Order(models.Model): order_num = models.CharField(null=True, max_length=10, unique=True) def __str__(self): return self.order_num #contains the detail of an order class OrderItems(models.Model): parent_order = models.ForeignKey(Order, on_delete=models.CASCADE) item = models.CharField(null=True, max_length=32) item_qty=models.IntegerField(null=True) def __str__(self): return self.item +' '+ str(self.item_qty) #Allow grouping orders into a group class Group(models.Model): group_num = models.CharField(null=False, unique=True, max_length=10) def __str__(self): return self.group_num #Contains the orders grouped in a group #related with Group via ForeignKey #related with Order via OneToOneField class GroupItems(models.Model): parent_group = models.ForeignKey(Group, on_delete=models.CASCADE) grouped_order = models.OneToOneField(Order,on_delete=models.CASCADE) def __str__(self): return self.grouped_order` **admin.py** `from django.contrib import admin from .models import Order, OrderItems, Group, GroupItems class OrderItemsInline(admin.TabularInline): model = OrderItems class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemsInline] class GroupItemsInline(admin.TabularInline): model = GroupItems class GroupAdmin(admin.ModelAdmin): inlines = [GroupItemsInline] admin.site.register(Order, OrderAdmin) admin.site.register(Group, GroupAdmin) admin.py from django.contrib import admin from .models import Order, OrderItems, Group, GroupItems class OrderItemsInline(admin.TabularInline): model = OrderItems class OrderAdmin(admin.ModelAdmin): inlines = [OrderItemsInline] class GroupItemsInline(admin.TabularInline): model = GroupItems class GroupAdmin(admin.ModelAdmin): inlines = [GroupItemsInline] admin.site.register(Order, OrderAdmin) admin.site.register(Group, GroupAdmin) Can access OrderItems data related … -
How to filter query objects by date range in DRF?
I have simple model: models.py class Report(models.Model): title = models.CharField(max_length=250) created_date = models.DateField() Created filters.py file and using django-filters package wrote FilterSet: from .models import Report class ReportFilter(django_filters.FilterSet): created_date = django_filters.DateFromToRangeFilter() class Meta: model = Report fields = ['created_date'] Simple views.py: from .filters import ReportFilter from .models import Report def Reports(request): reports = Report.objects.all() myFilter = ReportFilter(request.GET, queryset=reports) reports = myFilter.qs return render(request, 'dashboard/index.html', {'reports': reports, 'myFilter': myFilter}) And the last file index.html: {% block content %} <form method="get" style="display: block; width: 335px; margin: 20px auto;"> {{myFilter.form}} <button type="submit">Search</button> </form> {% if reports %} {% for report in reports %} <tr> <td> {{ report.title }} </td> <td> {{ report.created_date }} </td> </tr> {% endfor %} {% endif %} </table> {% endblock content %} Question in short: How to do it DRF? (beginner in DRF) What I tried so far: serializers.py from rest_framework import serializers from .models import Report class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report fields = '__all__' views.py from .filters import ReportFilter from .serializers import ReportSerializer from rest_framework import viewsets from django_filters.rest_framework import DjangoFilterBackend from .models import Report class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer filter_backends = [DjangoFilterBackend,] filterset_class = ReportFilter Did not change filters.py and added all … -
filter by parent field in django queryset
Hi i want to get all the items of a coffee shop by its slug . as it is clear it saves the pk not the slug in the model. Is there any way to get this instead of finding cafe pk and etc. i am searching for some thing like just one query for it. here is what i coded : url path( "<str:cafe_slug>/", ProfileList.as_view(), name="get_item_menu", ), in view def get(self, request,cafe_slug): queryset = Item.objects.filter(cafe__slug=cafe_slug) model class Item(models.Model): name = models.CharField(max_length=256, unique=True,) cafe = models.ForeignKey(CoffeeShop, on_delete=models.CASCADE) class CoffeeShop(models.Model): name = models.CharField(max_length=256, unique=True) slug = models.CharField(max_length=256, unique=True,) -
Complex filtering with Q() Django
I have models Order and User: class Order(Model): ... status = CharField(choices=STATUS, default=NEW, max_length=20) referral_user = ForeignKey("app.User", CASCADE, 'referal', blank=True, null=True) operator = ForeignKey("app.User", CASCADE,'operator', blank=True, null=True) class User(Model): ... orders_for_all_operators = BooleanField(default=True) operators = ManyToManyField("User", related_name="admins") I need to filter orders for operators like this: Status: New Operator: requested user or no operator. Order's referral_user: has the requested user in their operators field or orders_for_all_operators = True I've tried this code but it's not working: qs = queryset.filter(Q(Q(referral_user__in=self.request.user.admins.all()) | Q(user__orders_for_all_operators=True)) | Q(Q(operator=None) | Q(operator=self.request.user))) -
Error message when I run my Django server with sudo. "ImportError: Couldn't import Django..."
I have a Django server in our local environment that we run some scripts through. I wanted to get rid of having to run it with the portnumber attached to the IP when i run the web-app. So instead of running it with port 8000 i want to run it with 80. requirement.txt: asgiref==3.6.0 backports.zoneinfo==0.2.1 certifi==2022.12.7 charset-normalizer==3.0.1 Django==4.1.7 idna==3.4 oauthlib==3.2.2 requests==2.28.2 requests-oauthlib==1.3.1 sqlparse==0.4.3 urllib3==1.26.14 I found some sources (*) that said that i could run it with sudo to get rid of the initial: 'Error: You don't have permission to access that port.' message. (*)Django: Error: You don't have permission to access that port But when i run the command sudo python manage.py runserver 0.0.0.0:80 i get the error message: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> if __name__ == '__main__': main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The … -
django-celery with redis broker, new preiodic task not starting
I have a drf project and I use celery with redis broker. every thing working fine and run smoothly, but when I try to add a new preiodic task , I see it created, I see it in the celery beat but the task never run. I think the problem is with the redis because fushall will solve the problem. I don't want to do flushall every time I add a task. Any idea? someone ever had a similar problem? Thanks. -
Is making a separate table with product categories, even though I have separate tables for products, a good idea?
I don't know which database schema is better to use. The first one seems nicer to me, because I don't know if making separate tables for categories if our table is that category is a good idea. But the second one makes it easier to query the database. Unless other options are better, I will try all the advice. First: class Genre(models.Model): CATEGORY_CHOICES = (('book', 'Book'), ('cd', 'CD'), ('film', 'Film'),) name = models.CharField(max_length=100) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) def __str__(self): return str(self.name) + " " + str(self.category) class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=True) image = models.ImageField(upload_to='product', default=None) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) class CD(Product): band = models.CharField(max_length=100, null=False, blank=False) tracklist = models.TextField(max_length=500, null=False, blank=False) class Book(Product): author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) class Film(Product): director = models.CharField(max_length=100, null=False, blank=False) duration = models.IntegerField(null=False, blank=False) Second: class Product(PolymorphicModel): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) image = models.ImageField(upload_to='product', default=None) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) class CD(Product): GENRE_CHOICES = ( ('Rock', 'Rock'), ('Pop', 'Pop'), ('Reggae', 'Reggae'), ('Disco', 'Disco'), ('Rap', … -
Django 4.0 Dynamically adding a new form
I am trying to add a form to a new row in there own columns with a button then having all the forms saved with the submit button. Only the first form is being saved, I am assuming it is the javascript doing it but I have no clue with javascript and ChatGPT is not helping lol {% extends 'containers/base.html' %} {% block body %} <h3 class="m-4">All Containers</h3> <div class="row"> <div class="col-12"> {% if success %} <div class="alert alert-success" role="alert"> Container/s have been added successfully. <a href="{% url 'index' %}" class="alert-link">Go to Home Page.</a> </div> {% else %} <div class="card bg-light mb-3"> <div class="card-header">Add Containers</div> <div class="card-body"> <p class="card-text"> <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th scope="col">Company Name</th> <th scope="col">Container Number</th> <th scope="col">Driver In</th> <th scope="col">Date In</th> <th scope="col">Driver Out</th> <th scope="col">Date Out</th> <th scope="col">Container Size</th> <th scope="col">Empty/full</th> <th scope="col">Import/Export</th> </tr> </thead> <form action="{% url 'add' %}" method="POST"> {% for form in formset %} {% csrf_token %} {{ formset.management_form }} <tbody class="container-table-body" id="container-table-body"> <tr> <td> <div class="fieldWrapper"> {{ form.company_name }} </div> </td> <td> <div class="fieldWrapper"> {{ form.container_number }} </div> </td> <td> <div class="fieldWrapper"> {{ form.driver_in_name }} </div> </td> <td> <div class="fieldWrapper"> {{ form.driver_in_date }} </div> </td> <td> <div class="fieldWrapper"> … -
Admin not giving permission to newly registered user unless he/she is approved by him
Iam creating a school management website, there are three modules : admin,teacher and student. The registered teacher and student can only log into the website after admin approves them. For That here iam using a status field in both teacher and student model as intergerfield and setting its default value as 0. so after registration teacher and student have status 0 and when the admin approves them the status value changes to 1 and then they can log in. models.py => rom django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class Login(AbstractUser): is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) class Course(models.Model): course_name = models.CharField(max_length=100) course_desc = models.TextField(max_length=200) def __str__(self): return self.course_name class teacher(models.Model): user = models.ForeignKey(Login, related_name='Teacher', primary_key=True, on_delete=models.CASCADE) Name = models.CharField(max_length=100) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) Gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) Course = models.ForeignKey(Course, on_delete=models.DO_NOTHING) Email = models.EmailField() Image = models.ImageField(upload_to='images/teachers') Status = models.IntegerField(default=0) def __str__(self): return self.Name class student(models.Model): user = models.OneToOneField(Login, on_delete=models.CASCADE, related_name='Student', primary_key=True) Name = models.CharField(max_length=100) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) Gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) Course = models.ForeignKey(Course, on_delete=models.DO_NOTHING) Email = models.EmailField() Image = models.ImageField(upload_to='images/students') Status = models.IntegerField(default=0) def __str__(self): return self.Name and the forms.py=> from … -
Celery worker keeps creating new SQS queue
I'm using Django with Celery and attempting to deploy Celery using SQS and ECS. These are my celery-related Django settings: CELERY_BROKER_URL = "sqs://" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_IMPORTS = "app.tasks" CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "us-west-2", "predefined_queues":{ "staging.fifo": { "url": "https://sqs.us-west-2.amazonaws.com/<account id>/staging.fifo", } } CELERY_TASK_DEFAULT_QUEUE = "staging.fifo" My celery worker ECS task definition gives it full IAM access to SQS. But every time I start my celery worker ECS container, instead of using my existing SQS queue, "staging.fifo," the worker seems to create a new queue in SQS called "celery." Why is it creating this new queue instead of using the queue that I specified? -
Django admin dependable dropdown
So I'm trying to make a dependable dropdown for django admin, and when i select a province the console shows the following error: 405 method not allowed {"readyState":4,"responseText":"{\"detail\":\"Method \\\"GET\\\" not allowed.\"}","responseJSON":{"detail":"Method \"GET\" not allowed."},"status":405,"statusText":"Method Not Allowed"} the related codes are as given below and the method is POST on both the ajax function and View but it says GET method is not allowed the models.py is as: class Province(models.Model): name = models.CharField( max_length=30 ) class Meta: verbose_name = _("province") verbose_name_plural = _("provinces") def __str__(self): return self.name class District(models.Model): province = models.ForeignKey( Province, on_delete=models.CASCADE ) name = models.CharField( max_length=50 ) class Meta: verbose_name = _("district") verbose_name_plural = _("districts") def __str__(self): return self.name class SchoolProfile(models.Model): """ School detail model """ .....other_fields.... province = models.ForeignKey( Province, on_delete=models.SET_NULL, blank=True, null = True, verbose_name = _("province") ) district = models.ForeignKey( District, on_delete=models.SET_NULL, blank=True, null = True, verbose_name = _("district") ) and on admin.py @admin.register(SchoolProfile) class SchoolProfileAdmin(admin.ModelAdmin): inlines = [ServerInline, ServerUpdateInline] list_display = [...] class Media: js=("school/dependent-dropdown-ajax.js",) views.py from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from django.http import JsonResponse class DistrictList(APIView): permission_classed=[IsAuthenticated,] def post(self, request, format=None): province=request.data['province'] district={} if province: districts=Province.objects.get(id=province).districts.all() district={p.name:p.id for p in districts} return JsonResponse(data=district, safe=False) urls.py url(r'^districts/$', DistrictList.as_view(), name='districts'), dependent-dropdown-ajax.js the … -
Python to Django & Template
as a python below works, as exactly as I need ` import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Expenses.settings') django.setup() from prettytable import PrettyTable from django.db.models import Sum from dailytrans.models import Transactions import calendar def print_table(data): months = sorted(list(data.keys())) table = PrettyTable() table.field_names = ["Month"] + [month for month in months] for trans_mode in sorted(data[months[0]].keys()): row = [trans_mode] for month in months: row.append(data[month].get(trans_mode, 0)) table.add_row(row) print(table) if __name__ == '__main__': transactions = Transactions.objects.all() if not transactions: print("No data found") else: mode_totals = transactions.values('trans_mode').annotate(total=Sum('trans_amount')).order_by('trans_mode') month_totals = {} for trans in transactions: month = trans.trans_date.month month_name = calendar.month_name[month] month_totals[month_name] = month data = {} for mt in mode_totals: mode = mt['trans_mode'] for month_name in month_totals.keys(): month_total = transactions.filter(trans_mode=mode, trans_date__month=month_totals[month_name]).aggregate(total=Sum('trans_amount'))['total'] if not month_total: month_total = 0 if month_name not in data: data[month_name] = {} data[month_name][mode] = round(month_total, 2) print_table(data) ` how to transfer this to view and render to template I want achive as like in the attachment. I want to sum the trans_total grouped by month, then group by trans_mode. -
Having issue with xhr.send(blob) for Django, sending audio file
I am trying to send the blob to the backend but it failed. Code for views.py @login_required @ensure_csrf_cookie @require_http_methods({"GET","POST"}) def record_audio(request: HttpRequest) -> HttpResponse: if request.method == "GET": return render(request, 'recording/record.html') blob= request.FILES.get("blob", None) if blob is None: return HttpResponseBadRequest("Missing audio-blob parameter") now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") filename = f"{request.user.username}_{now}.wav" filepath = Path.joinpath(settings.MEDIA_ROOT, "recordings",filename) with open(filepath, 'wb') as audio_file: for chunk in blob.chunks(): audio_file.write(chunk) return HttpResponse(status=HTTPStatus.NO_CONTENT) Code for the sending blob part: var csrftoken = getCookie('csrftoken'); var xhr = new XMLHttpRequest(); xhr.open('POST', '/record-audio/', true); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.setRequestHeader("MyCustomHeader", "Put anything you need in here, like an ID"); // console.log(blob) // downloadBlob(blob) xhr.send(blob); I am also using the jquery-1.12.3.js -
Multi Database Architecture in Django
in my Django project, I have database architecture requirements like this users and organization details are stored in a single DB here that I named as auth_db and each organization may have its independent DB or multiple organization has a single DB this project follows a monolith architecture, all databases are configured in a single project. to achieve these I create two db routers and a middleware before that I store the db name in the auth_db the db name should be present in the request.user.organization.db_name, and all the databases are already configured inside the settings class AuthDBRouter: route_app_labels = {'auth', 'contenttypes', 'sessions', 'admin', 'user','organization', 'database'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return auth_db return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return auth_db return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == auth_db return None from django.utils.deprecation import MiddlewareMixin from rest_framework_simplejwt import authentication import threading from django.conf import settings THREAD_LOCAL = threading.local() class DBSelectionMiddleware(MiddlewareMixin): def process_request(self, request): user = authentication.JWTAuthentication().authenticate(request) if user: user = user[0] if user and not user.is_anonymous … -
Django-import-export is not getting imported in admin.py
I am trying to use django-import-export library to provide excel data upload action in the admin panel. I have done following pip install django-import-export Have added it to installed apps INSTALLED_APPS = ( ... 'import_export',) Have collected staticfiles python manage.py collectstatic However now when I am trying to import import_export in admin.py, It is showing an error that module is not found. Image of admin.py I have checked I am in same virtual environment. PIP freeze shows that the module django-import-export is installed in the virtual environment. PIP Freeze image Can someone help with what I am doing wrong here -
Optimize code and some bug with double click submit
my first question is some optimize and better clean code, one if inside view is used twice in another view, so how can i modify my code to cleaner code and second question is about when tried sumbit that views in template i need click twice submit button to add into db, when i click one nothing add and second time is like everything working, can someone tell me wheres some error def manual_montage_add(request: HttpRequest) -> HttpResponse: form_montage = forms.DailyMontageManualForm( request.GET or None, request=request ) formset = forms.MonterManualDailyFormset( queryset=MonterDailyHours.objects.none() ) if request.method == "GET": form_montage = forms.DailyMontageManualForm( request.GET or None, request=request ) formset = forms.MonterManualDailyFormset( queryset=MonterDailyHours.objects.none() ) if request.method == "POST": form_montage = forms.DailyMontageManualForm( request.POST, request=request ) formset = forms.MonterManualDailyFormset(request.POST) try: if formset.is_valid() and form_montage.is_valid(): montage = form_montage.save(commit=False) montage.user = request.user montage.save() for form in formset: if form.is_valid(): monter = form.save(commit=False) monter.daily_montage = montage monter.date = montage["date"].value() if ( form["status"].value() == "URLOP" or form["status"].value() == "L4" or form["status"].value() == "UŻ" ): start = "08:00:00" end = "16:00:00" monter.start_work = datetime.datetime.strptime( start, "%H:%M:%S" ) monter.end_work = datetime.datetime.strptime( end, "%H:%M:%S" ) monter.daily_hours = datetime.datetime.strptime( start, "%H:%M:%S" ) else: monter.start_work = form.cleaned_data["start_work"] monter.end_work = form.cleaned_data["end_work"] obj = calc_function( form.cleaned_data["start_work"], form.cleaned_data["end_work"], ) monter.sum_work = … -
Django can't connect to MySQL in Docker+Django+MySQL
I'm trying to pack my working student application into containers. Here is my docker-compose.yaml: version: "3.8" services: mysql_db: build: context: . dockerfile: ./docker/mysql/Dockerfile restart: unless-stopped env_file: env.dev ports: - "33061:3306" networks: - autopark_network backend: build: context: . dockerfile: docker/django/Dockerfile env_file: env.dev restart: on-failure depends_on: - mysql_db working_dir: "/app/autopark" expose: - 800 ports: - "8001:8000" command: ["python3", "manage.py", "runserver", "0.0.0.0:8000"] networks: - autopark_network networks: autopark_network: Here is env.dev: DEBUG=1 SECRET_KEY=<...> DJANGO_ALLOWED_HOSTS="localhost 127.0.0.1 [::1]" MYSQL_ENGINE=django.contrib.gis.db.backends.mysql MYSQL_DATABASE=autopark MYSQL_DATABASE_HOST=mysql_db MYSQL_DATABASE_PORT=33061 MYSQL_ROOT_PASSWORD=<...> MYSQL_USER=pavel MYSQL_PASSWORD=<...> I thought that both of my services will get those environment variables so I can be sure everything is ok. As if. I need GDAL for my project, that's why I started backend not with python but with ubuntu (here's my Dockerfile for backend): FROM ubuntu:22.04 MAINTAINER Pavel Vasilev <pvlvslv@yandex.ru> RUN apt -y update RUN apt -y install python3-dev python3-pip gdal-bin gdal-data WORKDIR /app/autopark ADD . /app/autopark RUN pip install -r requirements.txt Then I need initialization for my mysql_db (here's my Dockerfile for mysql_db): FROM mysql/mysql-server:latest COPY ./docker/mysql/init_db.sh /docker-entrypoint-initdb.d/ COPY ./docker/mysql/init_db.sql /usr/local/ RUN chmod +x /docker-entrypoint-initdb.d/init_db.sh And here is init_db.sh: #!/bin/bash mysql -u root --password="$MYSQL_ROOT_PASSWORD" << EOF SOURCE /usr/local/init_db.sql USE ${MYSQL_DATABASE}; GRANT ALL PRIVILEGES ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'; EOF init_db.sql was … -
Django queryset grouping by a field
I have models Subject, Topic and Question like this: class Subject(models.Model): subject = models.CharField(max_length=200, unique=True) class Topic(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) topic = models.CharField(max_length=200, blank=False) class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, topic = ChainedForeignKey( "Topic", chained_field="subject", chained_model_field="subject", show_all=False, auto_choose=True, ) I am filtering Question model like this: proc_subj = Question.objects.filter(approval_status="Approved").filter(subject__in=mysubjects).values('subject__subject', 'topic__topic') \ .order_by('subject__subject').distinct() This gives output like: <QuerySet [{'subject__subject': 'ss1', 'topic__topic': 'ICA1'}, {'subject__subject': 'ss1', 'topic__topic': 'ICA2'}, {'subject__subject': 'ss1', 'topic__topic': 'PDL ICA-2'}, {'subject__subject': 'ss2', 'topic__topic': 'Structural lines of hard tissues of teeth'}, {'subject__subject': 'ss2', 'topic__topic': 'Oral mucosa ICA-2'}, {'subject__subject': 'ss3', 'topic__topic': 'Salivary glands ICA-2'}, {'subject__subject': 'ss3', 'topic__topic': 'POST ICA-2 Dental morphology/eruption & shedding'}]> If we look at the above query set ss1 as a subject there are three entries. I want to regroup based on similar subjects and get output like the below: <QuerySet [{'subject__subject': 'ss1', 'topic__topic': 'ICA1', 'topic__topic': 'ICA2', 'topic__topic': 'PDL ICA-2'}, {'subject__subject': 'ss2', 'topic__topic': 'Structural lines', 'topic__topic': 'Oral mucosa'}, {'subject__subject': 'ss3', 'topic__topic': 'Salivary glands ICA-2''topic__topic': 'POST ICA-2'}]> I tried by adding .grouped_by(subject__subject) also I tried template regroup tag both did not give me the desired results. Any one please give me a hand? The reason I am trying is to create a option grouped multi select list like this: -
how to deploy django (apiview ) web application in ec2 ? with DateaBase but without using frim AWS-RDS ? (is this for test deploy ment )?
I can deploy the Django from ec2. but I need from DB how can i connect DB without RDS-AWS its just testing deployment and I can't spend money because I am a student, please any one can show the answer ? some of them instruct me to create dB inside your ec2 but I can't have good knowledge and no other's tutorials. please help me to find the answer ? -
Django rest framework slow response time
I am working on a project. I am using Django rest framework. I have a category model. And there is only 2 rows. And the api response time is 180 ms avarage. it is too slow for only 2 rows. And api is very simple. Why it is too slow for such a simple api. here is my view class CategoryListView(generics.ListAPIView): queryset = Category.objects.order_by('order').all() serializer_class = CategorySerializer def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) print(queryset.query) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) here is my serializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ("id", "name", "order") And here is the query generated. SELECT "questions_category"."id", "questions_category"."created_at", "questions_category"."updated_at", "questions_category"."name", "questions_category"."name_tk", "questions_category"."name_ru", "questions_category"."icon", "questions_category"."order" FROM "questions_category" ORDER BY "questions_category"."order" ASC I am analyzing it with django-silk query time is 6 ms. but response time is 180 ms Could somebody help me with this? -
Profile matching query does not exist
I am following a tutorial on building a social media app using django. I have this bug that has kept me stuck for days despite doing exactly as the tutorial goes. Whenever i try to open the settings page of my profile, I get a doesNotExist error. the error seems to be coming from here " user_profile = Profile.objects.get(user=request.user) " This the views for my settings page @login_required(login_url='signin') def settings(request): # Check if logged in user has profile, if not redirect to create profile user_profile = Profile.objects.get(user=request.user) return render(request, 'settings.html', {'user_profile': user_profile}) Sometimes I get an error about the profile_img not being found. Although i couldn't get it to repeat itself at the time of asking for help here. But when I commented out the profile_img line in my modles.py, the error changed back to 'profile not matching query' This my models.py class Profile(models.Model): objects = models.Manager() user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) location = models.CharField(max_length=150, blank=True) profile_img = models.ImageField(upload_to='profile_images', default='blank_profile_image.jpeg') However, removing the link to to my modles.py seems to make the settings page accessible. @login_required(login_url='signin') def settings(request): # Check if logged in user has profile, if not redirect to create profile #user_profile = Profile.objects.get(user=request.user) …