Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models troubles in admin
I was trying to build database connections for an online school project. It turned out that I have 2 entities Student and Course, they have a many-to-many relationship. At the same time, if I delete a student from a course, the course will not be deleted and also, when I delete a course, the students will not be deleted. I had an idea to make a related model through which I can assign courses to students and vice versa, but after creating the connection, when I try to disconnect a student from it, I get an error IntegrityError at /admin/student/studentcourse/1/change/ NOT NULL constraint failed: student_studentcourse.student_id Request Method:POSTRequest URL:http://127.0.0.1:8000/admin/student/studentcourse/1/change/Django Version:4.2.7Exception Type:IntegrityErrorException Value:NOT NULL constraint failed: student_studentcourse.student_idException Location:C:\Users\amane\PycharmProjects\StudyHome\.venv\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in executeRaised during:django.contrib.admin.options.change_viewPython Executable:C:\Users\amane\PycharmProjects\StudyHome\.venv\Scripts\python.exePython Version:3.11.4Python Path:['C:\\Users\\amane\\PycharmProjects\\StudyHome', 'C:\\Users\\amane\\PycharmProjects\\StudyHome', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 'C:\\Users\\amane\\AppData\\Local\\Programs\\Python\\Python311', 'C:\\Users\\amane\\PycharmProjects\\StudyHome\\.venv', 'C:\\Users\\amane\\PycharmProjects\\StudyHome\\.venv\\Lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2022.2\\plugins\\python\\helpers\\pycharm_matplotlib_backend']Server time:Mon, 27 Nov 2023 13:10:21 +0000 My project code student/models.py from django.db import models class Student(models.Model): GENDER_CHOICES = [ ('М', 'Мужской'), ('Ж', 'Женский'), ] student_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, blank=False) surname = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) age = models.IntegerField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES) parents_phone = models.CharField(max_length=100) parents_email = models.EmailField(max_length=100, blank=False) phone = models.CharField(max_length=20) email = models.EmailField(max_length=100, blank=False) description … -
Django channels login connection already closed
I'm trying to login user after registering where my app is using django channels in combination with Strawberry. class RegisterUserMutation(DjangoCreateMutation): def create_user(self, data, password): user = MyUserModel(**data) user.set_password(password) user.save() return user def login_user(self, info, username, password): request = get_request(info) user = auth.authenticate(request, username=username, password=password) print(f"Step 3.1 - authenticate user {user}") if user is None: raise IncorrectUsernamePasswordError() scope = request.consumer.scope print("Step 3.2 - fetched scope") async_to_sync(channels_auth.login)(scope, user) print("Step 3.3 - channels login") # According to channels docs you must save the session scope["session"].save() print("Step 3.4 - scope updated with session") # FIXME: session doesnt actually seem logged in. return user @transaction.atomic def create(self, data: dict[str, Any], *, info: Info): password = data.pop("password") username = data.get('username') validate_password(password) with DjangoOptimizerExtension.disabled(): data = self.set_default_values(data) print("Step 1: Set default values") user = self.create_user(data, password) print("Step 2: Created user") self.login_user(info, username, password) print("Step 3: Logged in user") return user When I try that code, the user "step 3" is never completed with error django.db.utils.InterfaceError: connection already closed. It seems that: The user is correctly created (Step 2) The user authenticated against django correctly (Step 3.1) The scope is fetched (Step 3.2) But the channels_auth.login is never completed: async_to_sync(channels_auth.login)(scope, user) Is where it seems to fail. Any … -
Iterating through form-data with nested keys in Django Rest Framework
I'm working on a project using Django Rest Framework, where I need to create a company by sending relevant documents through form-data. When I print the data received, it looks like this: { "company[company_owner][email]": "rohansheryabraham@gmail.com", "company[company_owner][phone]": "098765439", "company[company_owner][first_name]": "Mike", "company[company_owner][last_name]": "Tyson", "company[company_name]": "Testing", "company[company_email]": "testing@mail.com", "company[company_mobile_phone]": "980765432", "company[company_landline]": "78765421", "company[company_country]": "India", "company[email_otp]": "783143", "company[mobile_otp]": "256310", "company_detail[0][detail_id]": "110", "company_details[0][documents]": [some list of file], } Now unlike JSON I cannot dynamically access documents in form-data like print(company_detail[0]['documents'])can anyone suggest a good way to iterate this? for now, I am just printing data @api_view(['POST']) @permission_classes([AllowAny]) @parser_classes([FormParser, MultiPartParser]) def test(request): print(request.data) #logic to create company return Response() -
Django celery cron job is not calling back the tasks
I'm trying to run celery cron job after every 30 second but its not working. Tried every possible solution, mentioned the beat command in my docker-compose.yaml command field under celery_worker but its not working, don't know what i'm missing. Logs does not show anything unusual. apps/ app1/ tasks.py app2/ project/ __init__.py settings.py celery.py ... manage.py docker-compose.yaml celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") app = Celery("celery_app") app.config_from_object("django.conf:settings", namespace="CELERY") app.conf.beat_schedule = { 'send-event-reminders': { 'task': 'apps.app1.tasks.send_event_reminders', 'schedule': 30, # run after every 30 seconds }, } app.autodiscover_tasks() tasks.py (below method has no errors if i run it manually, but not getting hit from celery @shared_task def send_event_reminders(): logger.info("send_event_reminders task called") print("send msg") ...some code here return this is my celery_worker in my docker-compose.yaml celery_worker: ... build: dockerfile: ./docker/Dockerfile.dev command: celery -A etell_django_app worker -B -l info volumes: - .:/app - static_files:/app/static env_file: .env depends_on: - redis - etell_db -
TypeError at / Insertdetails() missing 1 required positional argument: 'request' - Django
I am getting the following error in a Django project TypeError at / Insertdetails() missing 1 required positional argument: 'request' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.2.7 Exception Type: TypeError Exception Value: Insertdetails() missing 1 required positional argument: 'request' Exception Location: D:\Works\django\projects\proj1\proj1\views.py, line 9, in Insertdetails Raised during: proj1.views.Insertdetails Python Executable: C:\Users\ankilla\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.6 I am totally new to Django, I need to insert data into mysql from HTML page. I was following a old video https://www.youtube.com/watch?v=d9fx8qrJyCY Views.py from django.shortcuts import render from proj1.models import Insertrecord from django.contrib import messages def Insertdetails(request): if request.method == "POST": saverecord=Insertdetails() saverecord.ID=request.POST.get('ID') saverecord.Name=request.POST.get('Name') saverecord.Email=request.POST.get('Email') saverecord.Address=request.POST.get('Address') saverecord.save() messages.success(request,'Saved') return render(request,'index.html') else: return render(request,'index.html') models.py from django.db import models class Insertrecord(models.Model): ID=models.IntegerField() Name=models.CharField(max_length=100) Email=models.CharField(max_length=100) Address=models.CharField(max_length=100) class Meta: db_table="employee" Index.html <form method="post"> Emp Id : <input type="number" name="ID"> Employee Name : <input type="text" name="Name"> Email : <input type="text" name="Email"> Address : <input type="text" name="Address"> <input type="submit" value="Submit </form> Urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ #path('admin/', admin.site.urls), path('',views.Insertdetails) ] Please help Followed the same as video to insert data into mysql -
Django JSONField filter on complex JSON document with list of object
I work with Django 3.2 and MariaDB. I have an Product Model with an product_settings field (typed as JSONField ). With a queryset I want to retrieve all products with a type of deposit equals to building. Example of truncated product_settings value : { "resources": [ { "resource_config": { "linked_to": { "params": { "deposit": { "type": "building" } } } } } ] } I'm trying with this queryset but it does not return any results : Product.objects.filter(product_settings__resources__resource_config__linked_to__params__deposit__type="oauth2") Do you have any idea ? I've already read this question but mine is quite more complex and need another solution. -
Many-to-many communication of a model in Django with itself
How can I create a customer table in the database using Django models so that the desired customers can be linked together, with the following conditions? The client may not be related to any other client. The customer may have a relationship with one or more other customers. When for customer 1 and customer 2 the connection with customer 4 was registered, and in reading the connections of customer 1 the connection with customer 4 was visible. Conversely, by reading the communications of customer 4, you can find out about customer 1 and customer 2. I have attached a schematic example of what I mean. Schema class CustomUser(AbstractBaseUser, PermissionsMixin): nid = models.CharField(max_length=10, unique=True, db_index=True, primary_key=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=255) USERNAME_FIELD = "nid" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.nid friends = models.ManyToManyField("self") -
Django, How to access request data in include template
In my Django project, I have some templates that includes in base template using {% include %} tag. How do I access request data in this included template? How do I access context variables in this included template? I was expecting that request data is accessible in any template. -
How to retry failed tasks in celery chunks or celery starmap
I would like to know how to configure these tasks correctly so that the failed tasks can be retried. One thing I have noted is if one of the tasks in the chunk fails, the whole chunk (I assume executed by celery.starmap) fails @celery_app.task def get_item_asteroids_callback(parent_item_id): pass @celery_app.task( ignore_result=False, autoretry_for=(requests.exceptions.ReadTimeout, TimeoutError, urllib3.exceptions.ReadTimeoutError, InterfaceError), retry_kwargs={'max_retries': 3}, retry_backoff=True ) def get_item_asteroid(work_id): """ Does some stuff that can raise some exceptions. """ raise requests.exceptions.ReadTimeout('Test Exception') @celery_app.task(ignore_result=False) def get_item_asteroids(parent_item_id): item_ids = [1,2,3.......] item_ids = [(item_id,) for item_id in item_ids] chunk_size = min(len(item_ids), 128) tasks = [get_item_asteroid.chunks(item_ids, chunk_size).group()] chord(tasks)(get_item_asteroids_callback.si(parent_item_id)) None of the failed tasks is retried (The Retried count is 0) -
Please tell me how to implement views.py of audio recording app
I want to create a recording app using Django. As a beginner, I'm not sure what kind of processing to write in views.py though I read many information about pyaudio, librosa etc... The desired functions are: Record the user's voice with the smartphone's microphone. put some effect on it.(I think I can handle this myself, so I'm not expecting code example) Save the recorded audio in the database. I would like to see an example code for implementing function1,3. As I said, I've read many information about pyaudio, librosa etc... But have no idea because I could not find how to combine the code to template.(like start recording button). Thank you in advance for your guidance. -
How to pass a sub-directory of a website to uwsgi in nginx?
Suppose I have a website named www.test.com. Now I've written a django server, and I want to access this server via www.test.com/api. So I write the nginx configuration file like this: server { listen 80; server_name www.test.com; root ROOT_FOR_MAIN_SERVER; access_log /var/log/nginx/access.www.test.com; error_log /var/log/nginx/error.www.test.com; location / { index index index.php index.html; try_files $uri $uri/ =404; } location /api { include uwsgi_params; uwsgi_pass unix:ROOT_FOR_DJANGO_SERVER/uwsgi/uwsgi.sock; } location ~ \.php(.*)$ { root ROOT_FOR_MAIN_SERVER; fastcgi_pass unix:/run/php/php8.1-fpm.sock; fastcgi_index index.php; fastcgi_split_path_info ^(.+\.php)(.*)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; include fastcgi_params; } location ~ /\.ht { deny all; } } But when I access www.topfyf.cn/api, the uri will still contains /api. Can I tell nginx or uwsgi that I want to delete the /api prefix, i.e., if I access /api/abc, the request becomes /abc when I comes to the django server? -
Static files not loading in pythonanywhere
I am going to run my project on the pythonanywhere site and I did all the work, but the static files are not loaded. I'm developing a website with Django. My static files are located in the static_root directory and the static file path is also set correctly in my Django settings. However, when I open the website in the browser, the static files are not loading. For example, when I try to access an image, I get the following error: 404 Not Found: /static/images/my_image.jpg I've checked the following: The static_root directory is accessible. The web server user has read access to the static_root directory. The Django application URL patterns point to the static files correctly. I've cleared the web server cache. I've used the Django debug toolbar and found no problems with the static file paths. Can anyone help me troubleshoot this issue? python version :3.9 django version :4.2.6 Thanks, Elyas -
how can i send my string statement to views.py file in django from another python file
class Decisions: @staticmethod def rpa(OlcumSonuclariLOG: list, dfLimit: pd.Series, test_kodu: int, urun_kodu: str, sonuc1=None, sonuc2=None, sonuc3=None, sonuc4=None,startDate = None,endDate = None,retest1 = None,retest2 = None,retest3 = None) -> None: rpaLog = OlcumSonuclariLOG[1:3] # 1. paletin 2. testi ve 2 paletin 1. testi seçiliyor statistics, sigma3 = Calculaters.spc_calculations(test_kodu, urun_kodu,startDate,endDate) OK_NOK_RPA = [] for i in range(len(rpaLog)): for j, rows in rpaLog[i].iterrows(): if (rows["Test Adı"] == "SS G'@100") and (rows["Deger"] <= LSL_SSG100): output = f"SS G'@100 için değer {rows['Deger']} alt spec {LSL_SSG100} altındadır." how can i pass the output variable to my views.py file ? -
How to login to Django views from React?
Currently I am facing an issue where I can sign in from react accurately but my django session is not updated based on whether I login or logout from react. What I am expecting is that when I sign in through react, my current user view in django will be changed to demonstrate the current user I signed in as from react but at this moment no changes can be seen. Using jwt tokens from react, I am able to access the current user view and get the correct user but this change can only be observed in react and the server side isn't adjusted to have the correct user logged in. The following image demonstrates my problem: problem Please provide any help that you can as I have been stuck on this problem for roughly a week now and have been unable to find a solution. This is how I handle sign ins in react. //Signs In the user through Django const handleSignIn = async ()=> { try { const response = await axios.post('http://127.0.0.1:8000/api/login/', { username, password }); //Store the access token const accessToken = response.data.access; alert("Sign In Success!\nAccess Token: " + accessToken) localStorage.setItem('accessToken', accessToken); //Store the refresh token … -
Store foreign key as eccrypted and fetch be decrypt
I am implementing a user management system using django ORM. It is said to store the Password in different table "user_password" and encrypt the the foreign key "id" of "user_password" table in "User" table. I implemented it by defining no relationship between the two tables. Is their any way to store and fetch the foreign relation object by encryting and decrypting the foreign key field while preserving the foreign key relation in database? -
Getting this Error PermissionError: [Errno 13] Permission denied: '/app/manage.py' in Docker
I am encountering a PermissionError when trying to run the docker compose run command for creating a Django project within a Docker container. The error message is as follows :- docker compose run --rm app sh -c "django-admin startproject myproject ." [+] Building 0.0s (0/0) docker:desktop-linux [+] Building 0.0s (0/0) docker:desktop-linux Traceback (most recent call last): File "/py/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/py/lib/python3.9/site-packages/django/core/management/commands/startproject.py", line 21, in handle super().handle("project", project_name, target, **options) File "/py/lib/python3.9/site-packages/django/core/management/templates.py", line 205, in handle with open(new_path, "w", encoding="utf-8") as new_file: PermissionError: [Errno 13] Permission denied: '/app/manage.py' . . . And this is my Dockerfile :- FROM python:3.9-slim ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /requirements.txt && \ adduser --disabled-password --no-create-home app ENV PATH="/py/bin:$PATH" USER app . . and this is my docker-compose.yml file :- services: app: build: context: . image: my-django-image ports: - 8000:8000 volumes: - ./app:/app command: > i tried … -
DJANGO Models based on MYSQL tables... :(
I have been working a bit with DJANGO, and I've encountered a somewhat serious issue. I'll start by saying that I'm trying to connect my MYSQL database to DJANGO, but when creating the models in PYTHON, well, they haven't turned out quite right. I'm new to this, so I don't really know how to handle M:N relationships in DJANGO. I tried some things, but when accessing from the ADMIN, it gives me an error, for example: OperationalError at /admin/Core/capctinstr/ (1054, "Unknown column 'CAPCT_INSTR.id' in 'field list'") I would greatly appreciate it if someone could help me with this. :( `-- -------------------------------------------------------------------------- -- -- Tabla: PUESTO CREATE TABLE PUESTO ( Codigo CHAR(4) PRIMARY KEY, Nombre VARCHAR(40) NOT NULL, Descripcion VARCHAR(320) NOT NULL ); -- Tabla: DEPARTAMENTO CREATE TABLE DEPARTAMENTO ( Codigo CHAR(4) PRIMARY KEY, Nombre VARCHAR(40) NOT NULL, Descripcion VARCHAR(320) NOT NULL, NumExtension VARCHAR(4) NOT NULL UNIQUE, FechaCreacion DATE DEFAULT(CURRENT_DATE) ); -- Tabla: PUESTO_DEPTO`your text` CREATE TABLE PUESTO_DEPTO ( Puesto CHAR(4), Departamento CHAR(4), PRIMARY KEY (Puesto, Departamento), FOREIGN KEY(Puesto) REFERENCES PUESTO(Codigo), FOREIGN KEY(Departamento) REFERENCES DEPARTAMENTO(Codigo) ); -- Tabla: EMPLEADO CREATE TABLE EMPLEADO ( Numero INT PRIMARY KEY AUTO_INCREMENT, NombrePila VARCHAR(60) NOT NULL, ApPaterno VARCHAR(60), ApMaterno VARCHAR(60), NumTel VARCHAR(15), Puesto CHAR(4), Departamento … -
I am creating a Django budgeting website and my changing status is not working, can anyone help me?
view-bills-admin.html {% extends "base/room_home.html" %} {% block content %} <div class="container d-flex align-items-center justify-content-center" style="min-height: 100vh;"> <div class="text-center"> <h1>{{ room_bills.title }}</h1> <p>Due: {{ room_bills.due }}</p> <div class="col-3"> <h3>Paid Members: </h3> <ul> {% for submission in submissions %} <li> <a href="proof/{{ submission.user.id }}" target="_blank">{{ submission.user.username }} {{ submission.text }}</a> <form> <label for="status">Status:</label> <select name="status" id="{{ submission.id }}" onblur="postStatus('{{ submission.id }}')"> <option value="P">Pending</option> <option value="A">Accepted</option> <option value="R">Rejected</option> </select> </form> </li> {% endfor %} </ul> </div> <div class="col-3"> <h3>Did not pay members: </h3> <ul> {% for user in did_not_submit %} <li>{{ user.username }}</li> {% endfor %} </ul> </div> </div> </div> <script> // Move the function outside the DOMContentLoaded event listener function postStatus(submissionId) { const selectElement = document.getElementById(submissionId); const status = selectElement.value; fetch(`/room/{{ room.join_code }}/bills/{{ bills.slug }}/status/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "submissionId": submissionId, "status": status }) }); } </script> {% endblock %} views.py @csrf_exempt def remark_proof_api(request, room_id, bills_slug): if request.method == "POST": data = json.loads(request.body.decode("utf-8")) submission_id = data["submission_id"] status = data["status"] sub = Submission.objects.get(id=int(submission_id)) sub.status = status sub.save() return JsonResponse({"success": True}) urls.py path('room/<str:room_id>/bills/<str:bills_slug>/status/', views.remark_proof_api, name='remark-proof'), I want the status to be changed but it doesnt work, everytime i refresh it keeps on going back to pending which is … -
Django load static tag not showing image
Tried viewing image on my browers but all i can see is the image placeholder. Here is the template code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="POST" style="background-color: rgb(201, 201, 24); padding: 10px;"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit"> </form> {% load static %} <img src="{% static 'myapp/mini.jpg}" alt="My image"/> </body> </html> in the settings i have: STATIC_URL = 'static/' STATICFILES_DIRS = [ 'myapp/static', ] STATIC_ROOT = 'static/' What can be the issue? I have tried renaming the folders and rearranging the image location but non helped. -
AddPage function in django making a new page but not redirecting to it - NoReverseMatch error
I'm trying to create a function that will make a new entry in a wikipedia website. So far the code I have will make the entry (i.e. if you go through the form to make the page, it will show up in the list of pages on the home screen) but instead of bringing you to the page when you hit submit, it shows me a NoReverseMatch error. It's saying "reverse for 'entry' not found. 'entry' is not a valid view function or pattern name." All I need it to do is redirect to the new page, but I can't figure out why it's saying entry isn't a valid view function? I have a function titled entry to hold the previous entries, but I'm having trouble connecting the issue. VIEWS.PY def entry(request, title): html_content = convert_md_to_html(title) if html_content == None: return render(request, "encyclopedia/error.html", { "message": "This entry does not exist." }) else: return render(request, "encyclopedia/entry.html", { "title": title, "content": html_content }) class AddPageForm(forms.Form): title = forms.CharField() content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", })) def add_page(request): form = AddPageForm() # <- called at GET request if request.method == "POST": form = AddPageForm(request.POST) # <- called at POST request if form.is_valid(): title … -
Django Form(Formset) is not working - id is missing?
My template form does not save the objects. here is my view: class FeatureDeliveryEditView( LoginRequiredMixin, PermissionRequiredMixin, SingleObjectMixin, FormView ): permission_required = "auth.can_access_supervising_sections" model = FeatureFilm template_name = "project/project_update/feature/update_featurefilm_delivery.html" def get(self, request, *args, **kwargs): self.object = self.get_object() return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def get_form(self, form_class=None): return FeatureDeliveryFormSet(**self.get_form_kwargs(), instance=self.object) def form_valid(self, form): form.save() messages.success(self.request, "Delivery erfolgreich gespeichert") return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): messages.error( self.request, f"Delivery nicht gespeichert: {form.errors}" ) return super().form_invalid(form) def get_success_url(self): return ( reverse("feature-detail-deliveries-half", kwargs={"pk": self.object.pk}) + "#content-start-under-cards" ) def handle_no_permission(self): return redirect("access-denied") and here is my form and formset: class FeatureDeliveryForm(ModelForm): class Meta: model = Delivery exclude = ( "feature_id", "tv_movie_id", "tv_serie_block_id", "restoration_id", "source_material", "scan_info", "usage_version", "orderer_id", "receiver_1_id", "receiver_2_id", "receiver_3_id", ) widgets = { 'trade_mark_brand': forms.Textarea(attrs={'rows': 1}), 'audio_channel_assignment': forms.Textarea(attrs={'rows': 1}), 'notes': forms.Textarea(attrs={'rows': 1}), # ... Andere Widgets hier } FeatureDeliveryFormSet = inlineformset_factory( FeatureFilm, Delivery, form=FeatureDeliveryForm, can_delete=True, ) if i used this template the form will be saved and all is working: {% extends "_base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row py-5"> <h3 class="text-center">{{ object }} - Delivery hinzufügen/editieren</h3> </div> <div class="row"> <form method="post" enctype="multipart/form-data"> {% for hidden_field in form.hidden_fields %} {{ … -
How to make django not send a `Content-Disposition` header?
I am trying to serve a static svg file on my local Django server. The file is quite large so I don't want to put it directly into my HTML. It shows This XML file does not appear to have any style information associated with it. The document tree is shown below. And then my svg. I have tried adding the following code in case Django couldn't identify svgs: import mimetypes mimetypes.add_type("image/svg+xml", ".svg", True) mimetypes.add_type("image/svg+xml", ".svgz", True) but it didn't help. It just served with the correct mime type. I believe the problem is in the Content-Disposition header, because compare the two responses: curl -i https://www.google.com/chrome/static/images/chrome-logo-m100.svg: HTTP/2 200 accept-ranges: bytes vary: Accept-Encoding, Sec-Ch-Ua-Full-Version-List, Sec-Ch-Ua-Platform, Sec-Ch-Ua-Platform-Version, Sec-CH-Prefers-Reduced-Motion content-type: image/svg+xml content-security-policy-report-only: require-trusted-types-for 'script'; report-uri https://csp.withgoogle.com/csp/uxe-owners-acl/chrome cross-origin-resource-policy: cross-origin cross-origin-opener-policy-report-only: same-origin; report-to="uxe-owners-acl/chrome" report-to: {"group":"uxe-owners-acl/chrome","max_age":2592000,"endpoints":[{"url":"https://csp.withgoogle.com/csp/report-to/uxe-owners-acl/chrome"}]} content-length: 2303 date: Sun, 26 Nov 2023 20:19:47 GMT expires: Sun, 26 Nov 2023 20:19:47 GMT cache-control: private, max-age=31536000 last-modified: Wed, 02 Mar 2022 19:00:00 GMT x-content-type-options: nosniff accept-ch: Sec-Ch-Ua-Full-Version-List, Sec-Ch-Ua-Platform, Sec-Ch-Ua-Platform-Version, Sec-CH-Prefers-Reduced-Motion critical-ch: Sec-Ch-Ua-Full-Version-List, Sec-Ch-Ua-Platform, Sec-Ch-Ua-Platform-Version, Sec-CH-Prefers-Reduced-Motion server: sffe x-xss-protection: 0 alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000 <svg fill="none" height="63" viewBox="0 0 63 63" width="63" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><linearGradient id="a" gradientUnits="userSpaceOnUse" x1="34.9087" x2="7.63224" y1="61.029" y2="13.7847"><stop offset="0" stop-color="#1e8e3e"/><stop offset="1" stop-color="#34a853"/></linearGradient><linearGradient id="b" gradientUnits="userSpaceOnUse" x1="26.9043" x2="54.1808" … -
Wagtail, change allowed extensions for WagtailImageField
I'm trying to add extra extensions wagtail.images.fields.WagtailImageField How it can be done? I've tried https://docs.wagtail.org/en/stable/reference/settings.html#wagtailimages-extensions , but seems like this is not the correct option -
Dynamic data for test with model_bakery
How to orginize dynamic data for a test using model_bakery? route_application_requester = Recipe( ApplicationRequester, form_applicant=cycle(FormChoices.values), inn=gen_inn, ) I need gen_inn to get the value from form_applicant, which can be entity or entrepreneur, and generate 10 or 12 digits depending on it. -
Am having errors anytime i want to carry out an installation with pip, i cant even install virtual environment
Been trying to carry out installations with pip but have been having errors, with virtual environment it keeps showing me could not find a version that satisfied the requirement vitualenv. I tried solving it with YouTube videos, i was instructed to add path to system environment but is still did not work