Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python-Django: How to list what is the specific database used of a specific application
I'm currently handling a existing project and just want to have an enhance on one of its specific application. There is a list of Databases in the settings and currently hard to find what application 1 database use. For example I have 5 Application and in the settings I have 10 Databases. I just want application 1 to be enhance/developed and the rest of the app not included when I migrate. Is there anyway that I just going to list what application 1 database used? So that the listed databases that application 1 use is the only databases that I'm going to include to the settings. Since I just going to have the databases limitedly copy to a dev server not the whole prod server. -
Deploy ML Model GCP / Django at scale, how to manage session?
I have build my model (dump file), but I need to deploy it for some users (maybe 10 for the first time). This is a chatbot, but: Every message linking to the previous message (Hello how can I help you?....I need tips for that.... Ok which tips??...) This is a web app, the first architecture that I think is to use: Flask Rest / FastAPI to deploy model as an API in cloud run (GCP) I'am using Django REST for the web back-end side, so, I would like to call the ML Model rest api in the django part. So, the ideal pattern is every users can access to a dedicated chatbot (ML Model). from fastapi import FastAPI app = FastAPI() MODEL="./model/mdel.dump" ... -
How django drop column in SQLite
Don't be confused. I am not asking how to drop column in Django. My question is what Django actually does to drop a column from a SQLite database. Recently i came across an article that says you can't drop columns in SQLite database. So you have to drop the table and recreate it. And its quite strange that if SQLite doesn't support that then how Django is doing that? Is it doing this? -
Handling multiple GET variables with Django
I have a view template that has multiple forms that can be handled by get data. Such as a search function, a number of entries per page dropdown, and a pagination. I was wondering how I could go about having all of these work together without overwriting the other, for example: www.website.com/account/?entries_per_page=5 This could be the url the user is currently on but lets say they search for "pineapple", I would like for it to goto: www.website.com/account/?entries_per_page=5&search=pineapple instead of, www.website.com/account/?search=pineapple but also we have to keep in mind the page the user is on unless they do a new search: www.website.com/account/?entries_per_page=5&search=pineapple&page=2 or www.website.com/account/?search=pineapple&page=2 I hope this isn't confusing, I really have been stuck on this and have not been able to figure out what to do. -
AttributeError at /cars/add_car 'int' object has no attribute 'get'
I want to add a Car to my database by using html inputs instead of forms. But when I run the code I get this error. I am new to django so I couldn't understand the similar problems that people had. AttributeError at /cars/add_car 'int' object has no attribute 'get' My full Traceback output Environment: Request Method: POST Request URL: http://127.0.0.1:8000/cars/add_car Django Version: 3.1.7 Python Version: 3.9.0 Installed Applications: ['cars.apps.CarsConfig', 'pages.apps.PagesConfig', 'accounts.apps.AccountsConfig', 'contact.apps.ContactConfig', 'houses.apps.HousesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'django.contrib.humanize', 'django.contrib.sites'] Installed Middleware: ['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'] Traceback (most recent call last): File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /cars/add_car Exception Value: 'int' object has no attribute 'get' My views.py def add_car(request): if request.method == 'POST': user_id = request.POST['user_id'] brand = request.POST['brand'] status_of_car = request.POST['status_of_car'] city = request.POST['city'] ilce = request.POST['ilce'] e_mail = request.POST['e_mail'] phone_number = request.POST['phone_number'] car_title = request.POST['car_title'] description = request.POST['description'] price = request.POST['price'] serial = request.POST['serial'] color = request.POST['color'] model = request.POST['model'] year = request.POST['year'] condition = request.POST['condition'] body_style = request.POST['body_style'] engine = request.POST['engine'] transmission … -
Why my Django 3.2 admin CSS is not working
I am really really frustrated being failed to find the issue. My django 3.2 admin is looking like without CSS only HTML. I am new to django. I don't know what happened. I have collected static files(CSS, Js, etc.) into the static folder of the project by this command: python manage.py collectstatic I also used whitenoise package to manage this stuff. But failed to do as a beginner. I need help please with the 3.2 version. Any help is really really appreciated. enter image description here enter image description here Here is my settings.py of the project """ Django settings for mac project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-6r-t8omh%(8(lxk1divtd2vb(f7@r&vq7n4#v9wx%4g+z9&6v3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'shop.apps.ShopConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Django serializing json
I'm building an API using django and I have come across a problem. I have a UserDetail model that has a foreing key to a User model. class UserDetail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.CharField(max_length=200, default="", blank=True) I want to serialize the information of User and the information of UserDetails in one json and this is what I'm currently doing: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') class DetailSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = UserDetail fields = ('user', 'about',) Right now I obtain this: { "user": { "username": "julia", "first_name": "antonia", "last_name": "uri", "email": "as¡¡test@test.test" }, "about": "" } But I want to obtain the information of UserDetail from User, not the other way around (like I'm currently doing) so that I get the information like this: { "username": "julia", "first_name": "antonia", "last_name": "uri", "email": "test@test.test", "details": { "about": "" } } I would really appreciate if someone could tell me what I'm doing wrong. Thank you! -
type object '...' has no attribute 'objects'
In models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Espresso(models.Model): employee = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_esp_log") time = models.DateTimeField(auto_now_add=True, blank=True) water_temp = models.DecimalField(max_digits=3, decimal_places=1) water_TDS = models.DecimalField(max_digits=3, decimal_places=2) name = models.CharField(max_length=2, choices=ESPRESSO_TYPES, default= ESPRESSO_TYPES[0][1]) batch_number = models.DecimalField(max_digits=4, decimal_places=0) dry = models.DecimalField(max_digits=4, decimal_places=2) wet = models.IntegerField() def __str__(self): return f"Log added on {self.time} by {self.employee}" In views.py the 'create_espresso' route attempts to create a new log as follows: def create_espresso(request): if request.method == "GET": return render(request, "score_sheet/espresso.html", {"form": Espresso()}) else: form = Espresso(request.POST) user = User.objects.get(username=request.user) if form.is_valid(): espresso = form.save(commit=False) espresso.employee = user espresso.save() espressos = Espresso.objects.all() return render(request, "score_sheet/index.html", { "espressos": espressos, "message": "Log added" }) else: return render(request, "score_sheet/espresso.html", {"form": form}) Also, here's the form POSTING to the view: {% block body %} <form action="{% url 'create_espresso' %}" method="POST"> {% csrf_token %} {{ form.as_table }} <button class="btn btn-success">Log</button> </form> {% endblock %} On submitting the form Django returns the following: type object 'Espresso' has no attribute 'objects' Here's the stacktrace in case it's needed: Internal Server Error: /create_espresso Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site- packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
Is there anyway to reduce the bitrate of cv2.VideoWriter live camera record video?
I have a python project that reads frames from a ip_camera and writes it in a .avi video, but its size is becomes too large for example a 1 min record has a size about 200 MB. I want to reduce the video bitrate to reduce the size at same time that the video is being written. I tried so many ways but none of them worked out. Here is my code: import os from threading import Thread import cv2 class VideoCamera(object): def __init__(self, src=''): self.capture = cv2.VideoCapture(src) self.status = False self.frame = self.capture.read() self.frame_width = int(self.capture.get(3)) self.frame_height = int(self.capture.get(4)) self.record_date = record_date self.camera_id = camera_id self.codec = cv2.VideoWriter_fourcc(*'MJPG') self.video_name = "video.avi" self.output_video = cv2.VideoWriter( self.video_name, self.codec, 5, (self.frame_width, self.frame_height)) self.stream_thread = Thread(target=self.update, args=()) self.record_thread = Thread(target=self.record, args=()) self.stream_thread.daemon = True self.stream_thread.start() def update(self): while True: if self.capture.isOpened(): (self.status, self.frame) = self.capture.read() def record(self): print('schedule') while True: print('stop recording') self.capture.release() self.output_video.release() cv2.destroyAllWindows() break try: if self.status: self.output_video.write(self.frame) frame_count += 1 except AttributeError: pass def start_recording(self): self.record_thread.start() if __name__ == '__main__': cam = VideoCamera('rtsp://<username>:<password>@<camera_ip>:<camera_port>') cam.start_recording() -
In Django I want to retrieve the selected file name the file is in my media folder i want to fetch it and display it in html
This is my html code for update the form I have the uploaded file through a html form and the pdf file is getting stored in my media folder and the file name in database, so like the text fields I also want to retrieve the selected file from the media folder the value ="{{i.cv}}" is not working like I did it in text fields so basically I have two html one is for filling up where there is also file field am uploading pdf files in it and it is storing in media folder another html for updating the data in there the upload cv does not select any file what's the solution for this. this is my html <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black">Upload CV</label></br> <input type="file" name="cv" id="cv1" value ="{{i.cv}}"> </div> </div> here is models.py class ApplyForm(models.Model): cv = models.FileField(upload_to='') this is views.py def update(request, id): i.cv = request.FILES['cv'] I just want the file to be selected during edit I am uploading pdf files -
How to organize Caching in Django?
I'm trying to figure out how to properly organize caching. There are actually two questions. Is it okay to implement caching like this? Perhaps there is a better option? class PostsListView(ListView): template_name = 'pages/post_list.html' def get_queryset(self): posts_list_qs = cache.get('posts_list_qs') if not posts_list_qs: posts_list_qs = get_all_posts() cache.set('posts_list_qs', posts_list_qs) return posts_list_qs What is the best way to invalidate this cache? What if I have a dozen of views / asynchronous functions, etc that require data from Posts. Just listing all the keys in signals like this? Should be a better way I think...And what if I need to use 'prefetch related'(inner join) for some request to database? I even need to repeat cache.delete(key) in signals for some other models. @receiver(post_save, sender=Post) def post_post_save(sender, instance, created, *args, **kwargs): cache.delete('posts_list_qs') cache.delete('posts_data_for_api_qs') cache.delete('posts_data_for_views_qs') cache.delete('posts_data_for_email_sending_qs') Please, advise me about how to organize work with the cache in the best way!? -
MultiValueDictKeyError varies in localhost and Heroku host
I'm currently learning django and I've created a simple TODO project which has an otp authentication feature. While running the project in localserver otp was generated and stored in the model which is then matched by using if (t.otp == int(request.POST['otp'])): where t is a model object. This works perfectly fine. While I deployed the same in heroku server with DEBUG = True for testing purpose, it is throwing MultiValueDictKeyError in line if (t.otp == int(request.POST['otp'])):. Initially t.opt is set to the value generated and it is reinitialized to 0 once the user enters the correct OTP and registers. Kindly notice the comments in the code that explains the issue a bit more. My views.py goes as (I've removed some elif part that are not required to reduce the number of lines), def regsub(request): if(request.method=="POST"): uname = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = str(request.POST['email']) pass1 = request.POST['pass1'] try: **#this tries to get the values pass1 and pass 2 whereas except gets the value otp** if(request.POST['pass1']==request.POST['pass2']): dictpass = { 'username':uname, 'fname':fname, 'lname':lname, 'email':email, 'password':pass1, } the_otp = r.randint(100000,999999) try: t=temp.objects.create(name=uname,otp=the_otp) t.save() except(IntegrityError): return render(request,'register.html',{'flag':True,'msg':"Username already exits! Please try again."}) sub = "OTP for registration" msg = "Some Message … -
How to use a test bucket for MinIO?
I'm writing a Django app, and I use Minio as my object storage. I use this python package.enter link description here I want to create a test bucket for my unit tests. What should I do? In my models.py file, I add a default bucket to save objects; I don't know what I should do for the test request. It is my model: class PrivateAttachment(models.Model): file = models.FileField(verbose_name="Object Upload", storage=MinioBackend(bucket_name='django-backend-dev-private'), upload_to=iso_date_prefix) I really appreciate any help you can provide. -
Failed to build cryptography greenlet ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
A client sent to me an app-web in python-django, I am trying to run app on my local windows 10 Installed docker desktop for w10. Then run docker-compose -f local.yml build And I got an error while building: #8 83.78 Failed to build cryptography greenlet #8 83.78 ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly The weird thing its that I dont have cryptography in my requirements files: base.txt pytz==2018.5 # https://github.com/stub42/pytz python-slugify==1.2.5 # https://github.com/un33k/python-slugify Pillow==5.2.0 # https://github.com/python-pillow/Pillow argon2-cffi==18.3.0 # https://github.com/hynek/argon2_cffi whitenoise==4.0 # https://github.com/evansd/whitenoise redis>=2.10.5 # https://github.com/antirez/redis django-background-tasks==1.2.0 # https://github.com/arteria/django-background-tasks # Django # ------------------------------------------------------------------------------ django~=2.1.0 # https://www.djangoproject.com/ django-environ==0.4.5 # https://github.com/joke2k/django-environ django-model-utils==3.1.2 # https://github.com/jazzband/django-model-utils django-allauth==0.37.1 # https://github.com/pennersr/django-allauth django-crispy-forms==1.7.2 # https://github.com/django-crispy-forms/django-crispy-forms django-redis==4.9.0 # https://github.com/niwinz/django-redis # Django REST Framework djangorestframework~=3.9.0 # https://github.com/encode/django-rest-framework coreapi==2.3.3 # https://github.com/core-api/python-client django-filter djangorestframework-filters==1.0.0.dev0 drf-flex-fields~=0.3.5 # Channels channels~=2.1.5 # https://github.com/django/channels channels_redis~=2.3.1 # https://github.com/django/channels_redis local.txt -r ./base.txt Werkzeug==0.14.1 # https://github.com/pallets/werkzeug ipdb==0.11 # https://github.com/gotcha/ipdb Sphinx==1.7.7 # https://github.com/sphinx-doc/sphinx psycopg2==2.7.4 --no-binary psycopg2 # https://github.com/psycopg/psycopg2 bpython~=0.17 # Testing # ------------------------------------------------------------------------------ pytest==3.7.3 # https://github.com/pytest-dev/pytest pytest-sugar~=0.9.1 # https://github.com/Frozenball/pytest-sugar # Code quality # ------------------------------------------------------------------------------ flake8==3.5.0 # https://github.com/PyCQA/flake8 coverage==4.5.1 # https://github.com/nedbat/coveragepy # Django # ------------------------------------------------------------------------------ factory-boy==2.11.1 # https://github.com/FactoryBoy/factory_boy django-debug-toolbar==1.9.1 # https://github.com/jazzband/django-debug-toolbar django-extensions==2.1.2 # https://github.com/django-extensions/django-extensions django-coverage-plugin==1.5.0 # https://github.com/nedbat/django_coverage_plugin pytest-django==3.4.2 # https://github.com/pytest-dev/pytest-django django-cors-headers … -
Filter objects manyTomany with users manyTomany
I want to filter the model Foo by its manyTomany field bar with users bar. Models class User(models.Model): bar = models.ManyToManyField("Bar", verbose_name=_("Bar"), blank=True) class Foo(models.Model): bar = models.ManyToManyField("Bar", verbose_name=_("Bar"), blank=True) class Bar(models.Model): fubar = models.CharField() with this user = User.objects.get(id=user_id) I want to gett all Foo's that have the same Bar's that the User has. I would like this to work: bar = Foo.objects.filter(foo=user.foo) but it doesn't work. -
Custom queries in django serializers
I have the following view that allows me to determine defined prices for the logged in user and captures the information of the provider model requested by the user: class ProductStoDists(mixins.ListModelMixin, generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,IsSavedRole) queryset = SellProduct.objects.select_related("provider", "product", "coupon_percentage", "coupon_quality").filter(~Q(stock = None), Q(disabled_sale=False)) serializer_class = SellProductSerializer parser_classes = (MultiPartParser,) filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ["product", "provider", "provider__state_prin_venue", "product__sectors", "product__categories", "provider__type_provider"] pagination_class = Pagination def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) #@method_decorator(cache_page(60*60)) #@method_decorator(vary_on_cookie) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) entity = Provider.objects.filter(administrator=request.user) data_price = [] if page is not None: serializer = self.get_serializer(page, many=True) object_dataset = DataSetIds() if request.user.role != "lab": prices = [] for sell_product_cost in serializer.data: provider = Provider.objects.filter(id_provider=sell_product_cost["provider"]).select_related("country_prin_venue", "state_prin_venue", "city_prin_venue", "administrator") price_object = CustomPrices(entity, request.user.id, provider) if provider[0].type_provider == "dist": if request.user.role == "dist" or request.user.role == "sto": sell_product_cost["distributors"] = price_object.get_sell_distributors(sell_product_cost["id_sell"]) else: sell_product_cost["distributors"] = None else: if request.user.role == "sto": sell_product_cost["storage"] = price_object.get_sell_storage(sell_product_cost["id_sell"]) else: sell_product_cost["storage"] = None return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) How could I make the "storage" or distributors field be done from the serializardor and not from the view?, since I consider that this can slow down the response of the customer service. -
Accessing attributes on different types of profiles
I've got two different type of user profile defined in my project: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) full_name = models.CharField(max_length=128) address = models.CharField(max_length=256) class Meta: abstract = True class ProfileA(Profile): # Special fields related to ProfileA class ProfileB(Profile): # Special fields related to ProfileB While I need to access the attributes on user's profile I use hasattr to detect profile type, something like: if hasattr(request.user, profilea): print(request.user.profilea.address) else: print(request.user.profileb.address) Or in templates: {% if user.profilea %} {{ user.profilea.address }} {% else %} {{ user.profileb.address }} {% endif %} To make it simpler I wrote a middleware to set profile attribute on request.user: if hasattr(request.user, "profilea"): request.user.profile = request.user.profilea request.user.is_a = True else request.user.profile = request.user.profileb request.user.is_a = False So now I can use something like {{ user.profile.address }} in my templates and request.user.profile.address in my Views. However my problem raise where I have to deal with a set of Users with different type of profile. Now I have to constantly use conditions every where I need to access attributes on User's profiles. I can also write a template tag: @register.filter def is_a(obj): if hasattr(obj, 'profilea'): return True return False And use it like: {% if user|is_a %} {{ user.profilea.address … -
How to customize the text in change_form template of Admin dashboard in Django?
I want to remove the word 'Another' from change_form template as shown in the image. Other Details is a StackedInline model. I tried overriding the template to remove the text but could not find a way. Please give a suggestion or a solution to this. Thanks in advance -
Invalid block tag 'else'. Did you forget to register or load this tag?
Why I got this error? I have this error on django, while it's working correctly on flask. 1 {% if user.is_authenticated %} 2 {% extends "home.html" %} 3 {% else %} 4 {% extends "index_not_auth.html" %} 5 {% endif %} TemplateSyntaxError at / Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.2 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? Exception Location: D:\GitHub Repositories\Django-WebApp\venv\lib\site-packages\django\template\base.py, line 534, in invalid_block_tag Python Executable: D:\GitHub Repositories\Django-WebApp\venv\Scripts\python.exe Python Version: 3.6.1 -
Through relationship using polymorphic model
I'm trying to use a through relationship between a polymorphic and a non-polymorphic table with the the RankedAthlete model: class ChoiceBlank(PolymorphicModel): pass class ChoiceAthlete(ChoiceBlank): choice = models.ForeignKey('SomeModel', on_delete=models.CASCADE) class BetMultiple(models.Model): answer = models.ManyToManyField('ChoiceBlank', blank=True, through='RankedAthlete') class RankedAthlete(models.Model): choiceAthlete = models.ForeignKey('ChoiceBlank', on_delete=models.CASCADE) bet = models.ForeignKey('BetMultiple', on_delete=models.CASCADE) rank = models.IntegerField() This doesn't work because RankedAthlete expects a ChoiceBlank and a ValueError is raised when I create one. Conversely, I can't migrate my db if I replace choice with a ChoiceAthlete. Django-polymorphic doc doesn't mention my use case, is it unsupported? Is there a way to make this work? -
Best practices for long running tasks in django
I am developing web app on django. One of the problem that I encounter, is long running tasks, that can execute during weeks or more. I am talking about Campaign entity. User creates one, launch and can wait and see intermidiate results. What is the best practise to implement such tasks in django. One of the options that I could find is celery and rabbitmq. -
Django: display many to many relationship through a model in themplate
I have this ManyToMany relationship through an intermediary model: class Group(models.Model): members = models.ManyToManyField(Student, through='NamedMembershipClub') class Membership(models.Model): year = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) I'm trying to display members with the year they joined in my template. I read on this post that I should use members_set.all {% for member in object.members_set.all %} <p>{{member.user.first_name}} {{member.year}}</p> {% endfor %} But it doesn't produce any output, the loop is just not entered because the set is empty. I also tried : {% for member in object.members.all %} <p>{{member.first_name}}</p> {% endfor %} Which gives some satisfaction because I can display the user but not the associated data in the Membership model. Is there any way to get the set directly in the template ? Thanks! I'm running Django 3.0. -
How can i filter by date min and date max with rows?
how can i get a filter by date min and date max without model, i connect to a external database and get a consultation but cant filter Add code here: views.py def BootstrapFilterView(request): cursor.execute("[Prueba].[dbo].[Pr_Ne] '10/04/2021 4:00:00', '28/05/2021 23:59:59'") qs = cursor.fetchall() prog_data_ini = request.GET.get('prog_data_ini') date_min = request.GET.get('date_min', None) date_max = request.GET.get('date_max', None) fecha = datetime.now() format_min = fecha.strftime('%Y-%m-%d') date_max = fecha + timedelta(days=1) format_max = date_max.strftime('%Y-%m-%d') if is_valid_queryparam(date_min): qs = qs.filter(prog_data_ini__gte=date_min) if is_valid_queryparam(date_max): qs = qs.filter(prog_data_ini__lt=date_max) html <div class="input-group date"> <b class="b-form">DESDE:</b><input type="date" class="form-control" id="publishDateMin" name="date_min" value="{{format_min}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> <div class="input-group date"> <b class="b-form">HASTA: </b> <input type="date" class="form-control" id="publishDateMax" name="date_max" value="{{format_max}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> -
Django: Show media files to authenticated users only
I'm on Django 3.2 not using django's default server and I want to restrict certain media[mostly pdf files] inside the media directory to logged in users only. Is there any way to do that? Thanks. PS:I'm aware of a question similar to this,but it is on django v1.x and Nginx -
how to send nested functions data to another function in python
I want to display the value of a variable in world function. def base(): print("Hello World") def child(): a = 10 return a def world(): num = base.child() # error ------- print(num) world()```