Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model autogenerate from a legacy mysql database: do I have to change the on_delete parameter's value from models.DO_NOTHING
I write a sql file for a mysql database as follows: create table bank ( bankname VARCHAR(20) not null, city VARCHAR(20) not null, money DOUBLE not null, constraint PK_BANK primary key (bankname) ); create table department ( departID CHAR(4) not null, departname VARCHAR(20) not null, departtype VARCHAR(15), manager CHAR(18) not null, bank VARCHAR(20) not null, constraint PK_DEPARTMENT primary key (departID), Constraint FK_BANK_DEPART Foreign Key(bank) References bank(bankname) ); create table employee ( empID CHAR(18) not null, empname VARCHAR(20) not null, empphone CHAR(11), empaddr VARCHAR(50), emptype CHAR(1), empstart DATE not null, depart CHAR(4), constraint PK_EMPLOYEE primary key (empID), Constraint FK_DEPART_EMP Foreign Key(depart) References department(departID), Constraint CK_EMPTYPE Check(emptype IN ('0','1')) ); create table customer ( cusID CHAR(18) not null, cusname VARCHAR(10) not null, cusphone CHAR(11) not null, address VARCHAR(50), contact_phone CHAR(11) not null, contact_name VARCHAR(10) not null, contact_Email VARCHAR(20), relation VARCHAR(10) not null, loanres CHAR(18), accres CHAR(18), constraint PK_CUSTOMER primary key (cusID), Constraint FK_CUS_LOANRES Foreign Key(loanres) References employee(empID), Constraint FK_CUS_ACCRES Foreign Key(accres) References employee(empID) ); create table accounts( accountID CHAR(6) not null, money DOUBLE not null, settime DATETIME, accounttype VARCHAR(10), constraint PK_ACC primary key (accountID), Constraint CK_ACCOUNTTYPE Check(accounttype IN ('SaveAccount','CheckAccount')) ); create table saveacc ( accountID CHAR(6) not null, interestrate float, savetype CHAR(1), … -
Django: How to compare two querysets and get the difference without including the PK
I don't think the word difference is correct because you might think difference() but it makes sense to me what I am trying to achieve. I do apologize if this is a common problem that's already been solved but I can't find a solution or dumbed down understanding of it. I have two querysets of the same model as follows: qs1 = ErrorLog.objects.get(report=original_report).defer('report') # 272 rows returned qs2 = ErrorLog.objects.get(report=new_report).defer('report') # 266 rows returned I want to compare the first one to the second one and find the 6 rows that don't match in the first qs1 I tried difference() and intersection() but I keep ending up with the same 272 rows or 0 rows. I have a feeling that it sees pk as a unique value so it never finds matching rows. I tried the following: # Get the 4 fields I want to compare and exclude field_1 = [error.field_1 for error in qs2] field_2 = [error.field_2 for error in qs2] field_3 = [error.field_3 for error in qs2] field_4 = [error.field_4 for error in qs2] # Assuming this would work qs3 = qs1.exclude(field_1__in=field_1, field_2__in=field_2, field_3__in=field_3, field_4__in=field_4) # But ended up with 10 rows in qs3 since it doesn't loop … -
How to restrict user going back after logout Using DJANGO
views.py def logout_user(request): # Contact Page logout(request) messages.success(request, f'logout successful') return redirect('login') -
ADDing file via Browsable Api in django rest framework
I am new to django and rest framework. There are two models named Video and Course and ManyToMany relationship as described below. class Video(models.Model): video = models.FileField(upload_to='static', null=True, blank=True) class Course(models.Model): title = models.CharField(max_length=250) video = models.ManyToManyField(Video) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) def __str__(self): return self.title When I add new course via admin panel, I can add new video to server by + sign in the right side. However, when I try to add new course via browsable API,(by POST method) It looks like I can only use videos which are already in the server, so I cant add new one.How can I add new Video when I add new course via api? -
django model method to return queryset with annotate
i am trying to define a field which being calculated based on user_type, I did the following method but its not working, if anyone can advise me to the correct approach. so what i am trying to achieve here is to construct a method such as <user>.book_limit to return the maximum number of allowed books based on user_type #models.py class UserProfile(models.Model): class UserType(models.TextChoices): FREE = 'FR', 'FREE' BASIC = 'BS', 'BASIC' PREMIUM = 'PR', 'PREMIUM' user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') bio = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) user_type = models.CharField(max_length=2, choices=UserType.choices, default=UserType.FREE) def __str__(self): return self.user.username @property def borrow_limit(self): return UserProfile.objects.annotate(book_limit=Case( When(user_type=UserProfile.UserType.FREE, then=Value('1')), When(user_type=UserProfile.UserType.BASIC, then=Value('2')), When(user_type=UserProfile.UserType.PREMIUM, then=Value('5')), default=Value('1'), output_field=IntegerField)) -
django url doesn't redirect properly
I am trying to send user to next page using button like this <a href="weekly/" class="btn">Weekly Report</a> <a href="daily/" class="btn">Daily Report</a> but when i click on header or another button at daily url keeps stacking like daily/weekly instead /daily or /weekly. It doesn't clear url and go to button instead just keeps adding it. this is url.py urlpatterns = [ path('', views.index, name="Home"), path('weekly/', views.weekly, name="weekly"), path('daily/', views.daily, name="daily"), ] i tried different ways to call url like {% url 'weekly' %} but still its same. All urls only keep stacking. even home page button does keep stacking -
How to store multiple values in a CharField in Django
Using TaggableManger from django_taggit didn't worked for two fields. The requirement is I have two fields in which I have to save the multiple keywords.For example user can give inputs like Hello World, 'Hi' and so on and I have to store them in one field and same goes to the another field also.How can I design my models properly ? class MyModel(models.Model): one_field = TaggableManager() another_field = TaggableManager() -
Am i missing something on templates on django
This is my code on html file on a django project. I am using this cod on this function def home(request): context = { 'post': posts } return render(request, 'blog/home.html', context) Template: <html> <head> <title> </title> </head> <body> {% for post in posts %} <h1>{{post.title}}</h1> <p>By {{post.author}} on {{post.date_posted}}</p> <p>{{post.content}}</p> {% endfor %} </body> </html> -
Why is MySQL Fulltext index not functioning?
I have a user table that looks something like this for testing: USER ---------------------------------- id username name 1 "djangoIsAwesome" "Ale" 2 "craze123" "John" 3 "hope this works" "JJ" 4 "Rage" "Ludo" 5 "coolguy1996" "Frank" I need to execute extremely performant queries that respond as the user is typing for a user. Normally one would use the LIKE %string% strategy but I can not afford to here as the USER table has millions of rows. I created a Fulltext index like so ALTER TABLE app.user ADD FULLTEXT ft_index_name(username, name); However, I tested the supposedly performant query: SELECT id, username, name FROM app.user WHERE MATCH (username, name) AGAINST ({string}); But I am not getting any rows returned in the query. I have also tried all the different modes (boolean, natural langauge, query extension) with no difference. Strings I have tried: "J", "wesome", "96", "k" What is wrong? -
MultipleObjectsReturned at /cart/ get() returned more than one Order -- it returned 3
I want to use get_or_create in my code, but when it returns more than one record, it shows MultipleObjectsReturned error. If there is single record its runs fine. Code at Views.py def cart(request): if request.user.is_authenticated: customer=request.user.customer order , created=Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() else: items=[] order={'get_cart_total':0, 'get_cart_items':0} context={'items':items, 'order': order} return render(request, 'store/cart.html', context) Any help will be appreciated. Thanks. -
Django project can't grab frames
[ WARN:1] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (1159) CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638 I am trying to do a simple project to show a webcam feed on my browser to learn how to do webApps with Python, and this error keeps popping up. Tried using the code of someone else on this site to learn and see how to improve upon it, to no avail. I am running this on Visual Studio Code. from django.shortcuts import render from django.http.response import StreamingHttpResponse from django.views.decorators import gzip from cv2 import cv2 import threading # Create your views here. class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() cam = VideoCamera() def gen(camera): while True: frame = cam.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def index(request): try: return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame") except: # This is bad! replace it with proper handling pass -
Django Oscar customize Dashboard
I am building a a website with django-oscar package, and I am looking for a solution to my problem. I want that the client can modify the product properties (ProductProperty class) from the dashboard. I think I have to create a new tab for editing properties at the left sidebar when I click on Edit product. Unfortunately I did not find any documentation to that. enter image description here -
Django: how to pass color as context variable to templates
I need some help: I want my view to pass as context parameter a color to the template in order to overrule the default colors within the svg files displayed by the page. I have a list of color constants: COLORS = {"W": "#ffffff", "V": "#065636", "B": "#0253A5", "R": "#CC1011"} I have within my view definition the definition of context variables: view_context = { 'user_display_name': user.user_display, 'lightcolor': COLORS[user.lightcolor], } return render(request, 'pages/page5.html', context=view_context) and within my template (pages/page5.html), I have a <style> section where to define the CSS styles: <style> .X { /* fill: #065636 !IMPORTANT; */ fill: "{{ lightcolor }}" !IMPORTANT; } </style> .X {fill: #065636 !IMPORTANT;} works just fine while .X {fill: "{{ lightcolor }}" !IMPORTANT;} does not work and is ignored, I guess because lightcolor is a string "#065636" instead of a RGBcolor #065636 similarly .X {fill: {{ lightcolor }} !IMPORTANT;} does not even appear to be a recognized syntax and I cannot find anything relevant on internet How could I pass the color as context parameter into the <style> section of the template and get this working? -
Angular HttpClient infinite loading by set header bearer
I have this code to get data from API return this.httpClient.get<any>(requestUrl, { headers: new HttpHeaders({ "Content-Type": "application/json", "Authorization": "Bearer " + this.cookieService.get('auth-token'), }), }); when I subscribe to this like this return this.api.loadAll('cuser').subscribe( result => { console.log(result); }, ); It doesn't return any data to me and just loading but when I remove the headers and call it again it shows me the data. return this.httpClient.get<any>(requestUrl, { // headers: new HttpHeaders({ // "Content-Type": "application/json", // "Authorization": "Bearer " + this.cookieService.get('auth-token'), // }), }); But I need the Authorization and the token to get current user data from Django back-end. So what make my code wrong? Following is the Post man sample that return correct data without issue var myHeaders = new Headers(); myHeaders.append("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkyNTUxMTE3LCJqdGkiOiIxMGJlZWExMDQ0MmE0NmUyOGVmM2E5NTBjY2NiNTRmOSIsInVzZXJfaWQiOjF9.5XOhaXANSk4CGbh7pHqE99Qh_yxj6YuewZHFC1UScIs"); var requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' }; fetch("http://localhost:8000/api/cuser", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); -
unable to start uwsgi with encodings error in uwsgi 2.0.18 and python 3.6.9
I'm having serious trouble to start uwsgi in django project with nginx. I even tried to run plugins=python36 but still failed. I checked uWSGI Fails with No module named encoding Error but doesn't help me. I still have no idea how to fix the ModuleNotFoundError: No module named 'encodings'. Could you please advise and help me out? Thanks!! Here's the versions info: Python 3.6.9 uwsgi 2.0.18 nginx version: nginx/1.14.0 (Ubuntu) /usr/local/bin/uwsgi I got the following error when running sudo uwsgi --ini /usr/share/nginx/html/portal/portal_uwsgi.ini [uWSGI] getting INI configuration from /usr/share/nginx/html/portal/portal_uwsgi.ini open("./python3_plugin.so"): No such file or directory [core/utils.c line 3724] !!! UNABLE to load uWSGI plugin: ./python3_plugin.so: cannot open shared object file: No such file or directory !!! *** Starting uWSGI 2.0.18 (64bit) on [Thu Jun 18 22:51:54 2020] *** compiled with version: 7.5.0 on 11 June 2020 23:01:20 os: Linux-5.3.0-59-generic #53~18.04.1-Ubuntu SMP Thu Jun 4 14:58:26 UTC 2020 machine: x86_64 clock source: unix detected number of CPU cores: 4 detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** chdir() to /usr/share/nginx/html/portal your processes number … -
Same Apis Giving different output on different servers in django
enter image description here This is output in my Local System , which is using python 3.6.9 with Django rest framework 3.11.0 And another image is below enter image description here This is the same Django view which is running on remote Machine with same code base but with Python version 3.6.10 with the same Django Rest Framework version 3.11.0 . I am confused and I searched about what can be a glitch , I see the output coming on remote is a Dictionary in which there is a "result" key But in My local Environment its simply returning the list of data . I don't think python version could cause that trouble , If anyone can let me know what can go wrong . View is using Generic class and its List enter image description here This is the View which is same on both the machines. ` class DoctorListApiView(generics.ListAPIView): serializer_class = DoctorListSerializer def get_queryset(self): valid_user = False # get data in header (patient's phone number) patient_username = self.request.META['HTTP_X_USERNAME'] try: user_obj = UserProfile.objects.get(phone = patient_username) hospital_code = user_obj.hospital_code if hospital_code == None : pass else: partner_code = PartnerDatabase.objects.get(hospital_code = hospital_code).partner_code # print('Hospital Code : ' + str(hospital_code)) # print('Partner … -
Set Django JSONField value to a JSON null singleton with the Django ORM
Using a Django JSONField on PostgreSQL, say I have the following model class Foo(models.Model): bar = models.JSONField(null=False) and I want to set a row to have bar=null where null is a single JSON null value (different to a database NULL value). I can achieve it through a raw SQL query: UPDATE "myapp_foo" SET "bar" = 'null'::jsonb WHERE "myapp_foo"."id" = <relevant_id> The closest things I can do in the ORM is Foo.objects.filter(id=<relevant_id>).update(bar=None) but Django is interpreting this as a database NULL and I get the following error: null value in column "bar" violates not-null constraint or Foo.objects.filter(id=<relevant_id>).update(bar="null") but Django (correctly) interprets this as the JSON string "null" Am I missing something or is this a gap in the ORM functionality? -
Model foreign key field empty
I have two models Order and a date model. The order model has a foreign key attribute of date model. I have made a form in which I can update the date fields of order, but when I click submit it creates a new date object in date model not in the order date field. I want my form to save values in the date field in order. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) view.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.date = date_instance order.save() context = { 'order':order,'form':form } … -
ReportLab : How to retrieve data from database
I'm new to Django and also this ReportLab things. Right now I have to use ReportLab to generate PDF. But I don't know how to retrieve data from database and insert it into the PDF. Can you guys help me on the way to do this ? I know how to do it in the html template but how can I do it in PDF ? I'm really lost right now :( views.py def empIncomeform(request): if request.method == "GET": b1 = Income1.objects.filter(Q(title='Salary')| Q(title='Bonus')).annotate(as_float=Cast('total_amount', FloatField())).aggregate(Sum('as_float')) b2 = Income2.objects.filter(Q(title='Overtime')).annotate(as_float=Cast('total_amount', FloatField())).aggregate(Sum('as_float')) context= { 'b1':b1, 'b2':b2 } return render (request, 'EmpIncome.html', context) empIncome.py (PDF) def drawMyRuler(pdf): from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('Arial-Bold', 'arialbd.ttf')) pdf.setFont("Arial-Bold", 11) pdf.drawString(10,100, b1) #this is where I want to put my db data pdf.drawString(20,200, b2) #this is where I want to put my db data fileName = 'Emp_Income.pdf' documentTitle = 'Employee Income Form' from reportlab.pdfgen import canvas pdf = canvas.Canvas(fileName) pdf.setTitle(documentTitle) pdf.save() EmpIncome.html <table> <tr> <th>#</th> <th>Details</th> <th>Amount</th> </tr> <tr> <td>1</td> <td>Salary and Bonus</td> <td>{{ b1.as_float__sum}}</td> </tr> <tr> <td>2</td> <td>Overtime</td> <td>{{ b2.as_float__sum}}</td> </tr> <tr> <td colspan="2">Total Amount</td> <td>{{ total.as_float__sum}}</td> </tr> </table> -
I am getting a 404 error when running Django admin on Chrome but works on Microsoft Edge
My Django admin was working fine, when I added the Allauth then the admin is not working on chrome and internet explorer but works fine on Microsoft edge. What could be the problem. -
Model Inheritance in Django Forms
How can I access the Child Model Data in Django Forms? Forms.py class CourseForm(ModelForm): class Meta: model = Course fields = '__all__' class SectionForm(ModelForm): class Meta: model = Section fields = '__all__' Models.py class Section(models.Model): SEM = ( ('1st', '1st'), ('2nd', '2nd'), ('Summer','Summer'), ) section_code = models.CharField(max_length=22) academic_year = models.CharField(max_length=22) semester = models.CharField(max_length=22, choices=SEM) course_fk = models.ForeignKey( Course, models.CASCADE, db_column='course_fk') course_staff_fk = models.ForeignKey( Course, models.CASCADE, db_column='course_staff', related_name='course_staff') schedule_fk = models.ForeignKey( Schedule, models.CASCADE, db_column='schedule_fk') scheduleClassroom_fk = models.ForeignKey( Schedule, models.CASCADE, db_column='schedule_classroom_fk', related_name='classroom_schedule') def __str__(self): return self.section_code Views.py def add_sections(request): form = SectionForm() if request.method == 'POST': form = SectionForm(request.POST) if form.is_valid(): user = form.save() messages.success(request, 'Section Created') return redirect('add_section') context = {'form':form} return render(request, 'app/add_section.html', context) HTML <div class="input-group mb-3"> <div class="input-group-append"> <label for="course-staff">Course Instructor</label> </div> {{form.course_staff_fk.staff_fk}} ### This is what i hope to do {{form.course_staff}} ####This is whats working but doesnt give me the right data </div> I was hoping to get the child data through the django forms. I have tried using __ to access the child model but with the same result. Any help and advice is appreciate. Im hoping that this community can help me in my problem. Thank you -
What is the difference between some_list=[a,b] and some_list=[a]+b?
In django, seems urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), path('', RedirectView.as_view(url='/catalog/')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), path('', RedirectView.as_view(url='/catalog/')), static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ] are different. However, in my mindset it seems that some_list=[a,b] and some_list=[a]+b should be same object. Am I correct? -
Application error with Heroku after deployment of Django app
After having deployed my app with success I clicked on "Open app" and I see this error: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. My log details: 2020-06-19T05:42:21.334962+00:00 app[api]: Release v6 created by user harshalsinha437@gmail.com 2020-06-19T05:42:21.542382+00:00 heroku[web.1]: State changed from crashed to starting 2020-06-19T05:42:26.249249+00:00 heroku[web.1]: Starting process with command : gunicorn mywebsite.wsgi --log-file - 2020-06-19T05:42:28.310063+00:00 heroku[web.1]: Process exited with status 0 2020-06-19T05:42:28.349024+00:00 heroku[web.1]: State changed from starting to crashed 2020-06-19T05:42:28.357811+00:00 heroku[web.1]: State changed from crashed to starting 2020-06-19T05:42:33.000000+00:00 app[api]: Build succeeded 2020-06-19T05:42:33.690668+00:00 heroku[web.1]: Starting process with command : gunicorn mywebsite.wsgi --log-file - 2020-06-19T05:42:36.303973+00:00 heroku[web.1]: Process exited with status 0 2020-06-19T05:42:36.338696+00:00 heroku[web.1]: State changed from starting to crashed 2020-06-19T05:42:38.907020+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harshal-portfolio.herokuapp.com request_id=9bfded63-ac10-4a2a-b9af-491cb7a70c73 fwd="223.230.128.180" dyno= connect= service= status=503 bytes= protocol=https 2020-06-19T05:42:39.307963+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harshal-portfolio.herokuapp.com request_id=18e4fab6-017a-4423-b23d-c3919da0d937 fwd="223.230.128.180" dyno= connect= service= status=503 bytes= protocol=https 2020-06-19T05:43:53.725469+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=harshal-portfolio.herokuapp.com request_id=8c0aaff8-1a6f-48f2-9a8c-4c231f6a450f fwd="223.230.128.180" dyno= connect= service= status=503 bytes= protocol=https 2020-06-19T05:43:54.171265+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=harshal-portfolio.herokuapp.com request_id=8a7448aa-3453-4fbe-bc6e-95f0a0dd572f fwd="223.230.128.180" dyno= connect= service= status=503 bytes= protocol=https 2020-06-19T05:44:30.900385+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" … -
How to check the data in a form with javascripts
Here I have a form which has 2 inputs. 1st input asks if it's a video or image. 2nd input takes in the file. Now I want the JavaScript function demo() to run only if the 1st input is video. Any help regarding this matter will truly be helpful. Thanks in advance. This is my form :- <form method="post" enctype="multipart/form-data"> <input type="radio" id="type" name="type" value="image" required /> <label class="text-black" for="subject">Image</label><br> <input type="radio" id="type" name="type" value="video" required /> <label class="text-black" for="subject">Video</label><br> <label class="text-black" for="subject">Upload the File</label> <input type="file" id="upload" name="file" accept="image/*, video/*" onchange="demo()" required /> <input type="submit" value="POST" class="btn btn-primary"/> </form> This is the JavaScript function :- <script type="text/javascript"> function demo() { var upload = document.getElementById('upload'); var type = document.getElementById('type').value; if (type == 'video') { if (upload.files[0].size > 5000000) { if (window.confirm('File size above 5mb. Want to reduce it ?')) { window.location.href='https://www.google.com'; } else { window.location = '/' } } } } </script> -
Django: Filtering not returning any results?
Here I am trying to filter the two models logs with some parameters but it is not returning any results. Is my view looks fine or I need to change logic since it is not returning any results. def get(self, request): crud_logs = LogEntry.objects.none() user_logs = UserActivity.objects.none() parameter = request.GET.get('param') today = datetime.datetime.today() current_month = today.month past_7_days = today - datetime.timedelta(days=7) if parameter == 0: return redirect('logs:activity_logs') elif parameter == 1: user_logs = UserActivity.objects.filter(action_time=today) crud_logs = LogEntry.objects.filter(action_time=today) elif parameter == 2: crud_logs = LogEntry.objects.filter(action__time__range=[past_7_days, today]) user_logs = UserActivity.objects.filter(action_time__range=[past_7_days, today]) elif parameter == 3: user_logs = UserActivity.objects.filter(action_time__month=current_month) crud_logs = LogEntry.objects.filter(action_time__month=current_month) logs = sorted(chain(crud_logs, user_logs), key=attrgetter('action_time'), reverse=True) return render(request, 'logs/show_activity_logs.html', {'logs': logs}) template <form action="{% url 'logs:filter_logs' %}"> <select name="param" id="" onchange="this.form.submit()"> <option value="0">Any date</option> <option value="1">Today</option> <option value="2">Past 7 days</option> <option value="3">This Month</option> </select> </form>