Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limit the user to give the test only once
I want to limit the student to attempt specific test once. There can be multiple quizzes but each student should be giving test once only. The student field is one to one field with user @login_required(login_url='studentlogin') @user_passes_test(is_student) def calculate_marks_view(request): if request.COOKIES.get('course_id') is not None: course_id = request.COOKIES.get('course_id') course=QMODEL.Course.objects.get(id=course_id) total_marks=0 questions=QMODEL.Question.objects.all().filter(course=course) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks student = models.Student.objects.get(user_id=request.user.id) result = QMODEL.Result() result.marks=total_marks result.exam=course result.student=student result.save() return HttpResponseRedirect('view-result') The template for exam that I used is given as follows: <div class="container"> <div class="panel panel-primary"> <div class="panel-heading"> <h6 class="panel-title">Courses</h6> </div> <table class="table table-hover" id="dev-table"> <thead> <tr> <th>Exam Name</th> <th>Take Exam</th> </tr> </thead> {% for t in courses %} <tr> <td> {{t.course_name}}</td> <td><a class="btn btn-danger btn-xs" href="{% url 'take-exam' t.id %}"><span class="glyphicon glyphicon-circle-arrow-right"></span></a></td> </tr> {% endfor %} </table> </div> </div> I want to show the button only to new user <td><a class="btn btn-danger btn-xs" href="{% url 'take-exam' t.id %}"><span class="glyphicon glyphicon-circle-arrow-right"></span></a></td> -
unable to view address information and name on checkout page.. please do help me out in solving my error
<div class="col-sm-4 offset-sm-1"> <h4>Select Shipping Address</h4> <hr> <form action=""> {% for ad in add %} <div class="card"> <div class="card-body"> <h5>{{ad.name}}</h5> <p>{{ad.locality}}, {{ad.city}}, {{ad.state}}, {{ad.zipcode}}</p> </div> </div> <div class="form-check mt-2 mb-5"> <input class="form-check-input" type="radio" value=""> <label class="form-check-label fw-bold" for=""> Address: {{forloop.counter}} </label> </div> {% endfor %} <div class="text-end"> <button type="submit" class="btn btn-warning mt-3 px-5 fw-bold">Continue</button> </div> </form> </div> views.py ''' def checkout(request): user = request.user add = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) amount = 0.0 shipping_amount = 50.0 totalamount = 0.0 cart_product = [p for p in Cart.objects.all() if p.user==request.user] if cart_product: for p in cart_product: tempamount = (p.quantity*p.product.discounted_price) amount += tempamount totalamount = amount +shipping_amount return render(request, 'app/checkout.html', {'add':add , 'totalamount': totalamount,'cart_items': cart_items}) ''' views.py address ''' def address(request): add= Customer.objects.filter(user=request.user) return render(request, 'app/address.html', {'add':add,'active':'btn- primary'}) ''' -
SSE DJANGO REQUEST COUNT
i still new using SSE and i have a question about SSE in Django version 3.2.5, i am using StreamingHttpResponse to send SSE response to EventSource client and it does work fine, my question that why it takes to long to open the connection between backend and EventSource? why it sends only 145 responses/15 seconds ? i tried to open the code of StreamingHttpResponse but i didn't find anything related to the number of response here in the code def sse_movies(request): def event_stream(): while True: sleep(.2) yield f"data: {datetime.time(datetime.now())}\n\n" return StreamingHttpResponse(event_stream(), content_type='text/event-stream') i am using sleep to wait only 2/milliseconds for each iteration. but whenever send the EventSource it waits almost 15/secods to initiate the connection with the back-end, and after it sends 145 requests then waits 2 seconds then sends another 145 requests once more and after the second 145 is sent it waits another 15 seconds here is the code of EventSource client let url = '/test/' +'sse/movies/' let sse_client = new EventSource(url) let movies = document.querySelector('#data-movies') let movies_list = document.querySelector('#messages') sse_client.onopen = function(message_event) { console.log('opened') } console.log(sse_client) sse_client.onmessage = (message_event) => { console.log(message_event.data) console.log(sse_client.readyState) } NOTE: when i remove white: True EventSource doesn't wait and sends requests … -
django moderation and custom model managers
I am using Django 3.2 and django-moderation I want to moderate Foo: class MyCustomManager1(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=True) class MyCustomManager2(MyCustomManager1): def get_queryset(self): return super().get_queryset().filter(/* some criteria */) class Foo(models.Model): # some fields objects = models.Manager() published = MyCustomManager1() live = MyCustomManager() moderation.register(Foo) When I run python manage.py makemigrations, I get the error: Foo has no attribute unmoderated_published I tried to hack around this by adding the fields and creating Managers for moderated objects - but although that got rid of the errors, the object was no longer moderated. The only way I could get created objects to be moderated, was to remove all the model managers - with the exception of the default objects manager. How do I get django-moderation to work with models with custom model managers? -
How to programatically call a class based view from another class based view in drf. Tranform the request data before call
I'm trying to call an existing class based view for Model1 from another class based view of Model2. The data I'm receiving from the front end in JSON has the data for Model1 and Model 2 together in below format: request.data format: { "model1": { "key1": "val1" }, "model2": { "key2": "val2" } } In my Model1View, I'm doing some additional things which I want to do whenever I have to save some new data to Model1. So I intend on using the same view. So when I call Model2View, I want to seperate the request data for Model1 and call Model1View first. Once I successfully get a response from this view, I want to use the model1_id (primary key of Model1), to add to the request data and save Model2. While testing with this view, I'm getting an error: django.http.request.RawPostDataException: You cannot access body after reading from request's data stream Models: from django.db import models class Model1(models.Model): model1_id = models.AutoField(primary_key=True) key1 = models.CharField(max_length=20, blank=False, null=False) class Model2(models.Model): model2_id = models.AutoField(primary_key=True) key2 = models.CharField(max_length=20, blank=False, null=False) model1_id = models.ForeignKey('Model1', blank=False, null=False, on_delete=models.PROTECT) Serializers: from rest_framework import serializers from .models import * class Model1Serializer(serializers.ModelSerializer): class Meta: model = Model1 fields = … -
Django Rest Framework get_permissions require one permission or other
I have defined get_permissions method on ListCreateAPIView and applied custom permissions there but I have one problem. class ListSchoolStudents(generics.ListCreateAPIView, TeacherPermission): serializer_class = StudentSerializerForList permission_classes = [IsAuthenticated & TeacherPermission] def get_queryset(self): pk = self.kwargs['pk'] return Student.objects.filter(school__id = pk).select_related('school','school_class').prefetch_related('subject') def get_permissions(self): if self.request.method in ['POST']: return [PrincipalPermission()] return [permissions.IsAuthenticated(), TeacherPermission()] When I defined it like this Principal can only use POST method. But I also want that user to be able to use other methods. I have tried something like this : def get_permissions(self): if self.request.method in ['POST']: return [PrincipalPermission()] return [permissions.IsAuthenticated(), TeacherPermission(), PrincipalPermission() ] But as I understand it requires all permission in list to be satisfied. I am looking for something like this return [permissions.IsAuthenticated(), TeacherPermission() or PrincipalPermission() ] I know that this possibility exists in permission_classes by writing permission_classes = [IsAuthenticated | TeacherPermission] Is there a simple way to do this or I am forced to write another custom permission that is granting permission if user is Teacher or Principal? -
Static path file directory written wrong
The problem I am facing here is that this static directory path I have write is wrong but I am not sure on how I should tweak it. I will provide a picture of the directory. My static code: {% static 'members/static/css/'.css' %} {% static 'members/static/js/'.js' %} and more what needs to be tweaked: {% static 'members/static/' %} -
django.db.utils.OperationalError: no such column: (no solution yet)
The problem is I just made some changes and inserted a new column total_price field, but its not reflecting (i mean to say after migrations its still showing the error below_ i have checked many solutions none of them seems to work Stuck on this for 2 hours: thanks in advance no such column: orders_cartitem.total_price <-- error return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: orders_cartitem.total_price class CartItem(models.Model): menu_item = models.ForeignKey(MenuItem, null=True, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(null=True) total_price = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) def __str__(self): return "This entry contains {} {}(s).".format(self.quantity, self.menu_item) -
The view accounts.views.login didn't return an HttpResponse object. It returned None instead
views.py i am trying to create a login page if username and password is correct it should redirect to home page otherwise it should print invalid credentials but i am not able to visit the login page it is giving error - The view accounts.views.login didn't return an HttpResponse object. It returned None instead. from django.core.checks import messages from django.shortcuts import redirect, render from django.contrib.auth.models import User from django.contrib.auth import authenticate,login from django.contrib import messages def login(request): if request.method=='POST': username=request.POST['username'] password=request.post['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request,'invalid credentials') return redirect('login') login.html login.html code- <form action="login" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Username"><br> <input type="password" name="password" placeholder="password"><br> <input type="submit"> </form> <div> {% for message in messages %} <h1>{{message}}</h1> {% endfor %} </div> urls.py url- from django.urls import path from .import views urlpatterns=[ path("login",views.login,name='login') ] -
Static path not working even though it has been written right [closed]
After I added a lots of thing to my blog I wanted to add a template to my sign up template. But When I did that I was caught in an error. which was really hard to fix. But I figured it out as it was a directory fault meaning that I have written the directory wrong for my static code. I know that this is the problem as I am sure static works as I have used it before. I will provide an image on how my directory to static looks. The question I am trying to convey is this code is not working event though it should My static code: {% static 'members/static/css/style.css' %} -
JavaScript Option Selection and Quantity Sum Issues
I am a student who is learning Janggo. While practicing the shopping mall example, I asked the question because it was difficult to print the selected option and calculate the corresponding quantity and total price. In the meantime, I found the code I got from the code pen, and I want to write my code in this code. I tried to put it in myself, but I'm experiencing a lot of errors and problems. I would really appreciate it if you could help me put my code in this code. Among my codes, the option is the option name, the option value is the option value, and the value.extra_cost is the price that corresponds to the option value. Experts, I would be very, very grateful if you could help me solve the problems I face. It's my code. <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="mcd" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="mcd" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} … -
Nginx doesn't work try_files in Django app with Vue js
I use history mode in Vue js app on production mode with Django app. So, I have to response all get request by using try_files command on nginx. But it doesn't work. My site config: server { listen 80; server_name www.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/usr/projects/example; } location / { include proxy_params; proxy_pass http://unix:/home/usr/projects/example/example.sock } location / { roor /home/usr/projects/example; try_files $uri $uri/templates/index.html $uri.html=404 } } Please, help me to find out the error in my code, thanks in advance. -
Djongo fails to query BooleanField
I have Django application with a module like this: class myApp(models.Model): is_new = models.BooleanField(default=True) more_fields = models.TextField(blank=True) And using Djongo for database (which is mongodb) I can query all fields in the module with no issues, however, when filtering for a boolean field like the following: myList = myApp.objects.filter(is_new=False) for record in myList: .... It fails with the following error: File "/home/user/myApp/venv/lib64/python3.9/site-packages/djongo/sql2mongo/operators.py", line 258, in evaluate self.rhs.negate() AttributeError: 'NoneType' object has no attribute 'negate' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/myApp/venv/lib64/python3.9/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/user/myApp/venv/lib64/python3.9/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/home/user/myApp/venv/lib64/python3.9/site-packages/djongo/sql2mongo/query.py", line 885, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: SELECT "mysite_myapp"."more_fields", "mysite_myapp"."is_new" FROM "mysite_myapp" WHERE NOT "mysite_myapp"."is_new" Params: () Version: 1.3.6 It seems like a Djongo issue unless boolean fields are queried differently Versions is use: Django 3.2.5 djongo 1.3.6 -
How do I use Signals i Django to Calculate Age based on Date entered, if entered at all?
We do not use Date of Birth as a mandatory field during signup. But, in the Model we have an auto-calculate function to arrive at the 'Age' of the user. So while this works fine when using Django built-in registration mechanism, it fails with custom. How can Signals be leveraged to check - if DoB was entered? if DoB entered, then calculate Age and Populate Age Field? Thanks in Advance for shring your knowledge. Regds. -
I am getting two slashes at the end of my url when I put in the base url, what could cause this?
My url is adding two slashes at the end when you search the base url. For example if I went to example.com it would go to https://www.example.com// However, if I go to https://www.example.com/ it stays on https://www.example.com/ I have been trying to track down where this issue is coming from. It is not clear to me which part of my build is even capable of such a thing. I am using heroku, React, Django and Google Domains and I have been looking frantically through all four for something amiss but I need some assistance in determining which of these could cause this issue and if possible some thoughts on what could cause this -
how to change the value of second input field based on click event of first input field
I have plus minus button in the first input field. If i click on 'plus' the value decreases in the second input field. And If i click on minus button the value increases in the second input field. This works fine for the first row "Sold" and "Left"(Please see the image). But when i click plus or minus button of second row. It does not change the value in the second row of "left" input field. This image is showing data from database which have 8 columns(id is hidden) this is my itemlist.html page <td> <div class="letsdoit"> <form action="{% url 'update_item' neww.id %}"> <button class="minus-btn" type="button" onclick="slleft()" name="button">-</button> <input type="text" size="1" value="{{neww.sold}}" id="soldd" name="soldd" class="soldd"> <button class="plus-btn" id="add" type="button" name="button">+</button> <input type="submit" class="bbttnn" value="Update"> </form> </div> <td><input type="text" size="1" class="leftt" id="leftt" name="leftt" value="{{neww.left}}"></td> And this is my script: <script> const quantities = document.querySelectorAll('.letsdoit'); [...quantities].forEach(function (letsdoit) { const minusButton = letsdoit.querySelector('.minus-btn'); const plusButton = letsdoit.querySelector('.plus-btn'); const inputField = letsdoit.querySelector('.soldd'); minusButton.addEventListener('click', function minusProduct() { document.querySelector(".leftt").value++; const currentValue = Number(inputField.value); if (currentValue > 0) { inputField.value = currentValue - 1; } else inputField.value = 0 }); plusButton.addEventListener('click', function plusProduct() { var t = document.querySelector(".qty").value; var s = document.querySelector(".soldd").value; document.querySelector(".leftt").value = Number((t - s) … -
Is there any defined way in django to refresh the ML model that I loaded in apps.py at the startup?
I have a REST API deployed using gunicorn, serving a ML model. Model size is 1 GB. I am loading my ML model at startup in apps.py. Whenever a request is made to the server, model is giving the response quickly. Now there is a model training happening in background using apscheduler that updates the ML model in every 3 hours. I want to refresh this updated model in the variable holding the previous model in apps.py without switching off my wsgi server. There is a defined methods to load the model at startup ex. loading model in apps.py Is there any way that somehow I can refresh the model also? -
CSRF Error When Communicating Between Two Servers
I have two Django-based servers where I want one to send a file.py to the other one via RESTful API. I do receive the POST request on the second server but I get a message like: Forbidden (no CSRF) POST http:\127.0.0.1 etc. server1 runs on http:\127.0.0.1:8000 and server2 runs on http:\127.0.0.1:8001. My intermediate goal is for server1 to send a POST request containing the file in binary to server2, whenever I go to the web address http:\127.0.0.1\8001\download, and I want server2 to save the file in a folder. The urls work fine so I do not include the code here. Here is the relevant code of server1: def execute_view(request, *args, **kwargs): files = {'file': open('testFile.py', 'rb')} req = HttpResponse.POST("http://127.0.0.1:8001/fileDownload/", files=files) and the relevant code of server2: def execution_view(request, *args,**kwargs): file = request.files['file'] with open('transferred.py','wb') as f: for chunk in file.iter_content(chunk_size=1892): if chunk: f.write(chunk) I saw I need to add, for example, @csrf_exempt over one of the functions but I do not even know on which. Either one does not work, even when I import the module. -
How do you remove the "XMLHttpRequest error" in Flutter? (Django backend, Flutter frontend)
I'm having trouble connecting my Django backend to my Flutter frontend on web.I have not tested on Android or iOS yet. I want to be able to do an API call and have it return a response that I can convert to a json. However it's been throwing errors no matter what I've tried. I've tried converting it into an https request with no avail. If anyone needs anything on the Django side please let me know This is what the error looks like: Error: XMLHttpRequest error. dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 909:28 get current packages/http/src/browser_client.dart 71:22 <fn> dart-sdk/lib/async/zone.dart 1613:54 runUnary dart-sdk/lib/async/future_impl.dart 155:18 handleValue dart-sdk/lib/async/future_impl.dart 707:44 handleValueCallback dart-sdk/lib/async/future_impl.dart 736:13 _propagateToListeners dart-sdk/lib/async/future_impl.dart 533:7 [_complete] dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue dart-sdk/lib/async/stream.dart 1219:7 dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall dart-sdk/lib/html/dart2js/html_dart2js.dart 37307:58 at Object.createErrorWithStack (http://localhost:63593/dart_sdk.js:5362:12) at Object._rethrow (http://localhost:63593/dart_sdk.js:39509:16) at async._AsyncCallbackEntry.new.callback (http://localhost:63593/dart_sdk.js:39503:13) at Object._microtaskLoop (http://localhost:63593/dart_sdk.js:39335:13) at _startMicrotaskLoop (http://localhost:63593/dart_sdk.js:39341:13) at http://localhost:63593/dart_sdk.js:34848:9 And this is a code snippet import 'package:http/http.dart' as http; var url2 = 'https://0.0.0.0:8809/test/'; try{ response = await http.get(Uri.parse(url2)); print(response.body); } catch(exception){ print('could not access'); response = await http.get(Uri.parse(url2)); } }, I had it print out the error. -
How to get rid of .pyc
I've been creating a Django app and I have a question about .pyc. I don't know exactly when, but I believe when I created a branch and moved into the branch, I always had a problem about .pyc. Three .pyc files always emerge to branch areas on VSCode. I want to even delete the three files, but I don't think it's the best way to solve this. Or maybe I can't delete them for another reason. -
how to count number of females and males per day (group by) in django
i'm trying to group by for dates and count number of field(choice field : male and female) this is what i tried genders = ( (male , _('male')), (female , _('female')), ) class MyModel(models.Model): gender = models.CharField(max_length=10,choices=genders,default=male) created_at = models.DateTimeField(auto_now_add=True) #others my views.py male= Q(gender='male') female= Q(gender='female') lists = MyModel.objects.annotate(day=TruncDay('created_at')).values('day').annotate(qnt=Count('id'),male=Count(male),female=Count(female) ).order_by('-day') i expect to return something like this : day : 1-8-2021 , qnt: 15 , male : 8 , female : 7 but it return total quantity qnt for both male and female ! is there a better approach to achieve that please ? -
Make order by function inside model class in Django
models: class Product(models.Model): product_model = models.CharField(max_length=255) price = models.DecimalField(default=0 , decimal_places=0 , max_digits=8) def product_all_price(self): if self.price > 0: ... return price else: .... return "0" my views: def products_list(request): products_list = Product.objects.filter(product_draft=False) products_list = products_list.order_by('-created_on') ... How can i order this list by product_all_price in models. show returned "price", above and all returned "0", below -
Heroku Node Js app will load (ex. https://appname-98115.herokuapp.com/) but the dns record is not
I have previously had this system running properly through google domains. I made some changes in Google domains and now my website and the DNS url itself will not work. I know the app is still running properly because the app will work in heroku (ex. https://appname-98115.herokuapp.com/) but the dns record will return site can not be reached (ex. http://www.fluffy-barracuda-vczoblygcndwilc4jl86qdra.herokudns.com/) Does this url loading rely on the google domain to be setup properly? Is this a sign that google domains is off? Or should the link work before it's setup in Google Domains and that's why the google domain is not currently working? At the moment it's hard for me to know where to start Thanks ! -
How can i check the model object is 30 days old or not in Django?
Info: I am trying to make monthly billing app. Where a customer can buy a property on a monthly basis payment. i want to change the pending attribute True to False if the customer last payment 30 days old. It is a schedule based app but i am not using django-crontab or celrey. i can use view funtion for it if user visit the pending_customers page the view can check the all and which customers the last payments date created_at if the created_at datetime is 30 days old. Then the view funtion can change the pending to False. pending_customers view is working fine but it is changed the pending to False when i visit the page pending_customers. It could not wait for 30 days. if the customer last payment is not 30 days old then how can i hold the view funtion until for 30 days? models.py class Customer(models.Model): """Customer Model""" name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) created_on = models.DateTimeField(auto_now_add=True) pending = models.BooleanField(default=False) class Payment(models.Model): """Payment Model""" customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='payment') created_at = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(max_digits=17, decimal_places=2, default=0.0) def save(self, *args, **kwargs): super(Payment, self).save(*args, **kwargs) self.customer.pending_customer = True self.customer.save() views.py def pending_customers(request): queryset = Customer.objects.all() … -
How to organize data in AWS S3 bucket during a web data migration?
I currently built a blog using Django. It involves creating a post where images are also uploaded to an AWS S3 bucket. However, I would like to rebuild the whole website in Node.js/the MERN stack in the near future. As I upload more photos to the S3 buckets, and build the website in Node.js- how should I keep track of organizing the data that I currently have in Django so that when I have the MERN stack website ready, I can seamlessly move both the post and photo info there?