Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Force http in heroku
I have a node.js app in heroku , this app uses a django api wich is http,but the heroku app is https and cant make petitions to the api , i get this error xhr.js:177 Mixed Content: The page at 'https://myapp.herokuapp.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint (API HTTP URL). This request has been blocked; the content must be served over HTTPS. I just want to change the https://myapp.herokuapp.com/ to http://myapp.herokuapp.com/ Thankyou in advance and sorry for my english -
Django App - allowing users to save their favorite posts to their profile for quick access
I'm working on a Django app that is essentially a database for different gym workouts. It allows users to search for workouts, and I anticipate that as scale increases, it would be annoying to keep searching for the same workout the user wants to learn about. Is there functionality in Django to let the user 'save' a certain workout so it appears on their profile page, almost like a playlist of sorts? -
How Sum columns from different tables in new table Django
I would like to create a new table, where in their columns can store the total sum of money of each project, depending certain criterias such as HR, Tools, Materials, Infrastructure. In this case the columns are named total_infraestructura, total_equipo, total_herramientas and total_ recursos Right now I'm getting struggle with getting the total values into the table. class CostoProyecto(models.Model): proyecto = models.OneToOneField(Proyecto, on_delete=models.CASCADE, primary_key=False, null=True) infra = models.OneToOneField(Infraestructura, on_delete=models.CASCADE, primary_key=False, null=True) equipo = models.OneToOneField(Equipo, on_delete=models.CASCADE, primary_key=False, null=True) herramientas = models.OneToOneField(Herramienta, on_delete=models.CASCADE, primary_key=False, null=True) materia_prima = models.OneToOneField(Recurso, on_delete=models.CASCADE, primary_key=False, null=True) def costo_infra (self): return Infraestructura.objects.aggregate(sum('Costo')) Costo_infra = property(costo_infra) The rest of the models to know context from django.db import models # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length=64) ResponsableProyecto = models.CharField(max_length=64) EvaluadorProyecto = models.CharField(max_length=64) DescripcionProyecto = models.CharField(max_length=500) class Financiamiento(models.Model): MontoProyecto = models.IntegerField(null=True, blank=True) MontoPropio = models.IntegerField(null=True, blank=True) MontoBanca = models.IntegerField(null=True, blank=True) MontoPublico = models.IntegerField(null=True, blank=True) proyecto = models.OneToOneField(Proyecto, on_delete=models.CASCADE, primary_key=False, null=True) def financiamiento_asegurado (self): return self.MontoPropio + self.MontoBanca + self.MontoPublico FinanciamientoAsegurado = property(financiamiento_asegurado) def porcentaje_financiamiento_asegurado (self): return self.FinanciamientoAsegurado / self.MontoProyecto PorcentajeFinanciamientoAsegurado = property(porcentaje_financiamiento_asegurado) def nota (self): if self.PorcentajeFinanciamientoAsegurado <= 0.05: return 0 elif self.PorcentajeFinanciamientoAsegurado <=0.15: return 1 elif self.PorcentajeFinanciamientoAsegurado <=0.25: return 2 elif self.PorcentajeFinanciamientoAsegurado <=0.35: return 3 elif self.PorcentajeFinanciamientoAsegurado … -
Django Admin FilteredSelectMultiple Widget selection doesn't work
I am trying to use the FilteredSelectMultiple widget from the admin widgets library. I was able to get the widget displayed on the web page. However, I cannot get the buttons to move the selections to the Chosen box. Here is my code: forms.py from django.contrib.admin.widgets import FilteredSelectMultiple from .models import * from django import forms # Create your views here. class ExampleForm(forms.Form): example_selector = forms.ModelMultipleChoiceField(queryset=Example.objects.all(), widget=FilteredSelectMultiple("Example", is_stacked=False)) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) class Meta: model = Example models.py from django.db import models # Create your models here. class Example(models.Model): example_id = models.AutoField(primary_key=True) example_name = models.CharField(max_length=45, blank=False, null=False) def __str__(self): return self.example_name index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> {{example.as_p}} <script src="/static/admin/js/vendor/jquery/jquery.js"></script> <script src="/static/admin/js/jquery.init.js"></script> <script src="/static/admin/js/SelectFilter2.js"></script> {{example.media}} </body> </html> url.py from django.contrib import admin from django.urls import path, include from django import views as django_views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('example/', include('example.urls')), url(r'^jsi18n/$', django_views.i18n.JavaScriptCatalog.as_view(), name='jsi18n'), ] I've checked the browser console and when I try to click on the buttons I get the following error: Uncaught TypeError: Cannot read property 'addEventListener' of null at Object.init (VM427 SelectFilter2.js:148) at VM427 SelectFilter2.js:233 at NodeList.forEach (<anonymous>) … -
Pytest assert return 401 instead of 200 when test login in DRF
I do not know what is wrong with this code when I am trying to test login, first assert passed so user created successfully but failed in second assert. Hint: I am using simple JWT Test Code: from user.models import User from rest_framework.test import APIClient from mixer.backend.django import mixer from django.urls import reverse import pytest client = APIClient() @pytest.mark.django_db class TestUser(): @pytest.fixture def setup_user(self): user = mixer.blend(User, email='a@a.com', password='1') return user def test_login(self, setup_user): assert User.objects.count() == 1 data = {'email': 'a@a.com', 'password': '1'} response = client.post(reverse('login'), data=data) assert response.status_code == 200 URL: path('api/login/', TokenObtainPairView.as_view(), name='login'), ERROR: FAILED user/tests/test_user.py::TestUser::test_login - assert 401 == 200 -
although I have correctly configured nginx and gunicorn my site does not work
I don't know where the error is but according to the status nginx and gunicorn is working fine I have checked the links by contributing to my site they are correct the error is "redirected you too many times." so according to you it's nginx and gunicorn /etc/nginx/sites-available/namesite.com server { if ($host = namesite.com) { return 301 https://$host$request_uri; } server_name namesite.com www.namesite.com; return 404; # managed by Certbot index index.html index.htm index.nginx-debian.html; location /static { alias /home/myname/nameproject/staticfiles; } location / { include proxy_params; client_max_body_size 100M; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/namesite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/namesite.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.namesite.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = namesite.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name namesite.com www.namesite.com; listen 80; return 404; # managed by Certbot } /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myname Group=www-data WorkingDirectory=/home/myname/nameproject ExecStart=/home/myname/nameproject/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ deployement.wsgi:application [Install] WantedBy=multi-user.target -
SQLAlchemy: limit select depth for self referencing table
I have two SQLAlchemy models: Comment and User, defined as following: Comment class Comment(Base): __tablename__ = 'comment' id = Column(Integer, primary_key=True,autoincrement=True , index=True) .... owner_id = Column(String, ForeignKey("user.id"), nullable=False) item_id = Column(Integer, ForeignKey("item.id"), nullable=False) original_comment_id = Column(Integer, ForeignKey("comment.id"), nullable=True) #relationship owner = relationship("User", back_populates="comments") item = relationship("Item", back_populates="comments") replies = relationship("Comment", backref=backref('parent', remote_side=[id])) User class User(Base): __tablename__ = 'user' id = Column(String, primary_key=True, index=True ) .... comments = relationship("Comment", back_populates="owner") As shown above, each comment can be a reply to another comment. I want to get a list of all comments for a given item, and each comment should contain its immediate parent only, if it has one. To achieve that, I'm using the following code comments = db.query(Comment).filter(Comment.item_id == item_id)\ .options( joinedload(Comment.owner).options(load_only("display_name")), joinedload(Comment.parent).options(joinedload(Comment.owner).options(load_only("display_name")))\ ) But it's not giving me just the immediate parent, but grandparents too. How can I limit the depth to immediate parents only ? -
Nonetype error while saving file with dropzone js in Django
I am trying to save documents/images into my SQL database using dropzone.js ,for my web app made using Django HTML FILE: {% extends 'Main/logged_base_expert.html' %} {% block content %} {% load static %} <head> <script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script> <link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css"> </head> <body> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.5/css/bootstrap-select.min.css" media="screen"> <form action="{% url 'document_upload' %}" method = "POST" class="dropzone dz" role="form" enctype="multipart/form-data"> {% csrf_token %} <div class="fallback"> <input name="file" type="file" id="file" multiple > </div> <button type="submit" class="form-control" id="cf-submit" name="submit">Submit</button> </form> <!-- client section end --> <!-- footer section start --> {% endblock %} views.py : def document_upload(request): c = main.objects.get(username = request.session['username']) unq_id = c.unq_id print("overall") if request.method == 'POST': images = request.FILES.get('file') print("image") fs = FileSystemStorage() filename = fs.save(images.name, images) Doc1 = Doc(user_id = unq_id, upload = images) Doc1.save() return render(request, 'Main/document_upload.html') models.py: class Doc(models.Model): unq_id = models.AutoField(primary_key=True) user_id = models.BigIntegerField() upload = models.ImageField(upload_to= 'expert/images') def __str__(self): return str(self.unq_id) The issue I keep facing is that , i keep getting the error AttributeError at /document_upload/ 'NoneType' object has no attribute 'name' It occurs in the following line, in views.py: filename = fs.save(images.name, images) Additional Info : the relative path of the image seems to be storing just perfectly in the database, but since i … -
get the size of an image to be uploaded in django before the upload process starts
Okay, I don't have a code snippet here, I wanted to display a progress bar when I am uploading an image in Django, am using celery and some other stuff, but most importantly i will need to know the size of the file been uploaded so that I can compute the progress of the upload, any suggestion or solutions, please. -
Override a save function to always update or create Django
I want to override the function for saving the profile inside the actual model. Here is my attempt so far: class Profile(models.Model): # others def save(self, *args, **kwargs): # Object is a new profile if email does not exist if not Profile.objects.filter(email = self.email).exists(): # save return super().save(*args, **kwargs) #object is an existing profile else: # update return super().update(*args, **kwargs) Simply update if its on the db. I'm doing this because I can't do the usual update_or_create from ImportExportModelAdmin. Any answer or link is appreciated. -
Exception Type: RelatedObjectDoesNotExist Exception Value: Cart has no owner. Django-eCommerce
I'm trying to make a webshop on Django and im facing up with one problem. When I;m running this code on my PC like python manage.py runserver it works perfect. But when I'm tryieng to run it in my local network like python manage.py runserver 0.0.0.0:8000 then i become this error: RelatedObjectDoesNotExist at /add-to-cart/vw_golf/bags/ Cart has no owner. Request Method: GET Request URL: http://192.168.1.165:8000/add-to-cart/vw_golf/bags/ Django Version: 3.2.4 Exception Type: RelatedObjectDoesNotExist Exception Value: Cart has no owner. Exception Location: C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 197, in get Python Executable: C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv\Scripts\python.exe Python Version: 3.9.2 Python Path: ['C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv\django3-ecommerce', 'C:\Users\dinar\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\dinar\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\dinar\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\dinar\AppData\Local\Programs\Python\Python39', 'C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv', 'C:\Users\dinar\PycharmProjects\shop_scnd_copy\venv\lib\site-packages'] These are my classes Cart and Customer: class Cart(models.Model): owner = models.ForeignKey('Customer', verbose_name='Kunde', on_delete=models.CASCADE) products = models.ManyToManyField(CartProduct, blank=True, related_name='related_cart') total_products = models.PositiveIntegerField(default=0) final_price = models.DecimalField(max_digits=9, default=0, decimal_places=2, verbose_name='Gesamtpreis') in_order = models.BooleanField(default=False) for_anonymous_user = models.BooleanField(default=False) def __str__(self): return str(self.id) class Customer(models.Model): user = models.ForeignKey(User, verbose_name='Kunde', on_delete=models.CASCADE) phone = models.CharField(max_length=20, verbose_name='Handynummer', null=True, blank=True) email = models.EmailField(max_length=255, verbose_name='Email', default='') address = models.CharField(max_length=255, verbose_name='Adresse', null=True, blank=True) orders = models.ManyToManyField('Order', verbose_name='Bestellungen', related_name='related_order') def __str__(self): return "Kunde: {} {}".format(self.user.first_name, self.user.last_name) This is my view: class AddToCartView(CartMixin, View): def get(self, request, *args, **kwargs): ct_model, product_slug = kwargs.get('ct_model'), kwargs.get('slug') content_type = ContentType.objects.get(model=ct_model) product = content_type.model_class().objects.get(slug=product_slug) cart_product, created = CartProduct.objects.get_or_create( user=self.cart.owner, … -
Returning the first object in a django queryset
I want to grab only the first element in the queryset below. But if add .first(), it returns an error saying that 'Product' object is not iterable query = Product.objects.filter(user=request.user).order_by('-created_at') Since this is not iterable, how can I grab the first object without converting to other datatypes like list -
python – My django’s website on cpanel doesn’t load my media files but all my stacticfiles and media work when DEBUG= True
i need some help to display my media files when debug= False I have a Django project that is working fine and showing all media files downloaded from admin when debug = True but I immediately change debug = False Django can't find my media folder but it loads my static folder. as you can see i have correctly configured my MEDIA_ROOT and MEDIA_URL. this is my setting.py setting.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = '#############################' DEBUG = False ALLOWED_HOSTS = ['##############################'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appsolve.apps.AppsolveConfig', 'ACCOUNTS', 'afiilitePrograme', 'manageapps', 'News', 'contactUS', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', #'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware',**strong text** 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'alpha1.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['alpha1/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'alpha1.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT='collected/static' MEDIA_ROOT … -
I want to display another model in the home admin site page django
In the admin site I display custom users, I mean in admin.py I wrote from .models import User, Product, Address from django.contrib import admin from .forms import CustomUserCreationForm from django.contrib.auth.admin import UserAdmin class CustomUserAdmin(UserAdmin): model = User add_form = CustomUserCreationForm fieldsets = ( *UserAdmin.fieldsets, ( 'Additional fields:', { 'fields': ( 'phone_number', 'billing_address', 'shipping_address', ) } ) ) admin.site.register(User, CustomUserAdmin) User is my model that inherits from AbstractUser, I want to display another model too which is called Product. How to do that? Here it is the second model class Product(models.Model): name = models.CharField(max_length=50) SKU = models.CharField(max_length=50) description = models.CharField(max_length=300) price = MoneyField(max_digits=19,decimal_places=4,default_currency='USD') class Product(models.Model): name = models.CharField(max_length=50) SKU = models.CharField(max_length=50) description = models.CharField(max_length=300) price = MoneyField(max_digits=19,decimal_places=4,default_currency='USD') class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.RESTRICT, null=True) image = models.ImageField() -
django page load slow in 10 seconds
The page is loading in 10 seconds and after downloading django-debug-toolbar i saw that I am making 124 queries and 90% of them are duplicates. class TerminalManagementView(LoginRequiredMixin, TemplateView): template_name = "app/terminal_management.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tb_terminal_categories'] = TbTerminalCategory.objects.all() context['tb_terminal_caregory_form'] = TbTerminalCategoryForm() context['tb_terminal_register_form'] = TbTerminalRegisterForm() filter = self.request.GET.get('category') if filter: terminals = TbTerminal.objects.all().filter( category__category_name=filter).order_by('create_time') else: terminals = TbTerminal.objects.all().order_by('create_time') page = self.request.GET.get('page', 1) paginator = Paginator(terminals, 9) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) context['terminals'] = data return context in this model I reference 4 other models, how do make this implementation work faster? class TbTerminal(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) customer = models.ForeignKey( TbCustomer, on_delete=models.CASCADE, db_column='cstm_id') terminal_id = models.CharField(max_length=64, blank=True, null=True) area = models.ForeignKey( TbArea, on_delete=models.CASCADE, db_column='extra_id1') room = models.ForeignKey( TbRoom, on_delete=models.CASCADE, db_column='extra_id2') terminal_name = models.CharField(max_length=64, blank=True, null=True) terminal_desc = models.CharField(max_length=255, blank=True, null=True) category = models.ForeignKey( TbTerminalCategory, on_delete=models.CASCADE, db_column='cat_id') device_model = models.ForeignKey( TbDeviceModel, on_delete=models.CASCADE, db_column='device_model_id') -
How to store a dictionary in a Django database model's field?
I want to store this list of dictionarys in a Django database: h = [ {'sale_id': 14, 'name': 'Macarena', 'fecha': datetime.date(2021, 3, 11), 'debe': 500.0}, {'sale_id': 14, 'name': 'Macarena', 'fecha': datetime.date(2021, 4, 11), 'debe': 500.0}, {'sale_id': 15, 'name': 'Yamila', 'fecha': datetime.date(2021, 4, 14), 'debe': 2000.0} ] I've tried this: h = tabla_creditos() class Creditos1(models.Model): sale_id = models.IntegerField(default=0) name = models.CharField(max_length=150) fecha = models.DateTimeField(default=datetime.now) debe = models.IntegerField(default=0) for i in range(0,len(h)): Creditos1.objects.create(name=h[i]['name'], sale_id=h[i]['sale_id'], fecha=h[i]['fecha'], debe=h[i]['debe']) where "h" is that dictionary, which results from "tabla_creditos()" function. And then, I tried to create the values for the DB with "objects.create" but I got duplicated values stored in DB: So, how can I store that dict in the DB? I found this solution: How to store a dictionary in a Django database model's field but none of the answers helped me. Thanks! -
How to change django-phonenumber-field error messages
I am using django-phonenumber-field. Everyone who uses this app probably knows that any prefix has the same example "Enter a valid phone number (e.g. +12125552368)." Enter a valid phone number (e.g. +12125552368). So, I don't like it and I wanted to change it but I could not change this text, I thought I would change it in html like this: {% if form.phone.errors %} <p class="alert-p"></p>Incorrect International Calling Code or Mobile Number!</p> {% endif %} Incorrect International Calling Code or Mobile Number! But when I changed it I realized that this method would not work for me because there was a likelihood that users would enter the same phone number and could not understand why it would not save if it did not send the appropriate error message. (phone number is unique) Now there is a problem, in one case, when the user enters the wrong number in the prefix, this time I want my built-in text to drop out as an error message, but when users enter the same number I want to drop out the django-phonenumber-field default Error message Account with this Phone already exists. I will take any advice on how I can solve this problem. -
Django ORM - Email groups
I'm try make a email group model in django that has "recipient" & "copy" fields. How can I do this? if you have a better implementation suggestion than below, pls let me know! from django.db import models class Email(models.Model): email_id = models.AutoField(primary_key = True) recipient = models.EmailField(unique=True, null=True) copy = models.EmailField(unique=True, null=True) def __str__(self): return self.recipient +" - "+ self.copy class EmailGroup(models.Model): group_id = models.AutoField(primary_key = True) group_name = models.CharField(max_length=50) sector = models.CharField(max_length=50) recipient = models.ManyToManyField(Email) copy = models.ManyToManyField(Email) def __str__(self): return self.group_name +" - "+ self.sector -
Send scheduled email django
I have made a small django app to fit all my needs. I will use it on my company level to track simple tasks of couple mehanical engineers. Now, only thing left is to send scheduled emails (every day at noon, if someone is behind with work, he would get an email). Since I'm using Windows and I'll deploy this app on Windows, I can't use cron job (this only works on Linux, as I've seen on forums), which is simple and easy. Only way I found so far was using django-celery-beat. This is not so easy to set up, and I need to run 'worker' each time I run my server. This is a bit above my level and I would need to learn a lot more (and it needs to have a message broker, like RabbitMQ, which I also need to run and learn to implement). I was wondering is there a more easy way to send a simple email every day at noon? I don't want to install additional apps, I wish to keep it simple as possible. -
Problem with Data Baze Sqlite in python django
I asked this but nobody help me. Because I try ask it again. Situation: I have a VPS server (OS: Ubuntu). I have to create a site on python django. I don't have a problem with it. Problem become when I create a project. Django project was generated. I did a migration. But when I log in super user menu this error show up: OperationalError at /admin/login/ attempt to write a readonly database I tried find a answer. Someone wrote that I need to give a grant to write in sqlite. I used putty and wrote mysql then CREATE USER 'novyi_polzovatel'@'localhost' IDENTIFIED BY 'parol'; and GRANT ALL PRIVILEGES ON * . * TO 'novyi_polzovatel'@'localhost'; But console show an error with syntax Before I don't have this problem Please help And sorry for my English -
File not automatically downloading
Hi there i have a view function which gives a response in a csv file but when i call it using the Django Api view it gives or shows nothing and not even starts downloading, here is my code @api_view(['POST']) @authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication]) u/permission_classes([IsAuthenticated]) def attendance_datasetgenerator(request): serializer = DatasetGeneratorSerializer(request.data) start_roll = serializer.data['start_roll'] end_roll = serializer.data['end_roll'] start_date = serializer.data['start_date'] end_date = serializer.data['end_date'] subject = serializer.data['subject'] att= Attendance.objects.filter(date__range=(start_date,end_date), student__pk__range=(start_roll,end_roll), subject__exact=subject) att2= Attendance.objects.exclude(date__range=(start_date,end_date), student__pk__range=(start_roll,end_roll), subject__exact=subject) df2 = DataFrame(att2.values()) df1 = DataFrame(att.values()) csv1 = df1.to_csv() csv2 = df2.to_csv() file1 = StringIO() file1.write(csv1) response = HttpResponse(file1, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=file1.zip' return response kindly guide -
Django Haystack can't update indexes when I insert a new record
I use haystack (whoosh) in my Django project and I set HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' to update indexes when I insert a new record. It work well on my pc. I have a cloud server and I use docker-compose to deploy my project. At this time, this feature no longer works. Has anyone encountered a similar problem, how can I solve it? Thank for your reply firstly !! -
GET js chunk 404'd on all but one chunk
I'm running a react frontend with django backend on aws lightsail (bitnami apache server). Everything had been working fine until I changed some frontend code and reran npm run build on the server. It completed successfully and I see the chunks in the correct static folder. All of them are there. When I access the website, it loads one of the chunks and then 404's on the rest. The built css chunks are all there, too. I've restarted the apache server a couple times for good measure but have the same problem. Any idea what could be happening? -
RuntimeWarning: DateTimeField (unbound) received a naive datetime , when increment duration until datetime.now
I'm trying to increment a duration until a condition. Data is saved in database but page doesn't refresh and I'm getting this error. What can be done? RuntimeWarning: DateTimeField (unbound) received a naive datetime (2021-07-04 18:54:38.827527) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" I'm using this code in my views from datetime import datetime ... if form.is_valid(): numof=form.cleaned_data['Numero_Of'] QuerySet_of=OF.objects.get(Numero_Of=numof) Usin=Poste.objects.get(OF_id=QuerySet_of.Id_OF,Nom_poste__startswith = "MGP") while Usin.Date_S_poste is None : OF.objects.filter(Id_OF=QuerySet_of.Id_OF).update(Nb_jrs_att_Usin = datetime.now() - F('Date_E_initial')) models.py Nb_jrs_att_Usin=models.DurationField(null=True, blank=True) In my settings, I have changed TIME_ZONE to TIME_ZONE = 'Africa/Tunis' USE_I18N = True USE_L10N = False USE_TZ = True -
How to view slideshow in django?
I am building a side project in Django where I have the following feature. There is a list of projects which a name and 10 images associated to it. When the user clicks on the name, there should be a pop up, having the slideshow of all the images associated to that particular project. I am using plain HTML for the templates along with the Django templating language. Can someone please help me out in doing this? My models.py is like class Project(models.Model): project_id = models.AutoField project_name = models.CharField(max_length=100, blank=False) project_img1 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img2 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img3 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img4 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img5 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img6 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img7 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img8 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img9 = models.ImageField( upload_to='project_images', blank=True, null=True) project_img10 = models.ImageField( upload_to='project_images', blank=True, null=True) def __str__(self): return self.project_name PS: The url remains same. It's just a pop-up/modal that opens/closes on button click. I am doing so by using the display:none property in CSS.