Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there anyone who can help me abaut virtualenv?
I want install virtualenv. I type pip install virtualenv and the response is Requirement already satisfied: virtualenv in c:\users\novin\appdata\roaming\python\python38\site-packages (20.6.0) Requirement already satisfied: platformdirs<3,>=2 in c:\users\novin\appdata\roaming\python\python38\site-packages (from virtualenv) (2.2.0) Requirement already satisfied: distlib<1,>=0.3.1 in c:\users\novin\appdata\roaming\python\python38\site-packages (from virtualenv) (0.3.2) Requirement already satisfied: filelock<4,>=3.0.0 in c:\programdata\anaconda3\lib\site-packages (from virtualenv) (3.0.12) Requirement already satisfied: backports.entry-points-selectable>=1.0.4 in c:\users\novin\appdata\roaming\python\python38\site-packages (from virtualenv) (1.1.0) Requirement already satisfied: six<2,>=1.9.0 in c:\programdata\anaconda3\lib\site-packages (from virtualenv) (1.15.0) And when I want active it, type it "source bin/activate", and the response is "source : The term 'source' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + source bin/activate + ~~~~~~ + CategoryInfo : ObjectNotFound: (source:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException" -
How to show foreign key field value instead of id in Django admin?
class Country(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=100) class Info(models.Model) country_name = models.ForeignKey(Country, on_delete=models.CASCADE) country_code = models.ForeignKey(Country, on_delete=models.CASCADE) info = models.CharField(max_length=100) In admin interface, while adding object in 'Info' model, 'country_name' field show IDs of countries by default. But I want to show names of countries instead of IDs. And similarly, 'country_code' field of 'Info' model also show IDs of countries by default. But I want to show codes of countries instead of IDs. How to do this? -
how to fetch product size in cart session in django
i am using dictionary to fetch product item and show it into the cart the product has three values its id quantity & and its size but i don't understand hw to fetch size in cart here is my views.py class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.all() print(item) return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('size') cart = request.session.get('cart') if cart: cart[item] = 1 else: cart = {} cart[item] = +1 request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my html code in which the form is <form method="POST" action="#{{ item.id }}"> {% csrf_token %} <input type="text" hidden value="{{item.id}}" name="item"> <label class="size" for="size">Size:</label> <p class="input"><input type="radio" name="size" value="S"> <span>S</span> <input type="radio" name="size" value="M"> <span>M</span> <input type="radio" name="size" value="L"> <span>L</span> <input type="radio" name="size" value="XL"> <span>XL</span> <input type="radio" name="size" value="2XL"> <span>2XL</span></p> <button type="submit" class="cart btn btn-outline-primary">Add to cart</button> </form> any idea how i can fetch that in the session thank you for your time -
Hamburger getting outside of mobile width due to ckeditor form . What to do?
I am new to django. I am trying to build blog website. On laptop create new post is perfectly visible like below. On laptop create new post But when i view it with mobile view hamburger got extended outside the mobile width no hamburger visible at first view hamburger visible after dragging page towards right i figured out this is due to ckeditor form which i have used for writing 'Text' in form. I don't know what should i do as i tried to set margin but it is only affecting other form fields not the 'Text' one. Note:hamburger visible on other pages of website -
URL Serialization Performance Issue in Sorl-Thumbnail
I'm having a bit of a difficult time with performance using sorl-thumbnail. I'm hosting images on S3 with the S3Boto3Storage storage backend, I'm using Redis as my Key-Value Store and all queries have been cached inside it already. I'm using the following dependencies: boto3==1.17.103 botocore==1.20.105 Django==3.2.4 django-redis==4.10.0 django-storages==1.11.1 redis==3.3.11 sorl-thumbnail==12.7.0 Now I run & time the following script: from sorl.thumbnail import get_thumbnail images = Image.objects.all() # 7 images for image in images: x = image.file y = x.url # 1 x = get_thumbnail(x, '800x600', crop='center') # 2 x = x.url # 3 Step 1: When I comment out #2 & #3, the script takes 0.193s Step 2: When I comment out #1 & #3, the script takes 0.0153s Step 3: When I comment out #1, the script takes 0.669s (!) The odd thing is that when I debug the 3rd step, x seems to already have the attribute "url", so I don't know why it is taking so long to access it. The connection to Redis is working and the query towards it is already activated in the 2nd step. Like I said earlier, the thumbnails have already been generated, the lookups are cached in Redis, so it is (I … -
Connecting React to Django File content error
I have a react front-end that sends the contents of a file to my python django script the connection is working well, but i cant seem to return the contents back to react. The issue seems to be the below code any idea on how i can fix this to send back the content to react please Python Script: @api_view(["POST"]) def testfunc(data): return JsonResponse(data,safe=False) -
models don't register in django admin
I have 2 models which is Listing and Realtor class Listing(models.Model): #somethings class Realtor(models.Model): #somethings and in admin.py in listing package: from django.contrib import admin from .models import Listing admin.site.register(Listing) and admin.py in realtors package: from django.contrib import admin from .models import Listing admin.site.register(Realtor) and the setting of project is: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', ] but in admin panel there aren't registeredand there is no error while runing server -
how to store some extra information with one to ne relation with the user
I am trying to store some extra information about the user that has just logged in. Actually I have a different form that the looged in user need to fill up once the page is loaded. I want the extra information to be stored against the User that has logged in. I have assigned a one to one relationship but I am getting this error. Cannot assign "'username'": "PersonalDetail.user" must be a "User" instance models class PersonalDetail(models.Model): user= models.OneToOneField(User, null=True, on_delete=models.CASCADE) age= models.IntegerField( null=True) phone= models.CharField(max_length=10,null=True ) pan= models.CharField(max_length=10, null=True) enrollment_no= models.CharField(max_length=30, null=True) state= models.CharField(max_length=40 , null=True) views if request.method =='POST': user= request.POST.get("user") age= request.POST.get("age") phone= request.POST.get("phone") pan= request.POST.get("pan") enrollment_no= request.POST.get("enrollment_no") state = request.POST.get("state") details=PersonalDetail(user=user ,age=age, phone= phone, pan= pan, enrollment_no=enrollment_no, state=state ) details.save() return render(request, 'consult.html') I am beginner please correct my code since I am not able to store these information against the logged in userID or username. This form is recived the logged in user in side the page that he emters so this has to be stored in a different table. -
Execute external script on HTML button using Django
So I'm implementing a Django web page that contains different HTML buttons and each HTML button executes a different Python script. The button that executes external script would display this error : TypeError at /external/ expected str, bytes or os.PathLike object, not NoneType Here is the html code <form action="/external/" method="POST"> {% csrf_token %} {{data_external}}<br><br> {{data1}} <br><br> <input type="submit" value="Execute External Python Script"> </form> and here is views.py : def external(request): inp= request.POST.get('param') out= run([sys.executable,'/scripts/test.py',inp],shell=False,stdout=PIPE) print(out) return render(request,'web_app/home.html',{'data1':out.stdout}) How should I fix this ? -
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) …