Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My form doesn't return any error in django
I am a Django developer and I am trying two put two forms in one html file(register and login forms), but when I write an invalid input into them, they didn't return any error. views.py def log(request): if request.method == 'POST': print(request.POST) if 'email' in request.POST: regisform = RegisterForms(request.POST) if regisform.is_valid(): print("is valid") clean_data = regisform.cleaned_data user =User.objects.create_user(username=clean_data['user_name'],password=clean_data['password_2'],email=clean_data['email']) login(request,user) messages.success(request, "شما با موفقیت ثبت نام شدید." ) Profile.objects.get(user_id = request.user.id).hearts_time = jdatetime.datetime.today() send_user_notification(user=user, payload={"head":"تبریک", "body":"به سایت ویکی ریاضی حوش آمدید."}, ttl=10) return redirect('home:homepage') else: print("is not valid.") else: form = LoginForms(request.POST) if form.is_valid(): data = form.data print(data) print("running") try: user = authenticate(request, username = data['username'],password=data['password']) print(user) except: user =authenticate(request, email = data['email'],password=data['password']) print(user) if user is not None: login(request, user) messages.success(request, "شما با موفقیت وارد شدید.","warning") else: print('NOT LOGIN') return redirect('home:homepage') else: print("Naderi") form = LoginForms() regisform = RegisterForms() try: content = { 'form':form, 'regist':regisform, } except: content = { 'regist':regisform, } return render(request, 'accounts/login.html',content) forms.py class RegisterForms(forms.Form): user_name = forms.CharField(max_length=30, widget=forms.TextInput(attrs={"placeholder":'username'})) password_1 = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder':'password'})) password_2 = forms.CharField(max_length=30,widget=forms.PasswordInput(attrs={'placeholder':'Confirm password'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder':'Email'})) captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) def clean_password_2(self): print('func 1 is begining.') password1 = self.cleaned_data['password_1'] password2 = self.cleaned_data['password_2'] listletter = 'abcdefghijklmnopqrstuvwxyz' listletterc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' adad = '1234567890' print(password1,password2) if password1 != … -
How to inject something at the end of every render in Django?
I want to inject a specific HTML comment at the end of every render of HTML in Django. I don't want to write that at the end of base.html template, but want it to be injected by code. Is there a way for me to do it? -
Django & dependency injection
In the past, I've used dependency-injector, but it looks like it's unmaintained now. :-( Does anyone have any good suggestions for a DI package? I'd want to be able to inject dependencies into views, with the ability to inject mocks in view tests. -
Not able to add Images and videos using quill rich text editor from local machine
Not able to Add Images and videos using Quill.js rich text editor. I have added quill editor in my django blog site,everything works fine but when i try to click image icon to add the image's from local machine i get this box. see this image i'm not able to select images from my local machine to upload in my blog using quill, but when i try to paste url link of the image from the internet then it works perfectly but not from local machine. this is my code :- const ColorClass = Quill.import("attributors/class/color"); const SizeStyle = Quill.import("attributors/style/size"); Quill.register(ColorClass, true); Quill.register(SizeStyle, true); // #stop const toolbarOptions = [ ["bold", "italic", "underline", "strike"], // toggled buttons ["blockquote", "code-block"], ["link", "image", "video", "formula"], [{ header: 1 }, { header: 2 }], // custom button values [{ list: "ordered" }, { list: "bullet" }, { list: "check" }], [{ script: "sub" }, { script: "super" }], // superscript/subscript [{ indent: "-1" }, { indent: "+1" }], // outdent/indent [{ direction: "rtl" }], // text direction [{ size: ["small", false, "large", "huge"] }], // custom dropdown [{ header: [1, 2, 3, 4, 5, 6, false] }], [{ color: [] }, { background: [] … -
Crispy tag leads to Hidden Field TOTAL_FORMS is a required field. error on POST
I have the following form in my template: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% crispy blog_form %} {% for form in formset %} {% crispy form %} {% endfor %} <button type="submit">Save</button> </form> However: when I post this I get the following error: Hidden Field TOTAL_FORMS is a required field. and Hidden field INITIAL_FORMS is a required field. This form works well when I don't use the crispy tags. I want to use crispy forms to make the form look good. What am I missing and how can I fix it? My form looks like this: class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ['name','teaser','hero_image','text','video','category_tag','brand_tag','bottle_tag'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div( Row('name', css_class='form-row my-1'), Row('teaser', css_class='form-control, my-1'), Row('text', css_class='form-control, my-1'), Row('hero_image', css_class='form-control-file form-row my-1'), Row('video', css_class='form-control-file form-row my-1'), Row( Column('category_tag', css_class='form-group col-md-4 my-1'), Column('brand_tag', css_class='form-group col-md-4 my-1'), Column('bottle_tag', css_class='form-group col-md-4 my-1'), ), Submit('submit', 'Save', css_class='my-3 btn btn-secondary') )) class BlogImageForm(forms.ModelForm): class Meta: model = BlogImage fields = ['image'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.form_method = 'post' self.helper.layout = Layout( Div( Row('image', css_class='form-row my-1'), )) -
How to set manifest_storage for ManifestFilesMixin (Django)
I use django-storages to serve my static files from S3. I want to use the ManifestFilesMixin for cache busting my CSS and JS files. The following works fine: from django.contrib.staticfiles.storage import ManifestFilesMixin from storages.backends.s3boto3 import S3Boto3Storage class ManifestS3Storage(ManifestFilesMixin, S3Boto3Storage): pass Except that staticfiles.json is placed in my S3 bucket. I don't want this as explained here. The Django docs mention that it is possible to give a "manifest_storage" argument to the ManifestFilesMixin but I don't know how to do this. The docs mention how to do it for the ManifestStaticFilesStorage class but I don't understand how to do this for the ManifestFilesMixin. -
Django-translations not returning models translations on DRF
I have a project setup with django 3.2.5 and drf 3.14.0 on python 3.6 and postgres 9.6. I followed the following steps to create a translatable model for learning products model. using this library for translations here. from translations.models import Translatable class LearningProduct(Translatable): title = models.CharField( _("Title"), max_length=255, unique=True ) description = models.TextField( _("Description"), blank=True, null=True ) image = models.ImageField( _("Image"), upload_to="uploads/images/learning_products/%Y/%m/%d", max_length=255, blank=True, null=True ) link = models.URLField( _("Link"), blank=True, null=True ) class Meta: db_table = "learning_product" verbose_name = _("Learning Product") verbose_name_plural = _("Learning Products") class TranslatableMeta: fields = ['title', 'description', 'link'] def __str__(self): return self.title added it to the admin panel as follows: from translations.admin import TranslatableAdmin, TranslationInline class LearningProductAdmin(TranslatableAdmin): inlines = [TranslationInline] admin.site.register(LearningProduct, LearningProductAdmin) it lets me save the model's translations for the specified fields. i have two languages setup in my settings as: ## Translation settings. LANGUAGES = ( ('en', _('English')), ('ne', _('Nepali')), ) i have my apiview setup as follows and it lets me fetch the model when no accept-language is passed as well as when En is passed as the accept-language but i run into the error given below it when i try get method woth accept-language as Ne. views.py # views.py from rest_framework … -
JS result of year-link click lands in the false column
I have a 2-columns (div) page. Left column: the posts right column: the respective years The years are clickable: if a year is clicked the result should filter the posts in the left column. **The error: after a year-click, the filtered posts land as well in the left column ( which is ok) as in the right column, and the year links disappear (wich is bad) ** The left div (posts): <div class="fenster"> {% if posts %} {% for post in posts %} <h3>{{ post.post_title }}</h3> <p id="{{ post.id }}">{{ post.post_content|safe }}</p> <p>Veröffentlicht am: {{ post.post_date|date:"l, j. F Y, H:i" }}</p> <p>Autor: {{ post.post_author.user_login }}</p> <button class="edit-button" data-post-id="{{ post.id }}">Bearbeiten</button> <hr> {% endfor %} {% else %} <p>Keine Posts gefunden.</p> {% endif %} </div> <div> {% if posts.has_previous %} <a href="?{{ request.GET.urlencode }}&page={{ posts.previous_page_number }}">Vorherige Seite</a> {% endif %} <span>Seite {{ posts.number }} von {{ posts.paginator.num_pages }}</span> {% if posts.has_next %} <a href="?{{ request.GET.urlencode }}&page={{ posts.next_page_number }}">Nächste Seite</a> {% endif %} </div> The right div (years): <div class="fenster">Zeitleiste <br> <div class="container" style="display: flex; flex-wrap: wrap;"> {% for jahr in jahre %} <div class="flex-item" style="flex-basis: 10%;"> <a href="?action=year&year={{jahr}}" class="year-link">{{ jahr }} </a> </div> {% if jahr|divisibleby:10 %} <div style="flex-basis: 100%;"></div> {% … -
can't apply static file in django / docker
enter image description here what I have to next ? give me some advice .. it's github repository https://github.com/OZ-Coding-School/oz_02_collabo-006-BE/tree/Feature-docker i want to apply css and solve cors error nginx.conf server { listen 80; server_name 223.130.133.22; location / { proxy_pass http://dg01:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # 정적 파일 설정 location /static/ { alias /src/static; # Docker 컨테이너 내 Django STATIC_ROOT 경로 expires 30d; # 브라우저 캐싱 최대화 } } dockerfile # Python 3.12 베이스 이미지를 사용합니다. FROM python:3.12 # 환경 변수 설정으로 Python 출력을 stdout으로 보내도록 설정합니다. ENV PYTHONUNBUFFERED=1 RUN mkdir -p /path/to/django/logs/ RUN mkdir -p /var/log/nginx # 필요한 시스템 패키지 설치 # libpq-dev: PostgreSQL 데이터베이스 연동을 위한 라이브러리 RUN apt-get update \ && apt-get install -y --no-install-recommends libpq-dev \ && rm -rf /var/lib/apt/lists/* # pip를 최신 버전으로 업그레이드하고 poetry를 설치합니다. RUN pip install --upgrade pip \ && pip install poetry # /app 디렉터리를 작업 디렉터리로 설정합니다. WORKDIR /src # 프로젝트의 Python 종속성 관리 파일을 작업 디렉터리로 복사합니다. COPY pyproject.toml poetry.lock* /src/ # poetry를 사용하여 의존성을 설치합니다. 가상 환경은 생성하지 않습니다. RUN poetry config virtualenvs.create false \ && poetry install --no-dev --no-interaction --no-ansi # 프로젝트의 나머지 파일을 작업 디렉터리로 복사합니다. COPY . … -
Railway Error when deploying DJango App due to botocore dependency (boto3)
After installing boto3 package to integrate with AWS S3 buckets, the application fails on deployment. The Railway error is "botocore 1.34.93 depends on urllib3<1.27 and >=1.25.4; python_version < "3.10". On the local server (127.0.0.1:8000) everything works fine, and app deployed with no issues before installing boto3. Upon installing boto3, I expected the app to deploy on Railway as it did before installing the package. Any suggestions? -
I get this error when sending a POST request: MissingSchema: Invalid URL 'None/orders': No scheme supplied. Perhaps you meant https://None/orders?
I'm getting this error when I use Insomnia to send a POST request to an API of my backend code (which is running on my desktop) when I try to create an order. But when I send the same request to the API of the backend running on our test server it works. What is causing this error ? It seems to me that it has something to do with the configuration of my Insomnia but I'm not sure. From what I've read on Stack Overflow it can be caused by not prefixing the URL with http:// or https:// but my URL does have http://. Thank you in advance to anyone who can offer advice. [enter image description here](https://i.sstatic.net/zOP223U5.png) Tried sending a POST request to create an order but got an error. But when sending the same request to the version of the backend running on our test server it works. -
I tried uploading a python app using Django into a live server and got null return errors
I am learning some Django along with python and created a project recently. The project worked as i wanted in the development local server but when i uploaded it to a live server on the web I got so many errors. I followed the instructions and created a virtual env too. Here's the traceback: (dibaspratapbasnet.com.np/stderr.log) I tried the following: Changing the url links to all the error files. Editing the .htacess files. Giving all permissions. Changing the directories to the exact as shown by cPanel file manager. -
Django Signals : Access ManyToManyRel value from instance
I have the following signal : @receiver(post_save, sender=Document) def handle_added_or_edited_element(sender, instance, **kwargs): ''' This signal is used to compare the original and the current instance of the object being saved. If at least one field has changed, a row is inserted in the revision history of the related srd_revision ''' for field in sender._meta.get_fields(): if field.name in ['srd_revision', 'srdrevision', 'srd_rev']: print(instance._meta.get_fields()[0]) if not isinstance(field, (models.ManyToOneRel, models.ManyToManyRel)): if instance._get_field_value_map(instance._meta)[field.name].value != instance.__original_instance._get_field_value_map(instance._meta)[field.name].value: chapter, message = RevisionHistory().get_document_messages(instance=instance, created=False, updated_field=field.name) SrdRevisionHistory(chapter=chapter, title=message) This two lines : if field.name in ['srd_revision', 'srdrevision', 'srd_rev']: print(instance._meta.get_fields()[0]) Gives me a ManyToManyRel : <ManyToManyRel: srdapp.srdrevision> I would like to access the id of the srdrevision object related to the Document object. -
how do i export the actual field data instead of id?
admin.py from import_export import resources from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .models import Institution, Locality, AccessionNumber class AccessionNumberResource(resources.ModelResource): class Meta: model = AccessionNumber fields = ("user__username", "number", "institution__name", "locality__name", "locality__abbreviation", "date_time_accessioned") class AccessionNumberAdmin(ImportExportModelAdmin): resource_class = AccessionNumberResource list_display = ("user", "number", "institution", "locality", "date_time_accessioned",) list_filter = ("number",) # Add filter by accession number admin.site.register(Institution) admin.site.register(Locality) admin.site.register(AccessionNumber, AccessionNumberAdmin) I'm trying to export foreign key data instead of IDs..and it's not working -
Azure Deployment Failure: Django Azure Web App
I'm running a Django Web App - it's working locally, and was deploying successfully to Azure. I'm now seeing the following error on the logstream: Traceback (most recent call last): 2024-05-03T06:02:12.640875058Z File "/home/site/wwwroot/antenv/lib/python3.11/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker 2024-05-03T06:02:12.640878658Z worker.init_process() 2024-05-03T06:02:12.640881958Z File "/home/site/wwwroot/antenv/lib/python3.11/site-packages/gunicorn/workers/base.py", line 134, in init_process 2024-05-03T06:02:12.640885158Z self.load_wsgi() 2024-05-03T06:02:12.640899358Z File "/home/site/wwwroot/antenv/lib/python3.11/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2024-05-03T06:02:12.640909259Z self.wsgi = self.app.wsgi() 2024-05-03T06:02:12.640912259Z ^^^^^^^^^^^^^^^ 2024-05-03T06:02:12.640915159Z File "/home/site/wwwroot/antenv/lib/python3.11/site-packages/gunicorn/app/base.py", line 67, in wsgi 2024-05-03T06:02:12.640918359Z self.callable = self.load() 2024-05-03T06:02:12.640921359Z ^^^^^^^^^^^ 2024-05-03T06:02:12.640924259Z File "/home/site/wwwroot/antenv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2024-05-03T06:02:12.640927359Z return self.load_wsgiapp() 2024-05-03T06:02:12.640930759Z ^^^^^^^^^^^^^^^^^^^ 2024-05-03T06:02:12.640933659Z File "/home/site/wwwroot/antenv/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2024-05-03T06:02:12.640936759Z return util.import_app(self.app_uri) 2024-05-03T06:02:12.640939659Z ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-05-03T06:02:12.640942759Z File "/home/site/wwwroot/antenv/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app 2024-05-03T06:02:12.640945959Z mod = importlib.import_module(module) 2024-05-03T06:02:12.640948959Z ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-05-03T06:02:12.640952059Z File "/opt/python/3.11.8/lib/python3.11/importlib/__init__.py", line 126, in import_module 2024-05-03T06:02:12.640955059Z return _bootstrap._gcd_import(name[level:], package, level) 2024-05-03T06:02:12.640957959Z ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-05-03T06:02:12.640960859Z File "<frozen importlib._bootstrap>", line 1204, in _gcd_import 2024-05-03T06:02:12.640964759Z File "<frozen importlib._bootstrap>", line 1176, in _find_and_load 2024-05-03T06:02:12.640967959Z File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked 2024-05-03T06:02:12.640971159Z File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 2024-05-03T06:02:12.640974259Z File "<frozen importlib._bootstrap>", line 1204, in _gcd_import 2024-05-03T06:02:12.640977359Z File "<frozen importlib._bootstrap>", line 1176, in _find_and_load 2024-05-03T06:02:12.640980360Z File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked 2024-05-03T06:02:12.640984160Z ModuleNotFoundError: No module named 'trplbackend' This is my start up command: gunicorn --bind=0.0.0.0 --timeout 600 trplbackend.wsgi:application My project … -
Error Supabase hosting: django.db.utils.OperationalError: Tenant or user not found
I am trying to host my PostgreSQL database on Supabase from my Django project. I had success a few weeks ago with the same tech stack. I think the problem has to do with using django dotenv, but I followed the same steps and updated the same code as my last project. The error message: django.db.utils.OperationalError: connection to server at "aws-0-us-west-1.pooler.supabase.com" (52.8.172.168), port 5432 failed: FATAL: Tenant or user not found If I put the password directly in settings.py, it will connect to Supabase no problem but it doesn't feel secure to have the password commited to Github. If I put the info directly into the terminal shell, I'm able to access the database and make queries no problem. Once I use dotenv, it won't connect. Here is the code: from dotenv import load_dotenv import os load_dotenv() ... 'USER': str(os.getenv('SUPA_USER')), 'PASSWORD': str(os.getenv('SUPA_PW')), -
How to configure Daphne channels in Nginx server
I have a Django application that serves both http and websocket requests. The application is working properly in local. I have configured gunicorn and daphne services in Nginx server but Daphne service stops automatically within few seconds of starting even if request is not made. As a result websocket connection is not made. I am facing this error since few months and tried various solutions available but nothing works. /etc/nginx/sites-available/myapp upstream websocket{ server 0.0.0.0:8001; } server { listen 80; server_name mydomain.com; location = /favicon.png { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/projects/my_app; } # WSGI location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } # ASGI location /ws/ { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Origin "ws://domain.com:8001"; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/projects/my_app ExecStart=/home/ubuntu/projects/my_app/env/bin/gunicorn \ --access-logfile - \ -k uvicorn.workers.UvicornWorker \ --workers 3 \ --bind unix:/run/gunicorn.sock \ my_app.asgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/daphne.service [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=ubuntu WorkingDirectory=/home/ubuntu/projects/my_app ExecStart=/home/ubuntu/projects/my_app/env/bin/python /home/ubuntu/projects/my_app/env/bin/daphne -b 0.0.0.0 -p 8001 my_app.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target sudo systemctl status daphne.service ● daphne.service - … -
`request` parameter in Django - HTTPRequest or WSGIRequest
All of Django documentation says request is of type django.http.request.HTTPRequest. I use NGINX -> Waitress WSGI in my development, and I see see request is django.core.handlers.wsgi.WSGIRequest which inherits directly from HTTPRequest. I understand that Django must always run under WSGI, if so a request will always be WSGIRequest. So why does Django documentation always use HTTPRequest? -
CSS loaded but failed to apply when using Django
These are my folders: folders: my setting.py: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'blog','static'), ] my html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lexie's blog</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> Bootstrap is working but the stylesheet I wrote won't override the Bootstrap. I have tried to install whitenoise which fixed my previous MIME problem. And I have tried to change the static path. Also, python manage.py collectstatic was tried. I have checked the network using inspect, when refreshing page, it does show the blog.css has been loaded with 200 GET. And when clicking the URL 127.0.0.1:800/static/css/blog.css, it will show the source code of blog.css I am using my localhost and I have checked the way it interpret css, it is text/css, so I think there is no problem with interpreting. I don't know how to do it, please help T^T -
Why does my Django URL parameter result in an error?
I am a Django noob and this is my first post in stackoverflow. I need help in fixing my code. It was working well previously until I got an error regarding URL parameters as I tried adding an image for each person object using a foreign key. I'd like to improve with the help of your feedback. Please let me know if you have an idea of what changes I can do to make this project work. This is my code from the different django files: models.py class Person(models.Model): person_text = models.CharField(max_length=200) def __str__(self): return self.person_text class PersonDetail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) person_subtext = models.TextField() def __str__(self): return f"{self.person_subtext[:50]}..." class PersonImage(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) name = models.CharField(max_length=200) image = models.ImageField(upload_to='images/') def __str__(self): return self.name urls.py app_name = 'galleries' urlpatterns = [ # Home page path("", views.index, name="index"), # Page that shows all persons. path('persons/', views.persons, name='persons'), # Detail page for a single person. path('persons/<int:person_id>/<int:personimage_id>/', views.person_detail, name='person_detail'), # Page that shows all events. path('events', views.events, name='events'), # Detail page for a single event. path('events/<int:event_id>/', views.event_detail, name='event_detail'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def index(request): """The home page for History Gallery.""" return render(request, 'galleries/index.html') def persons(request): """Show all persons.""" persons = … -
Problem when styling django form fields upon errors
I have a bug I've been trying to fix for months but can't figure out. I'm building a website with Django. The site has a form, that, among other fields, has a field to input the name (called "nombre") and a field for the last name (called "apellido") of the user. I've declared a CSS rule (applied to the fields with the class "error" that gives a specific style to the fields that didn't pass the form validation, highlighting them in red. In a "forms.py" file, I wrote some code that assigns the class "error" to the fields that did not pass the validation. The problem is that, when I input invalid data into the "apellido" field and try to submit the form, both de "apellido" and "nombre" fields get highlighted in red. I have no clue why this could be happening. I figure it must be something with the "forms.py" file, where I assign the "error" class to the invalid fields. Here is the code of the "forms.py" file: from django import forms from .models import Turno class TurnoForm(forms.ModelForm): class Meta: model = Turno fields = ['nombre', 'apellido', 'email', 'fecha', 'hora'] widgets = { "nombre": forms.TextInput(attrs={"class": "form-control", "name": "nombre"}), … -
Dockerizing django app with Nginx, gunicorn and docker-compose - data base connectivity issue
Amateur programer here. I usually can google my way out of every issue but I struggle with the huge diversity in set ups for docker (and honestly feel al ittle overwhelmed). I am aware the the biggest tutorials out there (including the famous digitalocean one), but it didn't help. As title says, I am trying to dockerize a django app (in order to deploy to a VPS) using Nginx en gunicorn. My docker-compose file has a data base service, a django_unicorn service and a nginx container. The data base and nginx containers seem to set up correctly. But when my django_unicorn runs, in fails to connect to the data base. The error message is : django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno 111] Connection refused)")] After a while, it stops and gives me the localhost server to connect to, but it obviously shows nothing. I tried checking on the data base within my docker container. It is working fine and I connect within it with root user and my custom user. I uses the exact same credentials in my settings.py file in django. The HOST and PORT look ok to me (referring the db service in docker-compose … -
Override CSS when Debug=True
In order to avoid confusion between my production and development instance (where DEBUG = True), I'd like to override the CSS of my bootstrap Navbar in development (only) to show up e.g. in red instead of blue. What is the most elegant way to accomplish this? I can override get_context_data() everywhere to include my settings.DEBUG, or inherit from a newly generated base classes, but that doesn't seem very DRY. -
Display a converted .docx to PDF file from Django REST framework backend in React frontend
I am running a django REST framework backend and a React frontend. I want to convert a .docx to PDF bytes in the backend and display it on the frontend but I keep getting Failed to load PDF Document error. I have tried several pdf modules and different methods to display the PDF bytes in the frontend but I keep getting the same error. I will really appreciate any help . Below is what I came up with: views.py from docx import Document @api_view(['POST']) def viewFile(request): data = request.data file = File.objects.get(id=data['id']) try: pdf_bytes = convert_file_to_pdf(file) pdf_base64 = base64.b64encode(pdf_bytes).decode('utf-8') return Response({'pdf_base64': pdf_base64}) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def convert_file_to_pdf(file): if file: if file.filename.endswith('.docx'): doc = Document(file.file) pdf_bytes = BytesIO() doc.save(pdf_bytes) pdf_bytes.seek(0) return pdf_bytes.read() elif file.filename.endswith('.xlsx'): wb = load_workbook(file.file) # Convert to PDF using appropriate method (e.g., Excel to PDF) # Return PDF bytes elif file.filename.endswith('.pptx'): prs = Presentation(file.file) # Convert to PDF using appropriate method (e.g., PowerPoint to PDF) # Return PDF bytes else: raise ImproperlyConfigured("Unsupported file format") else: raise ImproperlyConfigured("File not found") DocumentViewer.js function DocumentViewer() { const [fileId,] = useState('327'); const [pdfUrl, setPdfUrl] = useState(null); useEffect(() => { const getPdf = async () => { try … -
How to store my user-uploaded files on Digital Ocean Spaces using django-storages?
I am totally new to this. My Django app is run in Docker. My app allows users to upload files which are stored, followed by executing some functions on the file then generating a new file that the user can download. I'd like to store the initial user-uploaded file and the output-file my django code generates. Here is my code: models.py: class TranscribedDocument(models.Model): id = models.CharField(primary_key=True, max_length = 40) audio_file = models.FileField(upload_to='ai_transcribe_upload/', null= True) output_file = models.FileField(null= True) date = models.DateTimeField(auto_now_add=True, blank = True, null=True) views.py: #save uploaded file if form.is_valid(): uploaded_file = request.FILES['file'] request.session['uploaded_file_name'] = uploaded_file.name request.session['uploaded_file_size'] = uploaded_file.size#add to models.py session_id = str(uuid.uuid4()) request.session['session_id'] = session_id transcribed_doc, created = TranscribedDocument.objects.get_or_create(id=session_id) transcribed_doc.audio_file = uploaded_file transcribed_doc.save() request.session['uploaded_file_path'] = transcribed_doc.audio_file.path #generate new file with open(file_location, 'r', encoding=charenc) as f: file_data = f.read()## transcribed_doc, created = TranscribedDocument.objects.get_or_create( id = request.session['session_id'] ) transcribed_doc.output_file = transcript_path transcribed_doc.date = timezone.now() transcribed_doc.save() settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", # set in docker-compose.yml "PORT": 5432, # default postgres port } } AWS_ACCESS_KEY_ID = 'key_id' AWS_SECRET_ACCESS_KEY = 'secret_key_id' AWS_STORAGE_BUCKET_NAME = 'name' AWS_DEFAULT_ACL = 'public-read' #change to private AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com/' # Make sure nyc3 is correct AWS_S3_OBJECT_PARAMETERS = …