Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Polars Read Excel file from Form (ie. request.FILES.get('file'))
All the Polars examples show reading an Excel file from a path string. df = pl.read_excel("docs/assets/data/path.xlsx") But I am passing in the Excel file from a Django Form Post. file_name = request.FILES.get('file') df = pl.read_excel(file_name) I am getting a "InvalidParametersError". How do input the file to Polars from a HTML form? or do I somehow have to get the path from the request.FILES and use that? I am new to the whole Polars thing but very excited to try it. thank you. -
How to hide webapi url and show a "pretty" url?
I need to generate a pretty URL for my own URL shortening service. My web server address looks something like https://my-backend-api-server.us-central1.run.app/redirectapp/redirect/wAzclnp3 and I wouldn't want to expose that, nor is it short. I want to "prettify" my URLs. How to do this in django assuming I have a domain www.mydomain123.com? -
Not able to deploy my Django application on Google Cloud Run
i need some help with my django docker deployment, so ill show you what I currently have and I need your help now configuring it to run with nginx and gunicorn so I can eventually use this to deploy my application with google cloud run. I'm using a mac btw okay so here is my directory: Dockerfile carz docker-compose.yml nginx static carszambia db.sqlite3 manage.py requirements.txt staticfiles docker-compose.yml: version: '3.8' services: web: build: context: . command: gunicorn carszambia.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/usr/src/app - static_volume:/usr/src/app/staticfiles expose: - "8000" env_file: - ./.env.dev depends_on: - db nginx: image: nginx:latest volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static_volume:/usr/src/app/staticfiles ports: - "8001:80" depends_on: - web db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=xxx_hidden - POSTGRES_PASSWORD=xxx_hidden - POSTGRES_DB=xxx_hidden volumes: postgres_data: static_volume: Dockerfile: # pull official base image FROM python:3.11.4-slim-buster # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update && apt-get install -y \ nginx \ && rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . # configure nginx COPY ./nginx/default.conf /etc/nginx/conf.d/ # Expose port for Nginx EXPOSE 80 # Start Gunicorn and … -
Event.preventDefault is not working in JS for form submission
// js document.addEventListener("DOMContentLoaded", function () { const individualOrderForm = document.getElementById('individual-order-form'); async function sendAjax(form) { try { const response = await fetch(form.action, { method: 'POST', body: new FormData(form) }); const data = await response.json(); if (data.status === "success") { showToast(data.detail, "success"); disableForm(form); } else { let errors = JSON.parse(data.errors); let errorsText = Object.entries(errors) .map(([field, errors]) => { return errors.map(error => `${error.message}`).join('\n'); }) .join('\n'); showToast(`${data.detail}\n${errorsText}`, "danger"); } } catch (error) { console.log(error); showToast(gettext("Произошла ошибка. Повторите попытку позже."), "danger"); } } individualOrderForm.addEventListener( 'submit', function (e) { e.preventDefault(); sendAjax(individualOrderForm); }, {passive: false} ); } ); <form id="individual-order-form" action="{% url 'mainpage:individual-order-negotiate' %}" method="POST" class="d-flex w-100 flex-column justify-content-start align-items-start text-start card-body"> <fieldset class="w-100"> <legend class="text-center"> <h2 class="fs-4 fw-normal" id="contact-us"> {% translate 'Свяжитесь с нами' %} </h2> </legend> <div class="form-text">{% translate 'Заполните форму, чтобы заказать букет из индивидуального состава.' %}</div> {% csrf_token %} <div class="mb-3 w-100"> <label for="customerNameInput" class="form-label">{% translate 'Имя' %}</label> <input class="form-control text-start" id="customerNameInput" aria-describedby="nameHelp" name="first_name" required> </div> <div class="mb-3"> <label for="contact-method-input" class="form-label"> {% translate 'Тел. номер в любой соц. сети или ссылка профиля' %} </label> <div class="d-flex"> {{ individual_order_form.contact_method }} </div> </div> <div class="mb-3 form-check"> <input type="checkbox" class="form-check-input checkbox-dark" id="recallCheckbox" name="recall_me"> <label class="form-check-label" for="recallCheckbox"> <small> {% translate 'Разрешаю мне перезвонить' %} </small> </label> </div> … -
How can I use multiple routers for a Django Rest Framework project?
I am facing a hard time on trying to use a router for an app and another for another app. # api/urls.py from django.urls import path, include from .views import UserViewSet, DepartmentViewSet, UserLoginView, UserTokenRefreshView router = DefaultRouter() router.get_api_root_view().cls.__name__ = "E.R.P. API" router.get_api_root_view().cls.__doc__ = "API do ERP" router.register('users', UserViewSet, basename='user') router.register('departments', DepartmentViewSet, basename='department') app_name = 'api' urlpatterns = [ path('login/', UserLoginView.as_view(), name='login'), path('token/refresh/', UserTokenRefreshView.as_view(), name='token_refresh'), path('', include(router.urls)), path('history/', HistoryView.as_view(), name='history'), ] # mobile_app/urls.py from django.urls import path, include from .views import CustomerLoginView mobile_app_router = DefaultRouter() mobile_app_router.get_api_root_view().cls.__name__ = "Mobile App API" mobile_app_router.get_api_root_view().cls.__doc__ = "API do Aplicativo Mobile" app_name = 'mobile_app' urlpatterns = [ path('login/', CustomerLoginView.as_view(), name='login'), path('', include(mobile_app_router.urls)) ] # erp/urls.py from django.contrib import admin from django.urls import path, re_path, include from . import settings from django.conf.urls.static import static from notifications import urls as notifications_urls urlpatterns = [ path('api/', include('api.urls'), name='api'), path('api/m/', include('mobile_app.urls'), name='api_mobile'), path('', admin.site.urls), re_path(r'^inbox/notifications/', include(notifications_urls, namespace='notifications')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The name and doc are being mixed, if I try to use a swagger or redoc (drf_yasg) the urls are mixed. It is like they are the same. How can I do it corectly? I tried to use multiple routers for a Django Rest Framework and … -
django-crispy-forms split form in two divs layout
I want to split a form into two divs with their own css_id so I can ajax update second div based on choices in the first. Problem is that my resulting form does not have divs with ids 'pbid' and 'pb-options' class PBForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.layout = Layout( Div('cc', 'pb_id', css_id="pbid"), Div('closed_r', 'closed_l', css_id="pb-options") ) pb_id = forms.ChoiceField(label='PB', widget=forms.RadioSelect) closed_l = forms.ChoiceField(label='Left Closed', widget=forms.RadioSelect, choices=BOOL_CHOICES) closed_r = forms.ChoiceField(label='Right Closed', widget=forms.RadioSelect, choices=BOOL_CHOICES) class Meta: model = pb fields = ['cc', 'pb_id', 'closed_r', 'closed_l'] -
Django Diagnosis Data Not Appearing in Admin After Endpoint Execution
I am working on a Django project where I process mock patient data and save it to a DiagnosisResult model in the database (SQLite). The goal is for this data to appear in the Django admin interface, but after calling the endpoint, the data doesn't appear in the database or admin. By "mock," I mean fictional data (not testing framework mocks), which I pre-generated to avoid using real patient data. Hers is my Minimal Reproducible Example (In order: models.py, views.py, urls.py, sample JSON data, Dockerfile, docker-compose.yml): models.py from django.db import models class Subtype(models.Model): CATEGORY_CHOICES = [('Acute', 'Acute'), ('Chronic', 'Chronic')] category = models.CharField(max_length=20, choices=CATEGORY_CHOICES) name = models.CharField(max_length=100) def __str__(self): return self.name class DiagnosisResult(models.Model): patient_name = models.CharField(max_length=100) age = models.IntegerField() symptoms = models.TextField() # Comma-separated list of symptoms test_results = models.TextField() likely_diagnoses = models.ManyToManyField(Subtype) def __str__(self): return f"{self.patient_name} (Age: {self.age})" views.py import json from pathlib import Path from django.http import JsonResponse from .models import Subtype, DiagnosisResult # File paths IS_DOCKER = Path("/app").exists() # Check if running inside Docker MOCK_DATA_FILE = ( Path("/app/apps/diagnosis/mock_data/mock_diagnosis_inputs.json") if IS_DOCKER else Path(__file__).resolve().parent / "mock_data" / "mock_diagnosis_inputs.json" ) def process_and_save_mock_diagnoses(request): with open(MOCK_DATA_FILE, "r") as file: mock_data = json.load(file) results = [] for patient in mock_data: likely_subtypes = Subtype.objects.filter(category="Acute") diagnosis_result … -
Django display edited time only for edited comments
This is my model for Comment class Comment(models.Model): content = models.TextField() dt_created = models.DateTimeField(auto_now_add=True) dt_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") def __str__(self): return f"Comment by {self.author.username} on {self.post.title}" and I am trying to display edited time if edited time != created time in the template <div class="comment"> <div class="comment-meta"> {{comment.author.nickname}} | Date: {{comment.dt_created|date:"M, d Y H:i"}} {% if comment.dt_created != comment.dt_updated %} | Last edited: {{ comment.dt_updated|date:"M d, Y H:i" }} {% endif %} </div> <div class="comment-content">{{comment.content}}</div> </div> ... But somehow it is displaying dt_updated for all comments even the ones that are not edited. I tried changing the code to check if it displays date when dt_created==dt_updated and it actually didn't display the edited time for all comments, including the comments that were edited. I also tried using comment.edited and it also didn't display edited time for all comments. What is wrong with my code? -
How to call and process Confirmation popup from a service function without interrupting the transaction
In my Django project, the business logic is placed in the service layer. Views only perform the function of working with templates. I have a basic template with a form and select type fields on it. When any field is changed, the script sends an AJAX request to views. views accepts this request and passes the data to a service function that uses it to write to the DB. template -> views -> service -> model Now I need to make a function to call the Confirmation popup from service to confirm the data change, receive a response from the window and process it. I already have a modal window and a script that calls it when response.confirmation_dialog. I need a mechanism for calling this window from the service without interrupting the transaction. One of the implementation options was to send a response to template with a confirmation modal call. Clicking the confirm-button on it would again send an AJAX request to views with confirmation information. Then this information would be sent back to the service, which checked whether the confirmation was passed or not. However, even with one confirmation, it looks bad, and the service may need several checks … -
Implementing Offline Updates for a Django REST Framework Project - Best Approach?
I'm building a Django REST Framework (DRF) application and am exploring ways to handle offline updates for my users. The goal is to allow users to access updated version of my project with a flash usb or something like that. as my clients does not have any special technical knowledge(like how to pull a repo or even how to deploy a project on their servers) i need to provide an easy way to let them update and use latest features. Now specifically, I'd like to know: Best practices for implementing offline updates in a DRF project Recommended libraries or frameworks to simplify this process Tips for managing data synchronization and version control for offline updates -
How can i calculate the task estimation in agile project management ? and how can i do it in code or can what dataset i use for it?
me and my team work on a project EI scrum planner it's important features that it can detect your emotions and give your task about it and the the important feature that we estimate the task in AI that it will automatically learn from the past tasks that have been estimated from the previous 2 sprints so i want to ask about this point how can i do the estimation of task i know something like calculate it with Pert law but is there any dataset that could i use instead of make my dataset? it is my graduation project i know something like calculate it with Pert law -
Extra "[]" characters appearing before login fields for django admin
On my Django admin login page I see extra "[]" before the username and password fields: and I really cannot figure out where they are coming from. I'm using Django v5.1.3 and I haven't made any extra customisations to the django admin, so it should only be loading the default CSS and JS that the admin site natively comes with. It happens on both Brave and Firefox browsers. I'd really like to get rid of these, but have no idea where to start... let me know if any extra code/settings would be helpful to figure out. Any help much appreciated. -
Django session key not found using str(instance.id)
This is my scenario I have a signal on cart apps which is raised when admin delete a product in django but searching for the product key in the session is not working below is the code that I'm using from django.db.models.signals import post_delete from django.dispatch import receiver from store.models import Product from django.contrib.sessions.models import Session @receiver(post_delete, sender=Product) def update_cart_on_product_delete(sender, instance, **kwargs): # Get all sessions for session in Session.objects.all(): data = session.get_decoded() print(data) if str(instance.id) in data: print(f"Instance ID {instance.id} found in cart") print(instance.id) del data[str(instance.id)] session['cart'] = data session.save() else: print(f"Instance ID {instance.id} not found in cart") And on the terminal when I get the result it appear like this {'session_key': {'47': 1}} Instance ID 47 not found in cart as you can see clear the INSTANCE.ID is in the cart '47' but django code is not able to find it even that I'm converting the key to str. Pls someone help me on this. -
How to display Field Quill in Django Views?
For my forum I am trying to use Quill Rich Text editor to format my Posts and comments. class Topic(models.Model): title = models.CharField(max_length=70, blank=False, null=False) description = QuillField(default="") And managed to create some content <class 'django_quill.fields.FieldQuill'> This is how it looks on admin form I have tried display it in views using <div class="">{{topic.description.html| safe}}</div> This is how it looks in Views I am using django-quill package enter link description here I have included all the style and script tags as recommended and still the styles are not applying. Any ideas how I can display the content as is. I have tried: Converting the delta type {"ops":[{"attributes":{"bold":true},"insert":"dqwdqwdqdqdq"},{"insert":"\n"}]} into html before saving the model. failed with error TypeError: 'FieldQuill' object is not subscriptable Please recommend reliable packages to convert delta to html or display the content with all formatting. TIA -
How would you ignore a trigger within another trigger with django-pgtrigger
I am updating tbla."field_2" from a trigger in tblb. Except tbla."field_2" is protected with a pgtrigger.ReadOnly trigger. This works without the pgtrigger.ReadOnly trigger in TblA. How would I do it and keep the pgtrigger.ReadOnly trigger on TblA.field_2? Model TblA(models.Model): field_1 = models.CharField(max_length=20) field_2 = models.PositiveIntegerField(default=0) class Meta: triggers = [ pgtrigger.ReadOnly( name='read_only_field_2', fields=['field_2'] ) ] class TblB(models.Model): field_a = models.ForeignKey(TblA, on_delete=models.SET_NULL) class Meta: pgtrigger.Trigger( func=pgtrigger.Func(''' IF (NEW."{columns[field_a]}" IS NOT NULL) THEN UPDATE "tbla" SET "tbla"."field_2" = "tbla"."field_2" + 1 WHERE "tbla"."id" = NEW.{columns[field_a]} END IF; RETURN NEW; ''') ), when=pgtrigger.Before, operation=pgtrigger.Insert, name='increment_tbla_field_2' ), I was thinking to mimic pgtrigger.ignore() functionality within the trigger by using set_config however I am not very familiar how persistent set_config is. Do I need to clean up at the end of the trigger? Is this doable? set_config('pgtrigger.ignore', '{myapp:pgtrigger_read_only_field_2_c8215,pgtrigger_read_only_field_2_c8215}', true) -
update the status of a buy a product button when we have more than one of that product in page with JavaScript in a Django app
I am Tring to update a buy button base of the quantity of the colors on that product in my django app with javaScript my code is working if i have one from that item in my page but some where in code when i have some swiper to show favorite products must sell products or must see products i have same item in diffrent places and when i try to chnage the color of the products it change the first one of the kind of this prodcut in page i have this view to check the product color quantity : def quantity_of_product_with_color(request): color_id = request.GET.get('color') try: product_color = ProductColor.objects.get(id=color_id) data = { 'in_stock': product_color.quantity > 0, 'quantity': product_color.quantity } except ProductColor.DoesNotExist: data = { 'in_stock': False, 'quantity': 0 } return JsonResponse(data) and for exampel i have this html code : {% for item in discounted_products %} <div class="swiper-slide"> <div class="product-box"> <div class="product-timer"> <div class="timer-label"> <span>{{ item.discount }}% تخفیف</span> </div> <div class="timer"> <div class='countdown' data-date="{{ item.offer_end.date|date_convertor }}" data-time="{{ item.offer_end.time|time_convertor }}"> </div> </div> </div> <div class="product-image"> <img src="{{ item.images.all.0.image.url }}" loading="lazy" alt="{{ item.images.all.0.image_alt }}" class="img-fluid p-2"> </div> <div class="product-title"> <div class="title"> <p class="text-overflow-1">{{ item.name }}</p> <span class="text-muted text-overflow-1"></span> </div> <div class="rating"> … -
DRF auth via Azure AD
Which Python package do you recommend for implementing authentication via Azure AD in a Django Rest Framework (DRF) project? So far, I have tried two packages, but both had issues: django-azure-auth: This package didn't display the login endpoints, making authentication impossible. django_auth_adfs: I had issues with configuration. I kept getting errors regarding the CLAIM_MAPPING and USERNAME_CLAIM properties. -
How to share the data folder from website to google drive
1.I am clueless to approach the problem to share the folder data information via a to google drive with an expiry date and time.So If can one have worked on this API's can help me out it can be any programming language just need the work flow to reach the approach.As per my company organization we are working on python language with Django Framework(DRF) and help me out which library we can use for this. 2. sharing the data happening via link, which is the library to share and save drive folder using python and django , as a backend how to send this data in payload and facing an issue to share the folder information(data) through the api. 3. if the user want to share some folder or save that folder in his google drive than how to send the payload response. Nothing................................. -
Django Deployment Code Execution Error vs Local Correct Execution
in my local server ( windows ) my project works fine, when i send a month from the filter via post request to my backend view it does its processing however in deployment (linux based server ) that requests somehow turns into a get request and doesnt send anything. We use ajax to send the request via fetch(url) Any assistance would be greatly appreciated I tried changing the csrf and cors and header values being sent to the linux server in order to bypass the error but nothing happens. Gunicorn Configuration [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target --- [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=root WorkingDirectory=/home/zeritek/cras ExecStart=/home/zeritek/cras/venv/bin/gunicorn \ --access-logfile /var/log/gunicorn-access.log --error-logfile /var/log/gunicorn-error.log \ --workers 3 \ --timeout 3000 \ --threads 3 \ --keep-alive 3000 \ --worker-class gevent \ --bind unix:/run/gunicorn.sock \ Extraction.wsgi:application [Install] WantedBy=multi-user.target Nginx Configuration server { listen 80; server_name 1440.25554.1555.4266; client_body_timeout 300; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/zeritek/cras; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; proxy_read_timeout 600; # Increase this value proxy_send_timeout 600; # Increase this value proxy_connect_timeout 600;# Increase this value } } -
Django Celery. Publush post on publish_date
I have a Post model. There is a field publish_date. If the post has a planned status, then i need to perform the publishing function on the publish_date. How can I do this? models.py: class Post(models.Model): STATES = ( ('draft', 'Draft'), ('published', 'Published'), ('planned', 'Planned') ) state = models.CharField(choices=STATES, default=STATES[0][0]) channels = models.ManyToManyField('channel.Channel') creator = models.ForeignKey('authentication.User', on_delete=models.SET_NULL, null=True) publish_date = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @receiver(post_save, sender=Post) def reschedule_publish_task(sender, instance, **kwargs): # There should be a task setting for a specific time here, as I understand it I tried to do this, but it didn't work, the task is not completed. models.py @receiver(post_save, sender=Post) def reschedule_publish_task(sender, instance, **kwargs): task_id = f"publish_post_{instance.id}" if instance.state == 'planned' and instance.publish_date: publish_post.apply_async((instance.id,), eta=instance.publish_date, task_id=task_id) tasks.py @shared_task def publish_post(post_id: int) -> None: from .models import Post post = Post.objects.filter(id=post_id).first() if post: if post.state == 'planned' and post.publish_date <= now(): post.state = 'published' post.save() -
TypeError: 'type' object is not subscriptable with prefetch_related
I’m trying to return a specific queryset using prefetch_related to optimize future queries, but I’m encountering an issue. When I don’t specify a return type, the code works fine. However, I want to understand the actual return type and what’s happening when I specify the return type as QuerySet[ABCInstance]. Here’s the code I’m working with: def _fetch_abc_instances(self) -> QuerySet[ABCInstance]: # Prefetch related "cde_instances" to avoid N+1 query issues return self.xyz_instance.abc_instances.prefetch_related("cde_instances") In this case: xyz_instance has a one-to-many relationship with abc_instances. abc_instances has a one-to-many relationship with cde_instances. My current environment: Python 3.6.7 Django 2.0.2 I’m expecting the return type to be ABCInstance, but since the query involves prefetching related data, the actual return type is different. I’d like to understand what the actual return type is in this case. -
Query for filter blogpages by category in wagtail graphiql
Help please if i have blog category relationship then how can i fetch blogs by category. Anyone know query for that. i am using wagtail grapple If i want to fetch blogs by category id or slug how can i do what is the graphiql query for that This is my models page = ParentalKey( "BlogPage", related_name="blog_category_relationship", on_delete=models.CASCADE ) category = models.ForeignKey( "base.Category", related_name="category_blog_relationship", on_delete=models.CASCADE ) panels = [FieldPanel("category")] @register_paginated_query_field("blogpage") class BlogPage(Page): introduction = models.TextField(help_text="Text to describe the page", blank=True) image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", help_text="Landscape mode only; horizontal width between 1000px and 3000px.", ) body = StreamField( BaseStreamBlock(), verbose_name="Page body", blank=True, use_json_field=True ) subtitle = models.CharField(blank=True, max_length=255) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) date_published = models.DateField("Date article published", blank=True, null=True) content_panels = Page.content_panels + [ MultipleChooserPanel( "blog_category_relationship", chooser_field_name="category", heading="Categories", label="Category", panels=None, min_num=1, ), FieldPanel("subtitle"), FieldPanel("introduction"), FieldPanel("image"), FieldPanel("body"), FieldPanel("date_published"), MultipleChooserPanel( "blog_person_relationship", chooser_field_name="person", heading="Authors", label="Author", panels=None, min_num=1, ), FieldPanel("tags"), ] graphql_fields = [ GraphQLCollection( GraphQLForeignKey, "categories", "base.Category" ), GraphQLString("subtitle"), GraphQLString("introduction"), GraphQLString("image_url"), GraphQLStreamfield("body"), GraphQLString("date_published"), GraphQLString("tags"), GraphQLCollection( GraphQLForeignKey, "authors", "base.Person" ), ] search_fields = Page.search_fields + [ index.SearchField("body"), ] -
Trying to connect my backend to my frontend
EditTransaction.js import React, { useEffect, useState } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; export default function EditTransaction() { const params = useParams() const [initialData, setInitialData] = useState() const [validationErrors, setValidationErrors] = useState({}) const navigate = useNavigate() function getTransaction() { fetch("http://127.0.0.1:8000/transactions/" + params.id) .then(response => { if (response.ok) { return response.json() } throw new Error() }) .then(data => { setInitialData(data) }) .catch(error => { alert('Unable to read the Transaction details') }) } useEffect(getTransaction, [params.id]) async function handleSubmit(event) { event.preventDefault() const formData = new FormData(event.target) const Transaction = Object.fromEntries(formData.entries()) if (!Transaction.name) { alert("Please fill the Name field") return } try { const token = '852de93b4848505296fb5fe56e41a6d1501adfca'; const response = await fetch("http://127.0.0.1:8000/transactions/" + params.id, { method: 'PATCH', body: formData, headers: { 'Authorization': `Token ${token}` }, }); const data = await response.json() if(response.ok){ //Transaction Created Correctly! navigate('/admin/transaction') } else if (response.status === 400){ setValidationErrors(data) } else( alert('Unable to Update Transaction') ) } catch(error) { alert('Unable to connect to the server') } } return( <div className="container my-4"> <div className="row"> <div className='col-md-8 mx-auto rounded border p-4'> <h2 className= "text-center mb-5">Edit Transaction</h2> <div className="row mb-3"> <label className='col-sm-4 col-form-label'>ID</label> <div className= 'col-sm-8'> <input readOnly className='form-control-plaintext' defaultValue={params.id}/> </div> </div> { initialData && <form onSubmit={handleSubmit}> <div className="row … -
Images do not appear on a page even though they are already in a DB (Django)
I try to learn how to deploy my django project. I have a form in which user can upload his image. The image is a content for ImageField of a Recipe model. Uploading process is working as expected but when I try to display these pictures on the page they just dont appear. Here's my code: settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py (project one): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('auth/', include('user_auth.urls')), path('main/', include('main_app.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py: class Recipe(models.Model): author = models.ForeignKey(UserExtended, on_delete=models.CASCADE, related_name='recipies') title = models.CharField(max_length=150, null=False) category = models.ForeignKey(RecipeCategory, related_name='recipies', on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to="images/", null=False) short_description = models.CharField(max_length=250, null=False) tutorial = models.TextField(null=False, default='') uploaded_on = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(UserExtended, related_name='liked_recipies') likes_count = models.SmallIntegerField(default=0) def __str__(self): return f'{self.author} {self.title}' example of my template: <img class="full-recipe-image" src="{{ recipe.image.url }}" alt="Фото блюда"> Any help would be a blessing to me since I'm pretty desperate. I tried to alter my urls.py and was struggling with MEDIA_ROOT / MEDIA_URL problem -
404: NOT_FOUND error on Vercel - Django deployment
I deployed a Django project on Vercel and it shows the deployment is successful. However, when I try to open the website, it shows the error: 404: NOT_FOUND Code: NOT_FOUND ID: lhr1:lhr1::6n29s-1732227821846-0cc9eddbb440 My Django project can be found in the following link: https://github.com/RailgunGLM/railgunglm-com I tried solving the problem by, as some solutions on stackoverflow suggested, inserting a vercel.json file and a build.sh file, adding the line app = application at the very end of wsgi.py, including .vercel.app in my ALLOWED_HOSTS in setting.py, and lastly, installed whitenoise. However, none of them seems to work. The application works normally in my local machine, but I'm not sure whether I made a mistake in one of these files. I would be really appreciated if there is a solution to fix this problem.