Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can subtract two dates on django
I want to substract two dates at the same TYPE OF REGISTER image I want to substract PAR DATES but i have 4 dates how can i do? views.py ## sentencia 1 sentencia ="exec [PR].[dbo].[PT_PR]" + "'" + maquina + "','" + str(rec) + "','" + orden + "'" + ",'" + str(fecha_i) + "'," + "'" + str(fecha_f) + "'" cr = cursor.execute(sentencia) resultstable = namedtuplefetchall(cr) fecha_total = fecha_f - fecha_i -
Django (Accidental deletion of socket file, need to recreate)
Yesterday evening, I accidentally highlighted one too many files which I needed to delete from my Django environment and I accidentally caught the .sock file of my test production .sock file. I have since tried everything I can think of to recreate the .sock file with no avail. Does anyone know of which method I should be following to recreate the sock file? As a last resort, I tried to manually create the .sock file and tried to run this command: gunicorn --workers 3 --bind unix:/home/testapp/test.sock test.wsgi:application Although, I receive an error during the boot phase, ValueError("%r is not a socket" % addr) which is understandable as I manually tried to recreate the file as a last resort option. I have tried to rebooting nginx, reloaded the daemon, and tried to restart gunicorn, hoping that the .sock may be automatically recreated within my project folder, but I'm not having any luck. Any tips would be most appreciated! Thank you :-) -
How to get foreign key values in Django?
models.py: class Publisher(models.Model): name = models.CharField(max_length=30) class Book(models.Model): title = models.CharField(max_length=100) publisher = models.ForeignKey(Publisher) views.py: book = Book.objects.get(pk=1) I need the publisher id and publisher name of this book. How to get them? -
Delete post after 24 days or 1 Day
I am building a Simple BlogApp and I am stuck on an Problem. What i am trying to do :- I am trying to delete the post according to user's choice , Suppose a user select delete after 1 day then i am trying to delete it automatically after 1 day BUT failed many times. models.py class Blog(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=300) time = models.CharField(max_length=30,choices=TIME) date_added = models.DateTimeField(default=timezone.now) class Image(models.Model): blogs = models.ForeignKey(Blog,on_delete=models.CASCADE) images = models.FileField(upload_to='files') views.py def delete_post(request): blogPost = Image.objects.filter(blog__user=request.user) d = timezone.now() - timedelta(hours=1) d1 = timezone.now() - timedelta(days=1) for foo in blogPost: if foo.blog.time == '24H': showing = Image.objects.filter(blog__user=request.user).filter(date_added__gte=d) elif foo.blog.time == '1D': showing = Image.objects.filter(blog__user=request.user).filter(date_added__gte=d1) context = {'showing':showing} return render(return ,'posts.html', context) BUT i try to run this then it is showing nothing BUT when user selects 1D then hide after 1 Day BUT it is not working. I have no idea how can i do it. Any help would be Appreciated. Thank You in Advance. -
Django loads image only with hardcoded path
So Django loads image only if I have hardcoded src value of img tag. This is my template with hardcoded image path (works fine): {% load static %} {% block content %} <p>{{ product.title_text}}</p> <p>{{ product.description_text }}</p> <p>{{ image.image }}</p> <img src="{% static 'my_app/images/product_images/some_image.jpg' %}" alt="{{ image.name }}"> {% endblock %} But if I change image path to the dinamic variable which value actually is the same path, nothing shows up. No errors, just no image. <img src="{% static image.image %}" alt="{{ image.name }}"> Any suggestions please? Thanks in advance. -
Django with legacy database user table
I am trying to integrate Django with an already existing database. I am using mysql database. When I ran the migrations, django has added its default tables like auth_permission, auth_user etc. I have a table in my database called tb_user which has the usname, psword and more additional fields. Since django default auth_user also has the username and password, how these two will work together? When I register a new user, the user will be stored in both tables? Is this an issue at all? I have posted a new question with more details and issues here. You can see the models. Django running migrations on legacy database -
Detected path traversal attempt when associating and saving a FileField to a model instance in Django
I'm trying to generate a pdf file and associate it with a Django model FileField. The process shown below works on a Django local development server, but on a deployment server (Nginx + Gunicorn) I get a SuspiciousFileOperation exception: Detected path traversal attempt in '/home/user/media/properties/1/myfile_1.pdf', which traces back to the model_instance.save() line. From the docs I understand that the error is raised if the path contains '..' to safeguard against path traversal attempts: def generate_filename(self, filename): """ Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(filename) if '..' in pathlib.PurePath(dirname).parts: raise SuspiciousFileOperation("Detected path traversal attempt in '%s'" % dirname) return os.path.normpath(os.path.join(dirname, self.get_valid_name(filename))) However, I don't see where my code contains such a relative path and don't know how to overcome the error. Settings.py MEDIA_URL = "/media/" MEDIAFILES_DIRS = ["/home/user/media"] MEDIA_ROOT = "/home/user/media" File operation myfile = open(f'{settings.MEDIA_ROOT}/temp/myfile_{model_instance.id}.pdf') django_file = File(myfile, name=f'myfile_{model_instance.id}.pdf') model_instance.myfile = django_file model_instance.save() models.py def directory_path(instance, filename): return f'{settings.MEDIA_ROOT}/properties/{instance.id}/{filename}' class MyModel(models.Model): myfile = models.FileField(blank=True, null=True, upload_to=directory_path) -
Django running migrations on legacy database
I am working with a legacy database and I have created a custom user model. I am working to set up the register and authentication funcs. I have created the user manager and in user model there are some fields that I have added for django like is_staff, is_active, date_joined. When I run migrations, the legacy table still does not have the columns I have added in the model. Should It actually alter the legacy database? class TbUser(AbstractBaseUser, PermissionsMixin): id = models.CharField(primary_key=True, max_length=40) usname = models.CharField(max_length=40, blank=True, null=True, unique=True) psword = models.CharField(max_length=255, blank=True, null=True) # added columns is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) objects = TbUserManager() USERNAME_FIELD = 'usname' REQUIRED_FIELDS = [] class Meta: managed = False db_table = 'tb_user' Also, when I am creating the superuser, I get the following error django.db.utils.OperationalError: (1054, "Unknown column 'tb_user.password' in 'field list'") Although The user manager looks like this class TbUserManager(BaseUserManager): def create_user(self, email, psword=None, **kwargs): if not email: raise ValueError('Users must have a valid email address.') if not kwargs.get('usname'): raise ValueError('Users must have a valid username.') user = self.model( email=self.normalize_email(email), usname=kwargs.get('usname') ) user.psword(psword) user.save() return user def create_superuser(self, email, psword, **kwargs): user = self.create_user(email, psword, **kwargs) user.is_superuser = … -
can't display images in template django, HELP ME PLEASE
hello i am working on a django project i am trying to save the images entered by the user in my database and this works fine, but when i try to display them they do not display even though my configuration seems correct here is my code: panneaux/model.py from django.db import models # Create your models here. class Panneaux(models.Model): nom = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) nbr_objet = models.DecimalField(decimal_places=2, max_digits=100, default=0) image_Panneaux = models.ImageField(upload_to='images/') panneaux/form.py from django import forms from .models import Panneaux class PanneauxForm(forms.ModelForm): nom = forms.CharField( widget=forms.TextInput( attrs={ "class": "form-control", } )) description = forms.CharField( required=False, widget=forms.Textarea( attrs={ "class": "form-control", } ) ) image_Panneaux = forms.ImageField() class Meta: model = Panneaux fields = '__all__' panneaux/view.py from django.shortcuts import render from .models import Panneaux from .forms import PanneauxForm from django.shortcuts import redirect import cv2 import numpy as np # Create your views here. def create_panneaux(request): context = {} if request.method == "POST": form = PanneauxForm(request.POST, request.FILES) if form.is_valid(): nomP = form.cleaned_data.get("nom") descriptionP = form.cleaned_data.get("description") image_PanneauxP = form.cleaned_data.get("image_Panneaux") obj = Panneaux.objects.create( nom = nomP, description= descriptionP, image_Panneaux= image_PanneauxP ) obj.save() form= PanneauxForm() print(obj) return redirect('./ui-notifications.html') else: form= PanneauxForm() context['form'] = form return render(request, "./ui-tables.html", context) def latestPanneaux(request): context = {} … -
Django polymorphic inline - Double trouble in Django Admin
I'm redesigning an online shop in Django and I had to create a model for custom fields. This is how models.py looks like: import uuid from django.contrib import admin from django.db import models from polymorphic.models import PolymorphicModel class BaseModel(models.Model): class Meta: abstract = True id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False) class Product(BaseModel): [various standard fields] class Price(BaseModel): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='prices') price = models.DecimalField(max_digits=16, decimal_places=2) currency = models.CharField(max_length=3) class BaseCustomField(BaseModel, PolymorphicModel): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='custom_fields') name = models.CharField(max_length=64) def __str__(self): return f'{self.name}: {self.value}' class CustomBooleanField(BaseCustomField): value = models.BooleanField() class CustomCharField(BaseCustomField): value = models.CharField(max_length=64) [other custom fields, they all look more or less the same] From the shell I can create products and assign them any price and custom field without any problem, so the models should be OK. The problems begin when I want to create products from Django Admin, which will be my only choice when I upload the site to the production server. from nested_admin import NestedModelAdminMixin, NestedTabularInlineMixin, NestedStackedInlineMixin from polymorphic.admin import PolymorphicInlineSupportMixin, StackedPolymorphicInline from .models import Product, Price, BaseCustomField, CustomBooleanField, [...] class BaseModelAdmin(admin.ModelAdmin): readonly_fields = ['created', 'modified', 'created_by'] ordering = ['-created'] def save_model(self, request, obj, … -
How to fetch few variables in django url template?
If I have one variable being fetched from url template according to this regular expression: re_path(r'^reset/(?P<uid>[\w]+)/?$', accounts.api.views.SetNewPassword.as_view()), how to rewrite it to fetch few possible variables: either uid or u32id? -
get corresponding column value from the database foreign key in the selected combo/dropdown django modelform classview
I am sure this is a basic question but I am trying to move from windows application development to web based application. When I select the "SiteName" from the combo, I need to save Country as well in the database with form.save() Model.py class CountryMaster(models.Model): CountryName = models.CharField(max_length=50) Code = models.CharField(max_length=10) class SiteMaster(models.Model): SiteName = models.CharField(max_length=100) Code = models.CharField(max_length=10) Country = models.ForeignKey(CountryMaster, on_delete=models.CASCADE) class DataMaster(models.Model): CountryName = models.ForeignKey(CountryMaster, on_delete=models.DO_NOTHING) SiteName = models.ForeignKey(SiteMaster, on_delete=models.DO_NOTHING) Forms.py class DataModelForm(forms.ModelForm): class Meta: model = DataMaster fields = 'SiteName' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['SiteName'].widget.attrs['class'] = 'form-control' view.py class DataCreateView(CreateView): template_name = "add_data.html" form_class = DataModelForm def get_success_url(self): return reverse("myData:data_dashboard") def form_valid(self, form): form.save() # data = form.save(commit=True) # data.save() messages.success(self.request, "You have successfully Added Data") return super(DataCreateView, self).form_valid(form) mypage.html {% extends 'base_data.html' %} {% load static %} {% block content %} <div class="content"> <form method="post" class="mt-5"> {% csrf_token %} <div class="container-fluid"> <div class="row"> <div class="col-lg-6"> <div class="card"> <div class="card-body"> <div class="form-group"> <label>Select Site Name:</label> {{ form.SiteName.errors }} {{ form.SiteName }} </div> </div> </div> </div> <div class="row"> <div class="col-lg-1"> <button type="submit" class="btn btn-block bg-gradient-primary">Add Data</button> </div> </div> </form> </div> {% endblock content %} I need to add the corresponding country on SiteName selection from … -
Django REST Framework permission_classes ModelViewSet
How do I create a permission, that only allows the user to be able to read, if they are logged in. If they are not logged in, they can not do anything. I feel like this is probably very easy, but I can't seem to find the answer. This is my views.py file: class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, ) I know IsAuthenticatedOrReadOnly allows the User to read, but I don't even want that. -
'QuerySet' object has no attribute 'time'
I am building a BlogApp and I am trying to access a model instance. BUT i am stuck on an Error. The error is keep showing 'QuerySet' object has no attribute 'time' models.py class Gallery(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) text = models.CharField(max_length=30,blank=True) time = models.CharField(max_length=30,choices=CHOICES,default='24_hours') class Photo(models.Model): photo = models.ForeignKey(Gallery,related_name='imagess',on_delete=models.CASCADE) file = models.FileField(upload_to='images') views.py def timeManage(request): varia = Gallery.objects.filter(user=request.user) show = varia.time context = {'varia':varia} return render(request, 'timeMan.html', context) I have also tried by using 'time = Photo.objects.filter(gallery__user=request.user)` BUT this error is still showing. I have no idea what i am doing wrong. Any help would be Appreciated. Thank You in Advance. -
search/filter with list of string graphene-django
I am looking to search for list of different characters/string using graphene-django with single search query run. ** class CandidateType(DjangoObjectType): class Meta: model = Candidate fields = "all" class Query(graphene.ObjectType): candidateInfo = graphene.List(CandidateType, search=graphene.String(), first=graphene.Int(), skip=graphene.Int(), last=graphene.Int(),) def resolve_candidateInfo(self, info, search=None, first=None, last=None, skip=None, **kwargs): qs = Candidate.objects.all() if search: filter = ( Q(candidateName__icontains=search)| Q(candidateEmail__icontains=search)| Q(candidateSkills__icontains=search) ) qs = qs.filter(filter) return qs ** Here the candidateName, candidateSkills, candidateEmail are in Candidate class with models.CharField With a single string/character search i am getting correct output. But it fails with list of sting/characters. -
I want to split funds using PayPal Django using django-paypal
I want to pay to the seller for his sold products How can I do this using in django please help. I'm looking into paypal payouts but is there any SDK? or anything that can help me? -
Remove remaining celery tasks when concurrency is set to 1?
I have a Django application running with Docker, I'm looking for a way to terminate the remaining celery tasks when the concurrency is set to 1. This is my urls.py file from django.urls import path from . import views urlpatterns = [ path('start-process', views.start_process), path('terminate-process', views.terminate_process), ] This is my views.py file from .tasks import add_task, remove_tasks def start_process(request): add_task.delay() return HttpResponse('Task Started') def terminate_process(request): remove_tasks.delay() return HttpResponse('All remaining tasks will be removed') This is my tasks.py file from celery import shared_task from my_app.celery import app from time import sleep @shared_task def add_task(): sleep(50) return 'task completed' @shared_task def remove_tasks(): app.control.purge() return 'All tasks removed' This does not work as expected because the concurrency is set the 1. I have started the celery worker with the following command celery -A my_app worker --concurrency=1 --loglevel=info Is there any way I can remove the remaining tasks when the terminate-process url is called? -
djnago View - how get a count queries from view?
how can I get the number of db requests during a view call? connetction.queries return empty list. My views.py: def get_context_data(self, **kwargs): context = super(OrderListView, self).get_context_data(**kwargs) date = Order.objects.get(number=1).created_date last_date = Order.objects.all().order_by('id').last() filter_ = Order.objects.filter(created_date__lte=date, created_date__gte=last_date.created_date) if self.request.GET: since_date = self.request.GET.get('date_since') to_date = self.request.GET.get('date_to') filter_ = filter_.filter(created_date__lte=since_date, created_date__gte=to_date) context['OrderListView'] = filter_ context['connections'] = connection.queries return context -
Django Image Resizing Before Upload
Currently, If I upload an image, It shrinks the image size then overwrites the file inside AWS s3 storage Media file and name it to the the file's original name For example: If i upload a 1MB size image called AA.png, It shrinks the size to 50KB, Then in AWS S3 Media file you would find the shrinked image named AA.png I want: File extension to always be .jpg, Eg: User uploads .png but stored as .jpg in AWS S3 Media Give each image a unique name generated by random numbers or strings If I change to storage.save("{random_number}.jpg", memfile), then the above problems could be solved, But it creates 2 Images in the S3 Media file, Eg: If a user uploads 1mb AA.png, Then results in S3 Media would be: some_random_number.jpg(50kb), AA.png(1MB, untouched original image), If I am correct, The image files in S3 are being overwritten if it has the same name, Is there a way to shrink the image in Django before it reaches S3 Media file and prevent the original image from being stored in the first place? Models.py: from PIL import Image from django.core.files.storage import default_storage as storage from io import BytesIO class Card(models.Model): photo_1 = … -
Run django+nginx+celery+gunicorn+daphne on docker
I have been trying for long to run my django application using docker but unable to do so. Application works fine using normal architecture like deploying on ubunutu compute engine. Below is the Dockerfile.prod ######### # FINAL # ######### # pull official base image FROM ubuntu:20.04 # create directory for the app user RUN mkdir -p /home/app # create the app user RUN adduser app RUN usermod -a -G app app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles WORKDIR $APP_HOME # install dependencies ARG DEBIAN_FRONTEND=noninteractive RUN apt-get update RUN apt-get upgrade RUN apt-get install python3-pip nano -y RUN apt-get install postgresql-contrib libpq-dev python-dev -y RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint-prod.sh COPY ./entrypoint.prod.sh $APP_HOME # copy project COPY . $APP_HOME # chown all the files to the app user RUN chown -R app:app $APP_HOME # change to the app user USER app RUN ls # run entrypoint.prod.sh ENTRYPOINT ["/home/app/web/entrypoint.prod.sh"] Below is docker-compose.prod.yml version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn Reporting.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles expose: - 8000 env_file: - ./.env.prod depends_on: - db - rabbitmq - redis db: … -
Use of Django Filter
Helloo! I have a project that works with Requests. I have a table with request_name, Department,... What I want is: for every user logging in to have only request from his department. Please help to achieve this. Thank you -
Problems deploying Django on a web server hosting multiple sites
Currently I am working on migrationg a Django site (app) to a hosting service, folder structure is as follows: /home/user /public_html /example.com /example.ee - wordpress site, needs to keep working /example.fi - where I am trying to deploy the django app When I try to install a Python app from cPanel, and set up everything to work for django application, wordpress site and all others return a 500 internal server error, how could I deploy django only for one domain without affecting other domains at all... also a problem is if I set ALLOWED_HOSTS=['*'] it does load the other pages but it loads them wrong (showing a wrong page as the home page etc.) I have searched online for a day now and I can't seem to find the answer, cPanel installs the python virtualenv into the user home directory and not in the public_html folder, where I would like it to run. and I want it to only affect the domain it is a part of. Relevant server information: Server Name : Servername cPanel Version : 94.0 (build 10) Apache Version : 2.4.46 PHP Version : 7.3.27 MySQL Version : 10.3.28-MariaDB-log-cll-lve OS : Linux -
Django template VS Angular/React/Vue - Perforamance
Since i am confused to either combine django and any javascript framework or use django templates. I would like to know to following queries, How will be the performance will effect if i combine both of them together instead of django templates? Why people prefer to combine 2 frameworks together and will they prefer for huge projects like ERP and why? Since connecting and fetching data from database like MySQL and NoSQL have major impact on performance, Does REST API (or any other way) will solve the problem? Because django templates providing inbuit functions to display the data (Suppose we have to add loop in front end and backend) I hope you will consider seconds of time for the performance monitoring. Why not bootstrap? Note : I am new to front end frameworks. -
Does Google "validate" forgotten password links? [closed]
I am working on a web app using Django (hosted on Heroku). I was testing the password reset functionality and it all worked as expected. However, I found in the web logs that after I had accessed the generated link that the exact same URL was requested 14 minutes later by a different IP address. The link had expired so the response was a 400 code. For reference, the password reset link looks like this and was sent to my gmail account: https://www.example.com/password_reset/[uidb64]/[token]/ I looked up the IP address and it shows the following host name: [town]-google-cdn-01.network.[UK-ISP].net There is no other unusual traffic to the site and my email account is secure. The only thing I can think of would be if Google were to check unidentified password reset links for phishing threats, but is that actually a thing? Is there any other way that the URL could be found? -
Inconsistent Migration History
I am trying to build a custom user model on django. I deleted all the files except init.py from migrations in the personal folder. whenever I run python manage.py makemigrations I get this error InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'. this is how my director looks like: Can someone please guide me through this problem