Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how webpack config file handle logo path when bundling frontend
I have a django project already build and running and i need to change its logo. I have updated the logo path in /static/js/header.jsx but change is not showing up in browser. I have cleared the browser cache. I am new to django and I am wondering if it has anything to do with webpack config file or something like that. Any one with any idea would help alot. Thanks Below is just code from /node/webpack.config.js not necessary related to my problem: var path = require('path'); var nodeExternals = require('webpack-node-externals'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var DeepMerge = require('deep-merge'); var nodemon = require('nodemon'); var fs = require('fs'); var deepmerge = DeepMerge(function (target, source, key) { if (target instanceof Array) { return [].concat(target, source); } return source; }); class WatchRunPlugin { apply(compiler) { compiler.hooks.watchRun.tap('WatchRun', (compilation) => { console.log('Begin compile at ' + new Date()); }); } } class CleanOldAssetsOnBuildPlugin { apply(compiler) { compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => { const newlyCreatedAssets = compilation.assets; const unlinked = []; console.log(path.resolve(buildDir + 'client')); fs.readdir(path.resolve(buildDir + 'client'), function (err, files) { if (typeof files === 'undefined') { return; } // we've started to see cases where files is undefined on cloudbuilds. adding this here as … -
Django async with AppConfig.ready sync/async
I am running Django version 4.2.4 in async mode. For one of my apps I have some code to run on ready like this: class CoreConfig(AppConfig): name = 'demo.core' def ready(self): from .utils import my_sync_func my_sync_func() When I run this code, I get the warning "RuntimeWarning: coroutine 'CoreConfig.ready' was never awaited" When I use sync_to_async like this: class CoreConfig(AppConfig): name = 'demo.core' async def ready(self): from .utils import my_sync_func await sync_to_async(my_sync_func)() I get the warning "RuntimeWarning: coroutine 'CoreConfig.ready' was never awaited" What is the correct way of doing this? Thanks a lot -
Filter using model field and reverse look up
I have two models Business: credit_officer Loan: Business disbursed() active() I want to get business who belong to a given credit_officer and have business.loan_set.active().count() == 1 This is how I was getting business for the given credit_officer but I don't know how to add the other condition business.loan_set.active().count() == 1 cro_businesses = ( Business.objects.filter(credit_officer=credit_officer_id) .values("id", "name", "credit_officer__id") .order_by("_created_at") ) -
Change the sort order with the dash being at the end of the query param
Instead of sorting like this /product/list/?sort=-price, I wish to sort like this /product/list/?sort=price-, where the dash character is placed at the end of the field name in the query param. In my views.py: from rest_framework.filters import OrderingFilter from rest_framework.generics import ListAPIView from rest_framework.response import Response from django.db.models import F from django_filters import rest_framework as filters from app.filters import ProductFilterSet from app.models import Product from app.serializers import ProductSerializer class ProductViewSet(ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter,) filterset_class = ProductFilterSet ordering_fields = ("date_updated", "price") def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def get_queryset(self): return super().get_queryset().annotate(date_updated=F("updated")) And in filters.py: from django_filters import rest_framework as filters from app.models import Product class ProductFilterSet(filters.FilterSet): class Meta: model = Product fields = { "category_id": ["exact"], "price": ["lt", "gt"], "is_available": ["exact"], } I tried adding a custom ordering filter, like this: class CustomOrderingFilter(OrderingFilter): def remove_invalid_fields(self, queryset, fields, view, request): # Remove the dash character from the end of the field name fields = [field.rstrip('-') for field in fields] return super().remove_invalid_fields(queryset, fields, view, request) class ProductViewSet(ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer pagination_class = … -
Send email using Django and Gmail backend
I'm struggling sending emails with a custom domain using Gmail backend. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"] EMAIL_HOST_PASSWORD = os.environ["EMAIL_HOST_PASSWORD"] EMAIL_PORT = 587 EMAIL_USE_TLS = True email = EmailMessage( subject, content, "myaccount@mydomain.com", [customer.email] ) email.send() I've created a Google account with the custom domain and generated an app password, but when using custom domain for EMAIL_HOST_USER, I get (535, b'5.7.8 Username and Password not accepted. Learn more at https://support.google.com/mail/?p=BadCredentials'): EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"] # myaccount@mydomain.com Then I tried with a Google account using a gmail.com domain, and this time it works: EMAIL_HOST_USER = os.environ["EMAIL_HOST_USER"] # myaccount@gmail.com So I need the sender's mail to be different than myaccount@gmail.com. I've tried to add a secondary mail address in Google, and used DEFAULT_FROM_EMAIL = "myaccount@mydomain.com" but it doesn't seem to change anything. I've also tried the solution from this post, same issue. -
Content Security Policy is set, but not detected
I have django-csp version 3.7 (https://pypi.org/project/django-csp/). It is added to the middleware section: MIDDLEWARE = [ 'csp.middleware.CSPMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And here's my settings: CSP_DEFAULT_SRC = ["'none'"] CSP_IMG_SRC = ["'self'"] CSP_STYLE_SRC = ["'self'", "'unsafe-inline'"] CSP_STYLE_SRC_ELEM = ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"] CSP_SCRIPT_SRC_ELEM = ["'self'", "'unsafe-inline'"] CSP_FONT_SRC = ["'self'", "data:", "https://fonts.googleapis.com", "https://fonts.gstatic.com"] I know that the above settings work because first I had lots of errors in the browser console and then all gone and the site works correctly. However, two sites checking the host headers (this one and this one) both report that my site is missing Content Security Policy. What I'm missing here? -
Django- filtering on ManyToMany field with exact matches
I have the following models: class Hashtag(models.Model): title = models.CharField(...) class Annotation(models.Model): ... hashtags = models.ManyToManyField(Hashtag) I want to get the Anntoations that have all [hashtag_1, hashtag_2, hashtag_3] as their hashtag. Following is my query: annotations = Annotation.objects.filter( hashtags__title__in=["hashtag_1", "hashtag_2", "hashtag_3"] ) This queryset, returns all annotation that have at least one of ["hashtag_1", "hashtag_2", "hashtag_3"] but I want to receive the annotations that have only these 3 hashtags (not more than and not less than these hashtags). How can I do that? I also tried the following query: annotations = Annotation.objects.annotate( hashtag_count=Count("hashtags") ).filter( hashtags__title__in=["hashtag_1", "hashtag_2", "hashtag_3"], hashtag_count=3 ) if an annotation has [hashtag_1, hashtag_2, hashtag_n], this query will return it (that is not what I want) -
converting a string to list of lists in java script
i have a list that i made using django and i passed it to index.html the problem is that i need to use it in the java script content but it is passed as a string to it and i tried JSON.parse but i got error message(Uncaught SyntaxError: Unexpected token 'F', "[[0, False], [0"... is not valid JSON) and here is the list:[[0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [0, False], [2, True], [2, True]] here is the html line: <div class="like-component" data-post-id="{{post.id}}" data-likes="{{likes}}"></div> and here is the java script part: function renderlikeposts(){ const likeComponents = document.querySelectorAll('.like-component'); likeComponents.forEach(component => { const postId = component.dataset.postId; const list = JSON.parse(component.dataset.likes); const likes = component.dataset.likes[postId-1][0]; const liked = Boolean(component.dataset.likes[postId-1][1]); ReactDOM.render(<Like postId={postId} likes={likes} liked={liked} list={list} />, component); }); } -
function on django object - server side
I have a django application and a corresponding API. Within the code for the application I have some functions and some computed fields that I am not exposing in the json returned through the API. If I am working locally, in the same location as the code, I can do something like this: from pythonfile.models import ModelClass pk = 'model-class-uuid' mc = ModelClass.objects.get(pk=pk) mc.the_function() My question is, can I do this on the server side? -
Django Celery Beat Periodic Tasks Running Twice
I trying to send scheduled emails to users but my Django celery periodic tasks running 2 times within a half-hour span. Every day I scheduled my email task at 7.00 AM but it is running 1st task at 7.00 AM and the same task is running at 7.30 AM also. Here is my celery app # coding=utf-8 from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings") app = Celery("app_name") app.config_from_object("app_name.celeryconfig") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print ("Request: {0!r}".format(self.request)) Celery app config # coding=utf-8 import os PROJECT_APP_PATH = os.path.dirname(os.path.abspath(__file__)) # Celery Config BROKER_URL = 'redis://redis_server:6379' CELERY_RESULT_BACKEND = 'redis://redis_server:6379' CELERY_TASK_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['application/json'] # Ignore other content CELERY_RESULT_SERIALIZER = 'json' CELERY_ENABLE_UTC = True CELERY_TASK_RESULT_EXPIRES = 0 # Never expire task results CELERY_IGNORE_RESULT = True CELERY_TRACK_STARTED = True CELERY_IMPORTS = ( "module.tasks" ) Periodic Tasks scheduled in Django admin panel Functionality working fine but these tasks are running twice daily for 2 to 3 days and after that, it will run once but if I restart celery then It will start running tasks again twice for some days. Please let me know If I'm missing in celery configuration. -
How can I connect the mayanedms api to my django project?
I would like to connect MayanEdms api to my Django project. Note that mayan is running on different port from my Django container (both are running Docker). The problem I'm having is because, if I navigate to the api link, it works for me, but if I do it through code it doesn't. I don't know why that is? I attach below the error that I get both in the browser and in the command console. I also attach the function that should connect to the API. What I want this function to do is to list all the documents that arrive to my email (it is read with MayanEdms). Once the documents are saved in Mayan, I want to show the information of the emails, including the attached files, in the independent interface that I have made with django. views.py: @login_required def f_facturaspendientes(request): # URL de tu API externa que proporciona las facturas pendientes api_url = 'http://127.0.0.1/api/v4/documents/' # Datos de autenticación auth = ('admin', 'jehK4XvBGp') # Realiza una solicitud GET a la API con autenticación response = requests.get(api_url, auth=auth) # Verifica si la solicitud fue exitosa if response.status_code == 200: data = response.json() # Convierte la respuesta JSON en … -
How to write unit tests with django-tenants and django-graphene to test graphql APIs?
i have written below code following the django-tenants documentation but it is not working and i am getting the error. I know i am not the first one doing this will appreciate any kind of lead..Thanks! I have added the following code which is very simple in use case in which we create organization and that's it import string, random from django_tenants.test.cases import TenantTestCase from django_tenants.test.client import TenantClient from app.tenant.models import Organization, Domain from ..utility import utils, constants def generate_token(user): # sourcery skip: inline-immediately-returned-variable """ this function generates a token for the user :param user: :return: token generated """ from strobes.app.serializers import TwoFactorAuthenticationSerializer t = TwoFactorAuthenticationSerializer() return t.get_token(user).access_token class TenantGraphQLTestCase(TenantTestCase): def setUp(self): alphabet = string.ascii_lowercase random_name = ''.join(random.choice(alphabet) for _ in range(10)) self.user = utils.generate_fake_superuser() self.tenant = Organization.objects.create(name="Clear Org",industry="Dummy",referer="Direct",employee_size=100,strobes_customer=True) domain = Domain() domain.tenant = self.tenant domain.domain = "client.co" domain.save() self.authentication_headers = { "HTTP_AUTHORIZATION": f"JWT {generate_token(self.user)}", "Content-Type": "application/json", } def tearDown(self): # Delete tenant and domain self.tenant.delete() self.domain.delete() def test_tenant_clients_query(self): client = TenantClient(self.tenant, **self.authentication_headers) response = client.post('/graphql/', {'query': '{ clients { name } }'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['data']['clients'][0]['name'], 'make') error i am getting: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django_tenants/test/cases.py", line 38, in setUpClass cls.tenant.save(verbosity=cls.get_verbosity()) File "/usr/local/lib/python3.8/site-packages/django_tenants/models.py", line 107, in save super().save(*args, … -
Django return render/httpresponse and Json into a single Jsonresponse
I'm new to Django and try to understand how to return 2 different kind of response type inside one return Jsonresponse : view.py def article_filter_mobile(request): # Here I'm trying to get the total records number of my DB number_of_rec = Record.objects.count() # Need to access {{number_of_rec}} in test.html count = render(request, 'test.html', {'number_of_rec': number_of_rec}) # here I'm listing all datas of my DB data = dict() locations = Record.objects.raw("SELECT * FROM myDb") available_lessons = [model_to_dict(l) for l in locations] # Need to access {{available_lessons|safe}} in a JS script inside grid_mobile.html data['html_table'] = render_to_string('grid_mobile.html', {'available_lessons': available_lessons},request=request) # I think my problem is here as data and count are not in the same format return JsonResponse(data,count) Can someone help me to understand what is wrong in this code ? Thanks -
Page not found (404) No comments found matching the query
views,py: class CommentCreateView(LoginRequiredMixin, CreateView): model = Comments fields = ['content'] template_name = 'blog/comment_create.html' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user messages.success(self.request, 'You have made a comment') return super().form_valid(form) class CommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comments fields = ['content'] template_name = 'blog/comment_update.html' def test_func(self): comment = self.get_object() if self.request.user == comment.author: return True else: return False def form_valid(self, form): messages.success(self.request, 'You have updated the post') return super().form_valid(form) urls.py: from django.contrib import admin from django.urls import path from blog.views import home, about, PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, CommentCreateView, CommentUpdateView urlpatterns = [ # path('', home, name='blog_home'), path('', PostListView.as_view(), name='blog_home'), path('post/<int:pk>', PostDetailView.as_view(), name='post_detail'), path('post/<int:pk>/update', PostUpdateView.as_view(), name='post_update'), path('post/<int:pk>/delete', PostDeleteView.as_view(), name='post_delete'), path('post/create/', PostCreateView.as_view(), name='post_create'), path('post/<int:pk>/create_comment/', CommentCreateView.as_view(), name='comment_create'), path('post/<int:pk>/update_comment/<int:comment_id>', CommentUpdateView.as_view(), name='comment_update'), path('about/', about, name='blog_about'), ] models.py: class Comments(models.Model): content = models.CharField(max_length=100) date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(to=User, on_delete=models.CASCADE) post = models.ForeignKey(to=Post, related_name='comments',on_delete=models.CASCADE) def __str__(self): return f'Comment by {self.author} for {self.post.title}' def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.post.pk}) that is fom post template: {% for comment in post.comments.all %} <article class="media content-section"> <div class="small text-muted">Comment by {{ comment.author }}</div> <a href="{% url 'comment_update' pk=object.pk comment_id=comment.pk %}">{{ comment.content }}</a> <div class="small text-muted"> Posted on {{ comment.date_posted }}</div> </article> {% endfor %} that is an error: enter image … -
Django: convert dropdowns created with Html pages in Django forms (project already working)
I have a small fully functional project where there are 3 dropdowns, however created with manual Html pages. I'm a beginner and I realized that it's better to use the classic Django Forms (and not create dropdowns manually with html pages). Can you show me how I can convert this little project to Django forms? Thank you **CODE PYTHON ** models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class FullRecord(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) city_departure = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_departure") city_destination = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_destination") @property def departure_destination(self): return f"{self.city_departure}-{self.city_destination}" def __str__(self): return self.country.name views.py **from django.shortcuts import render from .models import FullRecord, Country def trip_selector(request): if "Hx-Request" in request.headers: trips = FullRecord.objects.none() if request.headers["Hx-Trigger"] == "id_trip": country_id = request.GET.get("country") if country_id != "": trips = FullRecord.objects.filter(country_id=country_id) return render(request, "trips.html", {"trips": trips}) elif request.headers["Hx-Trigger"] == "id_extract_single_city": selected_trip = request.GET.get("trips") extracted_cities = [] if selected_trip != "": trip = FullRecord.objects.get(id=int(selected_trip)) trip_with_combined_names = trip.departure_destination split_trip = trip_with_combined_names.split("-") extracted_cities = split_trip return render(request, "extract_single_city.html", {"options": extracted_cities}) else: countries = Country.objects.all() return render(request, "form.html", {"countries": countries})** urls.py **from django.urls import path from . import views urlpatterns … -
Creating a Custom Choices Field in Django Model
I'm working on a Django project and need to implement a charfield field "Custom" in the dropdown menu in the UserProfile model. The requirements are as follows: Users should be able to select their gender from predefined options (Male or Female). Additionally, there should be an option to select "Custom" if the user's gender is not represented by the predefined options. If a user selects "Custom," a text field should appear, allowing them to enter their gender description. I've already created the UserProfile model with predefined gender choices, but I'm not sure how to dynamically show or hide the text field based on the user's selection of "Custom." Note: I want this to be done in both Django Admin and DRF API. Feature should look like this: a screenshot of a custom field taken from Instagram Here's my UserProfile model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) FEMALE = 'FEMALE' MALE = 'MALE' CUSTOM = 'CUSTOM' NONE = 'NONE' GENDER = [ (FEMALE, "Female"), (MALE, "Male"), (CUSTOM, "Custom"), (NONE, "Prefer not to say"), ] gender = models.CharField( max_length=20, choices=GENDER, default=NONE, ) custom_gender = models.CharField( max_length=255, blank=True, # Allow it to be optional null=True, # Allow it to be null ) … -
Importing data from MYSQL to Django
I using the inspectdb in Django because im trying to get the data from my localhost(MYSQL) now if i add or edit a data into my Mysql does also update automatically the changes into my django? or any reccomendation would really appreciate. #newbie I tried the InspectDb and i thought if i made changes into Mysql the django also update -
No such column: 'wagtailcore_page.latest_revision_id' post upgrade from wagtail 3 to wagtail 4.2.4
I have recently upgraded my Wagtail version from v3 to v4.2.4 In this upgrade, the wagtailcore_page creates a new column latest_revision_id through one of its migrations under the library. When I am trying to run my test cases, it is giving me an error with this column saying that it does not exist. During deployment too I faced the same issue but running migrations in a specific order worked and issue was resolved. During test cases, the internal test database is newly created and looks for that column before the migration that creates the column runs due to which this issue arise. Please find below screenshot for reference. screenshot -
How do I pass the current logged in user to a field in a django and another model via an automic transaction?
I have a model form and can fulfill this requirement by setting the form field equal to request.user in the form view. My problem is I need to create whats basically a join table during the form save and can't figure out how to get the request.user to the form field then do a final validation and form save in the view. I'm pretty new to django and web dev in general. Any help is greatly appreciated. class LocationCreateForm(forms.ModelForm): class Meta: model = Organization fields = ("name", "email", "address", "addressline2", "city", "state", "about", "payment") def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(LocationCreateForm, self).__init__(*args, **kwargs) @transaction.atomic def save(self): data = super().save(commit=False) if self.user is not None: data.created_by = self.user data.save() OrganizationTeam.objects.create( organization=data, practitioner=self.user, is_admin=True, ) return data HttpResponse("Didn't work.") -
Django+Html: Convert a working project from manual html forms to Django forms
In this 100% fully functional project, i would like to replace the manually created html forms with the classic Django forms. Can you show me how I can convert this little project to Django forms? Thank you **CODE PYTHON ** models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class FullRecord(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) city_departure = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_departure") city_destination = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_destination") @property def departure_destination(self): return f"{self.city_departure}-{self.city_destination}" def __str__(self): return self.country.name views.py **from django.shortcuts import render from .models import FullRecord, Country def trip_selector(request): if "Hx-Request" in request.headers: trips = FullRecord.objects.none() if request.headers["Hx-Trigger"] == "id_trip": country_id = request.GET.get("country") if country_id != "": trips = FullRecord.objects.filter(country_id=country_id) return render(request, "trips.html", {"trips": trips}) elif request.headers["Hx-Trigger"] == "id_extract_single_city": selected_trip = request.GET.get("trips") extracted_cities = [] if selected_trip != "": trip = FullRecord.objects.get(id=int(selected_trip)) trip_with_combined_names = trip.departure_destination split_trip = trip_with_combined_names.split("-") extracted_cities = split_trip return render(request, "extract_single_city.html", {"options": extracted_cities}) else: countries = Country.objects.all() return render(request, "form.html", {"countries": countries})** urls.py **from django.urls import path from . import views urlpatterns = [ path("", views.trip_selector, name="trips") ]** admin.py from django.contrib import admin # Register your models here. from .models import Country, … -
Django - How to delete an object from a button in a table
Objective: I want to delete an object from a table using a button in Django, but it's not working as expected. I've provided relevant parts of my code below. Can someone please guide me on what to add to urls.py and views.py to make this work? Database Attributes: _id: ObjectId response: string contact_id: string status: string views.py: def delete(request, id): try: excel_data = get_object_or_404(ExcelData, id=id) excel_data.delete() return redirect('web_services_app:tables') except ExcelData.DoesNotExist: # Handle the case where the object doesn't exist return HttpResponse("The object you're trying to delete doesn't exist.") **urls.py:** path('delete/<int:id>/', views.delete, name='delete'), **HTML Table in tables.html:** <div class="table-responsive"> <table class="table table-striped" id="data-table"> <thead> <tr> <th scope="col" style="font-weight: bold; color: black;">Response</th> <th scope="col" style="font-weight: bold; color: black;">Contact ID</th> <th scope="col" style="font-weight: bold; color: black;">Status</th> <th scope="col" style="font-weight: bold; color: black;">Actions</th> </tr> </thead> <tbody> {% for data in excel_data %} <tr class="table-row"> <td class="table-data">{{ data.response }}</td> <td class="table-data">{{ data.contact_id }}</td> <td class="table-data">{{ data.status }}</td> <td> <a class="btn btn-danger" href="/web_services_app/delete/{{ data.id }}">Delete</a> </td> </tr> {% endfor %} </tbody> </table> </div> I appreciate any help you can provide. Thank you! ❤️ -
Django and react images don't appear with media folder
I use django rest framework and react where I am trying to show a user's profile picture by fetching them with axios in react. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/build/static') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'frontend/build/static/media') When I save a user's profile picture from admin panel the image is added in media folder. React is inside django. I use build in react and the structure looks like this. build static media images src public In the django rest framework page the image looks like this /media/images/Photo.jpg The problem is that even when I open the image from the admin panel it doesn't show and instead shows this Also in the frontend it doesn't appear. const profiles = friends.map(friend => { return ( <> <img src={friend.profile.profile_pic} /> </> ) }) -
How to update where the files are stored in Django app
I have a Django app that contains multiple models with FileField. I am saving by default every file directly in the Media folder. But as the app grew larger also Media folder became bigger. Now my idea is to move the files into separate folders split by models. So I am wondering what is the best practice when it comes to this? Shall I move the files to separate folders, then manually update every file location in the Database and then update Filefield path for every model? Or is there better approach? -
How to trigger a file download on click using Django and Javascript
I'm trying to produce a file download on click using Django and Javascript. I've nearly figured it out but I'm confused as to how to prevent Django from automaticall downloading the file once processing is complete. Here is my code: views.py: def translateFile(request) : if request.method == 'POST': source_language = request.POST.get('source_language') target_language = request.POST.get('target_language') form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file = (converter(uploaded_file_path, source_language, target_language))#translates file file_location = uploaded_file_path with open(file_location, 'rb') as f: file_data = f.read() response = HttpResponse(file_data, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response Javascript: const formData = new FormData(form); const xhr = new XMLHttpRequest(); xhr.open('POST', form.getAttribute('action'), true); xhr.onreadystatechange = function () { console.log("Ready state: ", xhr.readyState); console.log("Status: ", xhr.status); if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { loaderDiv.style.display = 'none'; const downloadArrowDiv = document.querySelector('#download-btn'); downloadArrowDiv.style.display = 'flex'; const responseText = document.querySelector('#response_text') responseText.textContent = 'Click to download' // File was successfully translated, you can update UI here const downloadLink = document.querySelector('#response_text_anchor'); downloadLink.href = URL.createObjectURL(xhr.response); downloadLink.download = formData.get('file').name; downloadLink.click(); } else { // Handle error case console.error('Error translating file'); } } }; xhr.responseType = 'blob'; xhr.send(formData); }); HTML: <button … -
Django Heroku deployment errors
I am trying to deploy a web application and came across this issue where it says that it could not build wheels for myproject and that the runner is empty. I am just confused because I did not name it myproject on Heroku or VSCode. Is there something I might have done that made it register in this way? Regardless, I am trying to get over this roadblock so i can deploy it. remote: Building wheel for myapp (setup.py): finished with status 'done' remote: Created wheel for myapp: filename=myapp-0.1.dev0-py3-none-any.whl size=1166 sha256=ec655f854ab6a2c0ba6b36dda552a60e1b54af84d93a82785eda9229258b686c remote: Stored in directory: /tmp/pip-ephem-wheel-cache-7q7p2y16/wheels/8b/36/8b/cb810ee2b64417af5f91d361665839bd04414f112ecafcb1e0 remote: Building wheel for myproject (setup.py): started remote: Building wheel for myproject (setup.py): finished with status 'error' remote: error: subprocess-exited-with-error remote: remote: × python setup.py bdist_wheel did not run successfully. remote: │ exit code: 1 remote: ╰─> [3 lines of output] remote: warning: build_scripts: runner is an empty file (skipping) remote: remote: error: [Errno 2] No such file or directory: 'build/scripts-3.9/runner' remote: [end of output] remote: remote: note: This error originates from a subprocess, and is likely not a problem with pip. remote: ERROR: Failed building wheel for myproject remote: Running setup.py clean for myproject remote: Building wheel for mysqlclient (setup.py): started remote: Building …