Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate a random number in django?
I want to generate a random number to be added to a counter. But I am receiving an error and cant figure out why. Appreciate your help. from django.shortcuts import render, redirect, HttpResponse from random import random, randint # Create your views here. def index(request): if 'counter' not in request.session: request.session['counter'] = 0 return render(request, 'index.html') def process_money(request): print(request.POST['custId']) if request.method == 'POST': if request.session['custId'] == '1': request.session['counter'] += random.random() # Add a random number to the counter if request.session['custId'] == '2': request.session['counter'] += 10 request.session['custId'] = request.POST['custId'] return render(request, 'index.html') This is the error I get in the console: AttributeError: 'builtin_function_or_method' object has no attribute 'random' -
The view account.views.updatedata didn't return an HttpResponse object. It returned None instead
I have an issue with my update button and it show this error to me when I click the update button, it is suppose to redirect me to the next page where the staff can update the details, how do I fix that error, so that it can redirect me to the next page where it will show the forms for the staff to update the details The error I had is shown below here (Traceback error): Environment: Request Method: POST Request URL: http://127.0.0.1:8000/updatedata/17/ Django Version: 3.1.4 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms', 'channels'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', '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\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response self.check_response(response, callback) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 307, in check_response raise ValueError( Exception Type: ValueError at /updatedata/17/ Exception Value: The view account.views.updatedata didn't return an HttpResponse object. It returned None instead. views.py @login_required() def updatedata(request, id): photo = get_object_or_404(Photo, id=id) if request.method == 'POST': # check for the post request body form = UpdateForm(request.POST) if form.is_valid(): form.save() return redirect('/logdata') else: msg = 'form is not valid' # Show an error message … -
Django + Node.js + CentOS7 + Apache: What do I need to edit in httpd.conf to move to production?
Distinguished technical humans: I currently have a website that I built using Django as the backend, Node.js for the front end running on Apache and CentOS7 (linux). My dev server works fine today with my front end (node.js) being served to (myIP:3000) and my backend (django) being served to (myIP:8000). I am ready to move to production but am having trouble figuring out the correct configruations for the httpd.conf file. I pointed my DocumentRoot to the directory where my npm build is located and reset my apache server. This serves my homepage just fine to my IP. When I click the links to the rest of my site, however, I get 404 becuase my urls aren't being read in. Would appreciate any guidance here. Do I need to modify the django.conf files also? -
FPX element in the new Stripe PaymentElement is not configuring in the frontend
Has anyone tried to use the new PaymentElement in Stripe? According to the documentation, the payment_method_types need to be configured in the server side and the client side will automatically configure it after retrieving the client_secret . I've followed all the steps in the documentation and all other payment methods I've selected are working but the client side will not configure FPX Here's a screenshot of the output. As you can see, it's configuring card payment, grabpay and alipay but it isn't configuring fpx payment: Screenshot of Output Reference to Stripe Documentation that I'm following: https://stripe.com/docs/payments/accept-a-payment?platform=web&ui=elements Backend view -Django # stripe payment key stripe.api_key = 'sk_test_<<SECRET_KEY>>' @api_view(['POST']) def test_payment(request): data = request.data amount = int(float(data['amount']) * 100) intent = stripe.PaymentIntent.create( amount=amount, currency='myr', payment_method_types=['card', 'fpx', 'grabpay', 'alipay', ], ) return Response(status=status.HTTP_200_OK, data=intent) placeorder.js import React, {useState, useEffect} from 'react' import axios from 'axios' //UI components import Message from '../components/Message' import Loader from '../components/Loader' //---------- STRIPE PAYMENT COMPONENTS -------------// import {Elements} from '@stripe/react-stripe-js' import {loadStripe} from "@stripe/stripe-js/pure" import CheckoutForm from "../components/CheckoutForm" //dev-based publishable key const stripePromise = loadStripe('pk_test_<<PUBLISHABLE_KEY'); const PlaceOrder = () => { /* . . bunch of other code . . -----*/ const [amount, setAmount] = useState(0) let [clientSecret, setClientSecret] … -
Obtain in the same query the number of active and inactive users in django
I have two models class User(AbstractUser): ... class Agent(models.Model): ... user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="agent") I want to have the number of active and inactive users in a single request. My request: Agent.objects.annotate( actifs=Count(User.objects.values("id").filter("is_active")), inactifs=Count(User.objects.values("id").filter("is_active=False")), ) It does not work. How i can do it ? -
os.walk returns one empty list and then my actual list
I'm working on getting some subdirectories to output while ignoring another. I noticed in the output despite everything else seemingly working correctly, that I have an empty list also being returned. /usr/lib/python3.9/os.py(407)_walk()->('/home/presto.../pB/media/370', ['images5', 'images'], []) 'images' is removed later on in the code but that final empty list remains. /usr/lib/python3.9/os.py(407)_walk()->('/home/presto.../pB/media/370', ['images5'], []) for root, subdirectories, files, in os.walk(wk): for subgals in subdirectories: if subgals == primary_gallery: subdirectories.remove(subgals) else: subgal_path.append(os.path.join(root, subgals)) for file in sorted(files): raw_subgal_file_paths.append(os.path.join(root, file)) for x in raw_subgal_file_paths: split_root = raw_prim_path_length - len(x) compiled_subgal_file_paths.append(x[split_root:]) print(compiled_subgal_file_paths) The final output looks like this. [] ['/images5/10.gif', '/images5/11.gif', '/images5/20.gif', '/images5/21.gif'] How do I fix this? -
How to connect one model twice with another model?
I have two models in my project. It will be a small and simple applications for sending tickets to the support. First model is for autors of posts/tickets class Autor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) service_group = models.BooleanField(default=False) active = models.BooleanField(default=True) def __str__(self): return self.user.username second is for tickets. It will be only paty of it but you will see what I mean... class Ticket(models.Model): added_date = models.DateField('added date') added_time = models.TimeField('added time') topic = models.CharField(max_length=400, unique=False) description = models.TextField() post_author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='post_author') status = models.ForeignKey(Status, on_delete=models.CASCADE, default=1) open_date = models.DateField('open date', default='1900-01-01') open_time = models.TimeField('open time', default='00:00') service = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='service') close_date = models.DateField('close date', default='1900-01-01') close_time = models.TimeField('close time', default='00:00') def __str__(self): return self.topic However, this is how the connection of the model Author does not work. Cannot assign "1": "Ticket.service" must be a "Author" instance. Please help me connect it correctly to make it work. -
Which framework is the best for a specification sheet and technical specification sheet programm?
I'm a German student who is very new to python. Please excuse my bad English. For a university assignment I have to code a program which consists out of a login screen and two masks. The first screen, the login screen, intends to have two input fields: email and password. The second screen, the specification sheet (Lastenheft) will have numerous input fields. The third screen, the technical specifications (Pflichtenheft) will have numerous input fields (including some from the second screen). All data which a user can input needs to be saved in a database. Since I'm not that experienced in Python, I would like to request some help choosing one or more frameworks. Which one would you recommend for this purpose? I'm really interested in web2py, but I'm unsure if it will cover all requirements. -
Images not appearing in Django template For Loop
See Problem Here I want to loop over a directory of static images in Django. The images are being looped over correctly, but something is wrong with my <img src /> syntax. I've tried many variations on {{ flag }} but can't get anything to work. Can anybody advise? In settings.py I created the following STATIC_ROOT object: STATIC_ROOT = '/Users/TheUnforecastedStorm/Desktop/Code_projects/Portfolio_Site/portfolio_site/entrance/static' In views.py I joined this file path to my image directory and placed the list of images in the context dictionary. I then included this dictionary in my response: import os from django.conf import settings from django.shortcuts import render # Create your views here. def index(request): # Create a dictionary context = {} # Join images directory to index.html view flags = os.listdir(os.path.join(settings.STATIC_ROOT, "entrance/images/")) context['flags'] = flags # Return response return render(request, "entrance/index.html", context) I then looped over these images in my template: <!DOCTYPE html> {% load static %} <html> <head> <link rel="stylesheet" href="{% static 'entrance/entrance.css' %}"> <script src="{% static 'entrance/entrance.js' %}" type="text/javascript"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> {% for flag in flags %} <img src="{{ flag }}" alt="problem" /> {% endfor %} </body> </html> -
Can I serve static files from django and media files off S3
I'm trying to see if I can serve admin static files off S3. I'm trying to run a Wagtail fork (coderedCMS), and have been having a heck of a time getting the fontawesome icons to work. I've tried a few different things, but it's not worth the headache or time anymore. I wanted to see if it was possible to use AWS:S3, storages, and boto3 to set up my server to have nginx serve admin/static files, and media to be served from S3. I'm not sure what I would have to do as far as making this happen. I can set evertying up to serve all from S3 or all from my server itself, but not a mix. Can anyone point me in the right direction to make this happen? -
How to create dynamic pages in Django?
I want to create dynamic pages in Django like in WordPress but I am running out of clue. I have created django blog where data will be updated from admin site and dynamic blog pages will be generated based on postlist, postdetail, and sidebar widget. Now, I want to create page where from single view multiple page can be created. For example, About Us page, About Services Page, Contact page, Some Static Page (like privacy policy..) Where admin will be able to update the content from admin side and decide which content to display on which part of that page. Like ( Image, Video, texts, slides, etc, but that will be independent of template configuration) Like WordPress page customization. -
Error installing Django package django-tenants
When attempting to install django-tenants via "pipenv install django-tenants" I get the following error: _lib.ERR_load_RAND_strings() AttributeError: module 'lib' has no attribute 'ERR_load_RAND_strings' This is with Django version 3.1.13 and python is 3.9.2. Any ideas about how to fix this? -
How to use different .env files with python-decouple
I am working on a django project that I need to run it with Docker. In this project I have multiples .env files: .env.dev, .env.prod, .env.staging. Is there a right way to manage all this file with the package python-decouple? I've search for a workaround to deal with this challenge and do not find any kind of answer, not even on the official documentation. Can I use something like: # dont works that way, it's just a dummie example python manage.py runserver --env-file=.env.prod or maybe any way to setting or override the file I need to use? -
Django: Should i store data from API in the database or make requests for every new page of data
I just started using Django for a school project and want to make movie reletaed website using the DMTB API (The api is paginated).. I want to load large list of movies in a catalogue and my question is should i store data from the API in my database for easy acces or should i request from the api for every new page of the catalogue -
Django Many-to-Many relation, don't know how to use it (get and post request)
I'm trying to use my model with M2M relationship and trying to get all the values from a GET request. Also, I'm using an API called random quotes, which can be found here: https://rapidapi.com/martin.svoboda/api/quotes15/ Here is my models.py: from django.db import models class Tag(models.Model): tag = models.CharField(max_length=50) def __str__(self): return str(self.id)+". "+str(self.tag) class Quote(models.Model): frase = models.TextField() autor = models.CharField(max_length=150) tags = models.ManyToManyField(Tag) def __str__(self): return str(self.id)+". "+str(self.autor) And here is my views.py where i use API GET and POST functions: from django.shortcuts import render, redirect import requests from .models import Quote from .models import Tag from rest_framework.decorators import api_view from rest_framework.response import Response from django.http import Http404 from .serializers import QuoteSerializer, TagSerializer @api_view(['GET', 'POST']) def api_quotes(request): if request.method == 'POST': new_quote_data = request.data quote = Quote() quote.id = new_quote_data['id'] quote.frase = new_quote_data['frase'] quote.autor = new_quote_data['autor'] quote.tag = new_quote_data['tags'] quote.save() url = "https://quotes15.p.rapidapi.com/quotes/random/" querystring = {"language_code":"pt"} headers = { 'x-rapidapi-host': "quotes15.p.rapidapi.com", 'x-rapidapi-key': "4a3bce6d8cmsh044349ed231bf95p15f17ajsn846aa4e94d98" } r = requests.get(url , querystring, headers=headers) quote_json = r.json() print(quote_json) id = quote_json['id'] print(id) frase = quote_json['content'] autor = quote_json['originator']['name'] tags = quote_json['tags'] #LISTA de tags, os números não aparecem print(tags) new_quote = Quote() new_tag = Tag() new_quote.id = id new_quote.frase = frase new_quote.autor = autor … -
Can't extend correctly my base html file?
I am using Django python with a base.html that I want to extend on my login.html but it doesn't work right. My navbar is supposed to be at the top but it displays wrong as you can see on that picture I tried many different things but it didn't work. The bar should be at the top not the bottom base.html {% load static %} <link rel="stylesheet" href="{% static 'nav.css' %}"> {% block content %}{% endblock content %} <header> <div class="navbar"> <ul> <li><a href="default.asp">Home</a></li> <li><a href="news.asp">About</a></li> <li><a href="contact.asp">Services</a></li> <li><a href="about.asp">Contact</a></li> </ul> </div> </header> login.html {% extends "main/base.html" %} {% block content %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> <header> </header> <div class="wrapper"> <div class="title"> Login Form </div> <form action="#"> <div class="field"> <input type="text" required> <label>Email Address</label> </div> <div class="field"> <input type="password" required> <label>Password</label> </div> <div class="content"> <div class="checkbox"> <input type="checkbox" id="remember-me"> <label for="remember-me">Remember me</label> </div> <div class="pass-link"> <a href="#">Forgot password?</a> </div> </div> <div class="field"> <input type="submit" value="Login"> </div> <div class="signup-link"> Not a member? <a href="#">Signup now</a> </div> </form> </div> </body> </html> {% endblock %} -
docker doesn't reflect code change in docker container
I have a Django application that runs in the Docker container locally on Mac machine. This docker container is managed via docker-compose. Django application is configured to reload if its code changes. However, and this is a problem, when I change application code, Django default server reloads service, but changes are not reflected in the container. API response doesn't change. Here is my docker configuration: Dockerfile FROM python:2-slim RUN apt-get update && apt-get install -y build-essential COPY requirements /requirements RUN pip install -r /requirements/build.txt # copy app source into image COPY service_api /opt/service_api COPY manage.py /opt docker-compose.yml version: '3.7' services: service-django: image: service-django build: dockerfile: Dockerfile context: . ports: - 8000:8000 volumes: - ./service_api/:/opt/service_api/service_api # this path is correct! container_name: service-django hostname: service-django restart: always Docker desktop: 3.5.0 Docker Engine: 20.10.7 Compose: 1.29.2 Big Sur: 11.4 Any help will be appreciated! -
Django: class from models.py won't import
I have a django project where I have two models and added a third in this structure in the same file: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Product(models.Model): title = models.CharField(max_length=120) class Category(MPTTModel): name = models.CharField(max_length=200) class Range(models.Model): test = models.CharField(max_length=200) For brevity I've only shown the 1st line but Product and Category work perfectly. I then added Range, went to the console and python manage.py makemigrations, then python manage.py migrate, no errors and I can see it in the migrations file. Would somebody please put me out of my mystery and explain why in the shell: from products.models import Product, Category, Range throws cannot import name 'Test' from 'products.models' Product and Category import fine, but not Range?? Am I being dim here? -
Django - getting init parameters into a clean method in a form
I have a model with a unique together and I want to validate this condition in my modelform. The unique together includes a field that is passed to the form in an init method, the user, and a field that is in the form. I'm having problems with getting the first two into the clean method for validation. My first attempts at this failed, and I found this post but I could not get it to work for my situation: How to get requested user in clean function in django forms? model: class Objective(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) objective_name = models.CharField(max_length=10) description = models.CharField(max_length=300) mode = models.CharField(max_length=2, default='LA') class Meta: unique_together = ['user', 'objective_name', 'course'] ordering = ['objective_name'] def __str__(self): return self.objective_name The view: def addobjective(request, course_id): this_course = get_object_or_404(Course, pk=course_id) user = request.user all_courses = Course.objects.filter(user=user) objective_list = Objective.objects.filter( course=this_course).order_by('objective_name') context = {'objective_list': objective_list} if request.method == 'POST': form = ObjectiveForm(request.POST, my_course=this_course) if form.is_valid(): obj = form.save(commit=False) obj.course = this_course obj.user = user obj.save() form = ObjectiveForm(my_course=this_course) context['form'] = form return redirect('gradebook:addobjective', course_id=this_course.id) else: form = ObjectiveForm(my_course=this_course) context['form'] = form context['this_course'] = this_course context['all_courses'] = all_courses return render(request, 'gradebook/objective-form.html', context) … -
Truncated or oversized response headers received from daemon process - throwing error for large files - django
Concept is like this: User will upload two files, program will compare the two excel files for matches. It will match based on amount column. I am using pandas and numpy to achieve this File1: File2: Program will create intermediate matched dataframe, it will contain indices of both dataframe, the matched dataframe will look like below: Then I am merging df1 and df2 with the help of above matched dataframe, after merge, it will look like below: Problem statement: I am using AWS t2.micro, when I use smaller files, everything works fine, program will create the merged dataframe without any error, but when I use files with 40000 entries each, pandas can able to create matched dataframe, but it is not creating merged dataframe. ie) it can able to perform the first step, after the first step, it is throwing me this Truncated error. I am thinking, whether this error is coming, because RAM memory is not enough. Reason for this conclusion is that, 40000 entries will create around 5lakhs entries in matched dataframe, whether this 5lakhs occupies the whole memory space. (1GB RAM in t2.micro) I have WSGIApplicationGroup %{GLOBAL} in apache setting, so that is not the problem and … -
how to get count of using model relation in django?
I have 2 models 1 is Job Model which is something like this class Job(models.Model): name=models.CharField(max_length=500,null=False,blank=False) description=models.TextField(max_length=5000,null=True,blank=True) slug=AutoSlugField(populate_from='name',null=True, blank=True) industry=models.ForeignKey('Industry',null=True, blank=True, on_delete=models.SET_NULL) and other model is Industry model. This model has one to one relation with Job model Industry model is like this class Industry(models.Model): name=models.CharField(max_length=2000,null=True, blank=True) Now what i'm trying to do is to get count of jobs against each indsutry using industry model like this {% for industry in industry_2 %} <li><a href="#"><h6 class="category-title">{{ industry.name }}</h6> <span class="category-count">{{ industry.jobs_count }}</span> </a></li> {% endfor %} but its not working for me, please help me in this regard to solve this issue. Do suggest any better method also, Thanks -
how can i add a search box inside list_filter django?
i want to add a search box in the filter box (that you define as list_filter) class Review (TrackingModifierMixin): rating = models.FloatField( _("rating"), help_text=_("Rating of the product"), ) class ReviewAdmin(SimpleHistoryAdmin): list_display= ['rating'] list_filter = ['rating'] -
Django, query filter not applying to prefetched data
I have a table that contains the details of cards, and another table that holds the inventory data for those cards for the users. I am trying to get the card's data and include the inventory quantities for the cards returned. I do this by adding a prefetch for the query. However when I try to filter the prefetched data by the user id, it is still returning data for the users other than the one that is logged in. Code: sql_int = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" cards = magic_set_cards.objects.all().exclude(side='b').extra(select={'int': sql_int}) \ .prefetch_related(Prefetch('inventoryCards', queryset=inventory_cards.objects.filter(user_id=request.user.id))) \ .values('id', 'set_id__code', 'set_id__name', 'set_id__isOnlineOnly', 'number', 'name', 'imageUri', 'hasNonFoil', 'hasFoil', 'inventoryCards__user_id', 'inventoryCards__nonfoil', 'inventoryCards__foil') \ .order_by('-set_id__releaseDate', 'set_id__name', 'int', 'number') Data returned: { 'id': UUID('a7ef0985-345d-4d0d-bd71-069870ce4fd6'), 'set_id__code': 'MID', 'set_id__name': 'Innistrad: Midnight Hunt', 'set_id__isOnlineOnly': False, 'number': '46', 'name': 'Curse of Surveillance', 'imageUri': 'https://c1.scryfall.com/file/scryfall-cards/normal/front/d/6/d6a5b3b2-4f27-4c97-9d87-d7bdcc06d36a.jpg?1634348722', 'hasNonFoil': True, 'hasFoil': True, 'inventoryCards__user_id': 3, 'inventoryCards__nonfoil': 2, 'inventoryCards__foil': 0 }, { 'id': UUID('a7ef0985-345d-4d0d-bd71-069870ce4fd6'), 'set_id__code': 'MID', 'set_id__name': 'Innistrad: Midnight Hunt', 'set_id__isOnlineOnly': False, 'number': '46', 'name': 'Curse of Surveillance', 'imageUri': 'https://c1.scryfall.com/file/scryfall-cards/normal/front/d/6/d6a5b3b2-4f27-4c97-9d87-d7bdcc06d36a.jpg?1634348722', 'hasNonFoil': True, 'hasFoil': True, 'inventoryCards__user_id': 1, 'inventoryCards__nonfoil': 0, 'inventoryCards__foil': 1 } ... As you can see from the data above, they are the same cards but it is returning the inventory data for two different users. Please … -
How to serialize a list of objects into list of numbers
With django-rest-framework, how can I serialize the many elements of a one-to-many relationship into a list of integers with their ids? For example in class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks') order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() I would like to get something like { 'album_name': 'Things We Lost In The Fire', 'artist': 'Low', 'tracks': [15, 16, 17, 23] } -
urlpatterns in django for unicode names
I was working on categories in my website and after adding category with id like 11 or more it had a error . Reverse for 'category' with arguments '('more-cat', 14)' not found. 1 pattern(s) tried: ['category/(?P[\w-]+)/(?P[0-9])/'] its the urls.py re_path(r'^category/(?P<slug>[\w-]+)/(?P<id>[0-9])/' , views.listofproducts , name="category"), and its models.py class category(models.Model): sub_category = models.ForeignKey('self' , on_delete=models.CASCADE , null=True , blank=True , related_name='sub') sub_cat = models.BooleanField(default=False) name = models.CharField(max_length=200 , blank=True , null=True) create = models.DateTimeField(auto_now_add=True ,blank=True , null=True) update = models.DateTimeField(auto_now=True ,blank=True , null=True) slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True) image = models.ImageField(upload_to = 'category' , blank=True , null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("home:category" , args=[self.slug , self.id]) please help me with this problem.!