Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save a list of numbers to Django model
I am pulling some data from an API and I want to store it in my Django model. The data is a baseball inning and then runs scored that inning and comes to me like this... "innings":[ 0:0 1:3 2:0 3:0 4:1 5:2 6:0 7:0 8:4 ] I access each individual value like... for game in games: first_inning = game['scoreboard']['score']['innings'][0] second_inning = game['scoreboard']['score']['innings'][1] etc... But if I wanted to save all the data as it is and start the innings at 1 instead of 0, which type of field would I use and how would I do that? Would it be an ArrayField? I really appreciate your help. -
Add Tables As A Field In Django Python
So I Am Making A Shop Website I wanted to ask how do we add tables as a field? Do we use foreign key or something in Django I am using SQLite btw -
DRF Serializer IntegerField Validation To Make Sure ForeignKey Does Exists
I've a ModelSerializer class which uses an IntegerField as a replace for a ForeingKey relation. class CartItemCreateSerializer(serializers.ModelSerializer): product_id = serializers.IntegerField() class Meta: model = CartItem fields = ('id', 'product_id', 'quantity') def validate_product_id(self, value): if not Product.objects.filter(pk=value).exists(): raise serializers.ValidationError('Product not found') return value def save(self, **kwargs): product_id = self.validated_data['product_id'] cart_id = self.context['cart_id'] product = Product.objects.get(id=product_id) # product = get_object_or_404(Product, id=product_id) cart_item, _ = CartItem.objects.get_or_create( cart_id=cart_id, product=product) cart_item.quantity += self.validated_data['quantity'] cart_item.save() self.instance = cart_item return self.instance I've two questions about this class, first regarding the code, the validate_product_id method does a db call to check if the requested Product object exists and then inside the save method there is another call to db to get the same Product again, I think this way is not optimized for querying the same object twice. Is there a better way to check for the existence or raising proper error? second if I use get_object_or_404 the amount of code to write will decrease but there is no chance to raise a concise but relevant Error Message, so What do you usually do? -
Dump data frame values into a PostgreSQL table python
I have this data frame I want to dump this data into a Postgres table which has a foreign key of supplier and origin how can I do that, note that all the information of a supplier and origin exists in another data frame. -
S3 AWS for static files and heroku not working?
I am getting this error log from heroku after configuring S3 for static files. Can someone tell me what is wrong? https://i.stack.imgur.com/71Cja.jpg -
Custom Django template tag is not accessible at all pages
I am creating an app where there is no database because I am working with rest API, so the thing I want to show user phone number on the top of navbar at every page, I created a custom template tag and I am calling get_user_phone(user_phone) whenever someone logs in and pass that logged in user to this method and after loading the tag in the base template I am seeing the phone number but the issue is all other other pages which are extended by that base page is not showing this phone number @register.simple_tag() def get_user_phone(user_phone): return user_phone I am accesssing the user phone like this after loading the template {% get_user_phone user_phone %} -
how to find the diifrence of two time values
i have two functions one for add time to database from html if request.POST: time=request.POST.get("time") print(time) c.execute("insert into addtime(atime) values('"+str(time)+"')") conn.commit()```` I have an Html code to take the time `<form method="POST" > {% csrf_token %} <label>TIMES :</label> <input type="time" name="time" maxlength="30" required="" max="13" title="Enter characters only"> <input type="submit" name="subject" value="ADD Subjects"> </form> ` Here i have a function to compare two times one from database and other one is current time `def alarm(request): f="" time1=[] c.execute("select atime from addtime") data=c.fetchall() for i in data: for j in i: time1.append(j) from datetime import datetime now = datetime.now() print(now) import time f=time.strftime("%H:%M:%S") return HttpResponse("hai") how can I compare the two functions? the database value is stored in a list. later it is appended as string, the current time is also in string format! how can I compare these times, I WANT TO KNOW WHICH VALUE IS MORE CLOSE TO CURRENT TIME AND THE DIFFRENCE BETWEEN THEM? -
Do passing Django Queryset to method triggers database
I'm using Django for my backend and I'm wondering whether doing following thing hits the database. I know Django Querysets are lazy thus doing this only hits the database once : records = RecordModel.objects.all() records = records.filter(id__in=[1, 2, 3]) records = records.filter(name__in=["some", "random", "strings"]) print(records) In that case the database is really triggered when we try to print records. But when passing Queryset as method parameter. Is the database hit 2 times ? For instance: def some_api_endpoint(request): records = RecordModel.objects.all() records = RecordModel.filter_queryset(records, request.query_params) return Response(MySerializer(records, many=True).data) where filter_queryset performs some filtering on the queryset according to the request parameters. I'm wondering here if records are evaluated when passing it to filter_queryset AND when returning them in the Response ? Thanks in advance :) ! -
how to limit the number of time a button is clicked in django
i want to implement how to limit the number of time a button is clicked in django then send the user to the login page. To be more clear with my question, there is a download button and users can download pdfs when they are not logged in, now i want the max download to be 5 before a user is then redirect to the login or maybe register page so they can continue downloading. I tried this simple javascript code to do it but what is does it just increment the number when a button is clicked i do not really know how check if it's upto five click and then redirect. <script type="text/javascript"> var count = 0; var btn = document.getElementById("btn"); var disp = document.getElementById("display"); btn.onclick = function () { count++; disp.innerHTML = count; disp.save; } </script> <button id="btn">Click here to download </button> <span id="display">0</span>Clicked any more information needed? i available to provide it -
Django Real-time notifications in cross-platform apps without using django channels and redis server
Is there a way to get real-time notifications from Django to cross-platform apps without using Django channels and the Redis server? I am using Django in the back end and React in the front end. I used django channels and redis server locally. But due to some limitations, I was unable to push it to AWS. So I need to do it without django channels and redis server. Is there any way to do that? -
django.db.utils.ProgrammingError: column c.relispartition does not exist
USING: MacbookAir M1 (2020), MacOs Monterey(12.2.1), Python (3.10.2), Django (4.0.2), PostgreSQL (14.2) I started a simple django app and when i'm trying to connect my db (postgresql) i get this error File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: column c.relispartition does not exist LINE 3: CASE WHEN c.relispartition THEN 'p' WHEN c.relki... here is my settings.py DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql", 'OPTIONS': { 'options': '-c search_path=prg' }, "NAME": "******", "USER": "******", "PASSWORD": "******", "HOST": "**.***.***.***", "PORT": "5432" } } Never had problems with other db postgres. Have you ever seen something like this? -
aiohttp async with stripe Django
I am learning Django and I am trying to use aiohttp but I am unable to figure how can I use it with stripe API calls. This is my code: class ListCardSerializer(serializers.Serializer): pm = serializers.SerializerMethodField() class Meta: model = Bill fields = ["pm"] def get_pm(self, obj): stripe.api_key = settings.STRIPE_API_KEY cost = stripe.Customer.retrieve(customer_id) pm = stripe.Customer.list_payment_methods( customer_id, type="card" ) return pm I am new to Django any help will be appreciated. I am trying to convert my functions into async await. -
How to get value from dropdown list in django
I am trying to create an application which gets date from a db and then gets input from the user and returns data for that specific user-input value. I am facing an error while doing this. Views.py : from django.shortcuts import render from apple.models import predictions from django.views.generic import View # Create your views here. def home_view(request): return render(request, 'homepage.html') def post(request): company = str(request.POST.get("company-names")) final_date = request.POST["date1"] price = predictions.objects.filter(date=final_date) for x in price: pred = x.company return render(request, 'results.html', {'price': pred}) def back_view(request): return render(request, 'homepage.html') Homepage.html : <!DOCTYPE html> {% extends "base.html" %} {% block content %} <html> <body> <div class="login"> <h1 id = "page-title">Predict Stock Prices</h1> <h3 id = "date-title">Enter date (in format - yyyy-mm-dd)</h3> <h3 id = "company-title">Choose Company</h3> <form action="post" method="post"> {% csrf_token %} <select name="company-names" id="company-names" selected="selected"> <option value="reliance">Reliance</option> <option value="tcs">TCS</option> </select> <!-- <input type="text" id="company-names" name="company-names" placeholder="Company from Nifty-50"> --> <input type="text" name="date1" placeholder="Date after ( 2020-02-18 )" id="date-form" /> <input type="submit" id="button-submit" value="Predict" /> </form> </div> </body> {% endblock %} </html> Error I am getting : Error What my DB looks like : DB -
Search algorithm for crowded database Django
I am looking for search algorithm in order to fast search. I am currently using levenshtein_ratio_and_distance algorithm in order to search. But it is still taking a lot of time to search. Here is my code: def levenshtein_ratio_and_distance(s, t, ratio_calc = False): # Initialize matrix of zeros rows = len(s)+1 cols = len(t)+1 distance = np.zeros((rows,cols),dtype = int) # Populate matrix of zeros with the indeces of each character of both strings for i in range(1, rows): for k in range(1,cols): distance[i][0] = i distance[0][k] = k # Iterate over the matrix to compute the cost of deletions,insertions and/or substitutions for col in range(1, cols): for row in range(1, rows): if s[row-1] == t[col-1]: cost = 0 # If the characters are the same in the two strings in a given position [i,j] then the cost is 0 else: # In order to align the results with those of the Python Levenshtein package, if we choose to calculate the ratio # the cost of a substitution is 2. If we calculate just distance, then the cost of a substitution is 1. if ratio_calc == True: cost = 2 else: cost = 1 distance[row][col] = min(distance[row-1][col] + 1, # Cost of … -
Error Map Keys Must be unique while using YAML extension field in docker compose for django application
hi I have this in my YAML file , and I am getting error Map keys must be unique at <<: *common in django service. version: '3.4' x-common: &common restart: unless-stopped networks: docker_django x-django-build: &django-build build: context: . dockerfile: ./DockerFile.dev services: django: <<: *django-build <<: *common container_name: docker_django_dc01 command: bash -c "python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./:/code depends_on: - postgres -
How to create custom login decorators in django
I am creating an app in django where all the authentication like login signup is done by using an exernal rest api so there is no database involved in it. This is why I am saving logged in user data in request.session now the issue is I don't want to show some of the pages if the user is not inside the sessions, what we usually do back in django apps is use @login_required decorator but now as there is no database so what will be the procedure of not showing those pages to not logged in users. thanks -
Read data from google sheets and dump into Postgres database using python and django
I have data on google sheets and I want to dump data into the Postgres database using python and Django. Note that each row in a google sheet contains information for different tables like it could be a foreign key etc. Am looking for any tutorial/blog to serve this purpose. -
Can't load JS static file, but style.css file still work
This is my error. The styles.css and index.js file in same folder name network. But the styles.css file is work, and index.js file doesn't work, it looking to my other project is Mail [20/Feb/2022 14:17:59] "GET / HTTP/1.1" 200 1804 [20/Feb/2022 14:17:59] "GET /static/network/styles.css HTTP/1.1" 304 0 [20/Feb/2022 14:18:01] "GET /static/mail/inbox.js HTTP/1.1" 404 1667 [20/Feb/2022 14:18:01] "GET / HTTP/1.1" 200 1804 setting.py STATIC_URL = '/static/' index.html {% extends "network/layout.html" %} {% load static %} {% block body %} <div id="allposts-view"> <h2>All Posts</h2> <div id="new-post"> <h5>New Post</h5> <form id="new-post-form"> <textarea id="post-content" class="form-control"></textarea> <input type="submit" class="btn btn-success"/> </form> </div> <div id="post-detail"></div> </div> {% endblock %} {% block script %} <script src="{% static 'network/index.js' %}" defer></script> {% endblock %} index.js console.log('OK'); -
Django user permission on generate specific view depending on user group
I am new to Django user permission and is setting it up for the first time. I need to generate different views after user has logged in. The views being generated depends on the group that the user belongs to. Say we have two users called user1 and user2 user1 belongs to group1 user2 belongs to group1 and group2 For user1 I will like to render a view that is specific for group1. For user2 the view rendered must be have both the content specific for group1 and group2 In my current views.py I am only able to decide if a user has logged in and if true the page staffLoginIndex.html will be rendered. from django.shortcuts import render from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class StaffLoginIndexView(LoginRequiredMixin, View): login_url = '/accounts/login/' def get(self, request, *args, **kwargs): context = dict() context['user'] = request.user return render(request, template_name='staff/staffLoginIndex.html', context=context) -
product.Category: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'name'
I am following a tutorial on YT and I can't migrate my models. from django.db import models class Category(models.Model): name = models.CharField(max_length=255), slug = models.SlugField(), class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f"/{self.slug}/" I've tried several potential solutions... typo issue? class Meta: ordering = ('-name',) tuple & typo? class Meta: ordering = ('-name') tuple issue? class Meta: ordering = ('name') ...but to no avail. I would love if someone could help me out with this -
NOT NULL constraint failed error for a not existing field in Django
I removed name_ko field in Category model but this error is consistently arising even after migration. My models.py is like below. class Brand(models.Model): name = models.CharField(max_length=20) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) class Category(models.Model): name = models.CharField(max_length=10) It's also weird that I'm not getting this error in my computer but it's arising in all of my friends' computer. What should I do? I also cleared DB. -
Bootstrap 5 Dropdown Not Functioning
I am using Bootstrap 5 along Django to develop a website and I'm having issues getting a dropdown to function correctly. I have copied this code from w3schools exactly how it is and it is not working when I load the HTML. I've tried running it on the latest version of Chrome and Firefox and still no success. Does it have to do with the Bootstrap CDN? <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> </head> <body> <div class="container mt-3"> <h2>Dropdowns</h2> <p>The .dropdown class is used to indicate a dropdown menu.</p> <p>Use the .dropdown-menu class to actually build the dropdown menu.</p> <p>To open the dropdown menu, use a button or a link with a class of .dropdown-toggle and data-toggle="dropdown".</p> <div class="dropdown"> <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown"> Dropdown button </button> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Link 1</a></li> <li><a class="dropdown-item" href="#">Link 2</a></li> <li><a class="dropdown-item" href="#">Link 3</a></li> </ul> </div> </div> </body> </html> -
How to I override dj-rest-auth Registrations' SocialLoginSerializer? Error "non_field_errors": [ "Incorrect value" ] while running of postman
my system uses a custom user entity and I need to create this entity inside SocialLoginSerializer. It is not seemed to be mentioned here: https://dj-rest-auth.readthedocs.io/en/latest/configuration.html I tried adding in settings.py REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'BackendApp.auth_serializers.LoginSerializer', 'TOKEN_SERIALIZER': 'dj_rest_auth.serializers.TokenSerializer', "PASSWORD_RESET_SERIALIZER": "BackendApp.auth_serializers.PasswordResetSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER':'BackendApp.auth_serializers.RegisterSerializer', 'SOCIAL_LOGIN_SERIALIZER' :"BackendApp.auth_serializers.SocialLoginSerializer" } I ran the following on command line POST 'http://localhost:8000/dj-rest-auth/google/' and JSON: { "access_token": "ya29.A0ARrdaM_u-mk71-yQia3Kx2NpKe8PTlMixeVuXUB_CsjnWhOT-mb4TdG9FyED7iPWHQskQ1kyjJ8jqsdNwv7XY5-6-G36gwwAIS3tEVCKMwzUXdUB26OH7rqqcUfUfdskTdN85M04ljq0m0DYFOudfwdHMxNwjAOjF-3m-EjTBXFhtp6rrzhXBIwZVVE58Pghy28x0YNu0wE0Iu-J5NbcGlSIF_NmevLQ6QSNdpTglmZfKQOc06MKddlW-kRlE4pSpMSSOA", "code": "", "id_token": "", "endUserType":"Refashionee" } but I have gotten "non_field_errors": [ "Incorrect value" ] and POST /dj-rest-auth/google/ HTTP/1.1" 400 40 Any help is greatly appreciated My customised SocialLoginSerializer.py (Original source code from dj-rest-auth) class SocialLoginSerializer(serializers.Serializer): access_token = serializers.CharField(required=False, allow_blank=True) code = serializers.CharField(required=False, allow_blank=True) id_token = serializers.CharField(required=False, allow_blank=True) endUserType = serializers.CharField(required=True, write_only=True) .... def get_cleaned_data(self): return { 'endUserType': self.validated_data.get('endUserType', '') } def validate(self, attrs): .... if not login.is_existing: # We have an account already signed up in a different flow # with the same email address: raise an exception. # This needs to be handled in the frontend. We can not just # link up the accounts due to security constraints if allauth_settings.UNIQUE_EMAIL: # Do we have an account already with this email address? account_exists = get_user_model().objects.filter( email=login.user.email, ).exists() if account_exists: raise serializers.ValidationError( _('User is already registered with this … -
How to integrate django with existing Postgres database
To use an existing database in Django, you need to have a model for each table. But creating models for existing tables manually is just too much work. However, there's no need to do that, since Django has a builtin tool to solve this exact problem. Reference article linked here: how-to-integrate-django-with-existing-database -
Custom error message not being raised during model validation
I have created a custom max_length error message on my Question model title field. Yet when the QuestionForm is validated, it raises the default max_length error message: 'Ensure this value has at most 55 characters (it has 60).'. Why is the default error message being used when the form is validated? AssertionError: ValidationError(['Ensure this value has at most 55 characters (it has 60).']) != 'The title of your question is too long' class TestQuestionSubmissionTitleField(TestCase): """Verify that an error is raised when the title exceeds the maximum character limit.""" @classmethod def setUpTestData(cls): user = get_user_model().objects.create_user("TestUser") profile = Profile.objects.create(user=user) msg = "This is a very very very very very very very very long title" data = { 'title': msg, 'body': "The context to this post doesn't explain alot does it" } cls.form = QuestionForm(data) def test_invalid_question_title_length(self): import pdb; pdb.set_trace() self.assertFalse(self.form.is_valid()) self.assertTrue(self.form.has_error("title")) self.assertEqual( self.form.errors.as_data()['title'][0], "The title of your question is too long" ) from django.forms import ModelForm, CharField from django.forms.widgets import TextInput, Textarea from .models import Question class QuestionForm(ModelForm): body = CharField( widget=Textarea(attrs={"class": "question_input_field"}), min_length=50, help_text="Clarify your question with as much detail as possible", error_messages={ 'required': "Elaborate on your question", 'min_length': "Add more info to your question" } ) tags = CharField(widget=TextInput( attrs={"class": …