Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Django DB connection
I have an eLearning application developed in Django and deployed on Heroku. But I am facing one issue that is the local testing data that I have created is not reflected on the Heroku server. My application is successfully been deployed and is working like a charm but I don't have data on the Heroku server. Like on my local machine I have a username and password to login into the application and it works well on my local system but not on Heroku, the form gets displayed but I cannot log in. The error is that the data entry doesn't exist. Even some static data which gets rendered onto the home page is also not displayed. Is there any command which I need to run to upload my data from the local machine to the Heroku server? I have already used this command heroku run python manage.py migrate and then also pushed the updated version of the project to the Heroku master branch with git push heroku master after doing the commit. But still, no data is reflected onto the server. I have also tried the command heroku pg:push but it gives me missing two arguments error. Can someone … -
'Manager' object has no attribute 'normalize_email'
I have a fairly simple model with a many-to-many relationship: class Person(AbstractUser): ... topics = models.ManyToManyField("web.Topic", through="Interests", blank=True) ... objects = models.Manager() def __str__(self): return "{last}, {first} ({id})".format( last=self.last_name, first=self.first_name, id=self.id ) class Meta: ordering = ("last_name", "first_name") Based on that model, I have a form defined by: class TopicForm(ModelForm): class Meta: model = Person fields = ("topics",) def __init__(self, *args, **kwargs): super(TopicForm, self).__init__(*args, **kwargs) self.fields["topics"].widget = SelectMultiple(attrs={"size": 20}) self.fields["topics"].queryset = Topic.objects.order_by(Lower("name")).all() self.fields[ "topics" ].help_text = "Don't forget to hold the CTRL key (or cmd on a Mac) to select multiple topics" Finally, the view looks like: def update_my_profile(request): topics_form = TopicForm(request.POST or None, instance=request.user) if request.method == "POST": if topics_form.is_valid(): topics_form.save() context = { "topics_form": topics_form, } return render(request, "web/profile.html", context) for a reason I really don't get, the django framework is failing on if topics_form.is_valid(): I get the following error message: 'Manager' object has no attribute 'normalize_email' Surprinsingly, the failing code is within the django framework (django/contrib/auth/models.py in clean at line 365): def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) Even more surprisingly, if I put a breakpoint (in VSCode) at the line if topics_form.is_valid(): and run the command manually in the debug console, it does not fail... what did … -
Adjusting images in django templates
I am working on a django website, the code works pretty well but I'd like to make a few adjustments in order to make the web more professional. There's a section in the web called latest posts. Here's the code: <!-- Latest Posts --> <section class="latest-posts"> <div class="container"> <header> <h2>Latest from the blog</h2> <p class="text-big">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </header> <div class="row"> {% for obj in latest %} <div class="post col-md-4"> <div class="post-thumbnail"><a href="#"><img src="{{ obj.thumbnail.url }}" alt="..." class="img-fluid"></a></div> #Here's the image <div class="post-details"> <div class="post-meta d-flex justify-content-between"> <div class="date">{{ obj.date }}</div> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> </div><a href="#"> <h3 class="h4">{{ obj.title }}</h3></a> <p class="text-muted">{{ obj.overview }}</p> </div> </div> {% endfor %} </div> </div> </section> What you can see in the website is this: As you might have noticed, the images aren't adjusted and therefore, the text doesn't look aligned. Is there any code that can adjust this so that it looks like this? -
How to Write Custom Username validation using Self.clean_username for Profile Update form in Django?
I am newbie and i'm still learning django. If i've written something wrong please help me to correct it. Don't downvote the question. Hi i am writing my custom form validation for user profile update. My profile update form has - username first name last name profile image First i have used default form validation. It is also good but i want to update the error message so i tried to create a custom validation function as i seen in a post in stackoverflow. Please also check my username validation in forms.py So what is the error now? Now i am facing one more issues If i click on update button without changing anything then it shows can't use this username. {username is set to unique=True in model fields} If i don't update username and update just first name and last name. It doesn't allow this says same error. "Username is already taken" {because that username is validated and it already taken by current user"} what exactly i want? Instead of changing just error message now i want to write my own validation for this. I want if some click on update without changing any data no error message should … -
More optimal Database Design (Django) (PostgreSQL)
I have a SQL database table called Emp_Mast. This is quite a big table with around 70 columns and about 2000 rows. I have a few foreign key relations (eg Desgn_Mast) that need the history of their changes to be recorded. To do this another table is maintained called Desgn_Trans which will eventually have around 10000 records but only 4-5 columns. Here are the Table structures: Emp_Mast emp_mast_id (pk) fname mname lname desgn_mast (fk) ...... (around 65 more columns) Desgn_Mast desgn_mast_id (pk) desgn_name Desgn_Trans desgn_trans_id (pk) emp_mast_id (fk) desgn_mast_id (fk) created_date_time Currently whenever a change is made in desgn of the employee I update both the tables (Emp_Mast) and (Desgn_Trans). A PATCH request is made to Emp_mast and POST request is made to desgn_trans for any change. However this seems redundant and wasteful. The other option I have is to remove the column 'desgn_mast' from Emp_mast altogether, however the issue I think I will face is that I will have to query two tables - Emp_mast & Desgn_trans to get both the employee and desgn data. When the tables get large I think the speed overhead will be significant. Can someone please comment on which is the better design approach? -
Hi guys, I'm working on Writing your first Django app, part 2 tutorial, and I tried _str_() function and it doesn't give me the same result
this is my Question class in models.py : class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def _str_(self): return self.question_text when I execute : Question.objects.all() it gives me : <QuerySet [<Question: Question object (1)>, <Question: Question object (2)>]> any ideas ??? -
can't update checkbox in django template for loop table from model object, using jquery. jquery doesn't iterate with django loop
I have a dynamic table using for-loop in django template, it contains a checkbox on each row which I want to update as checked or unchecked from the boolean model object which is already available in the template, on loading the page. I have the code on template as: <tbody id="order_list_body"> {% for item in items %} <tr height="50px"> <td align="center"> {{item.item}} </td> <td align="center"> {{item.price}} </td> <td align="center"> {{item.stock}} </td> <td align="center"> <input type="checkbox" id="available" name="available" > {{item.available}} </td> <td align="center"> <a href="{% url 'order' %}" class="btn btn-info">Edit</a> <a href="{% url 'order' %}" class="btn btn-warning" >Delete</a> </td> </tr> //jquery to update the checkbox with the 'item.available' boolean <script> $(document).ready(function(){ if ('{{item.available}}' == 'True'){ $('#available').prop('checked', true); console.log("checked {{item.item}} as {{item.available}} in the true loop"); } else if ('{{item.available}}' == 'False'){ $('#available').prop('checked', false); console.log("checked {{item.item}} as {{item.available}} in the false loop"); } }); </script> {% endfor %} But somehow the javascript is not updating the checkboxes according to the boolean 'item.available' on the load of page. console.log gives : checked item1 as True in the true loop (index):197 checked item2 as False in the false loop (index):270 checked item4 as True in the true loop (index):353 checked item6 as False in … -
How to run this code inside a view function in views.py? urgent. thank you
import cv2 import pandas as pd import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() img = cv2.imread(file_path) clicked = False r = g = b = xpos = ypos = 0 index = ["color", "color_name", "hex", "R", "G", "B"] csv = pd.read_csv('codes.csv', names=index, header=None) def getColorName(r, g, b): minimum = 10000 for i in range(len(csv)): d = abs(r - int(csv.loc[i, "R"])) + abs(g - int(csv.loc[i, "G"])) + abs(b - int(csv.loc[i, "B"])) if d <= minimum: minimum = d colorname = csv.loc[i, "color_name"] return colorname def draw_function(event, x, y, flags, param): if event == cv2.EVENT_MOUSEMOVE: global r, g, b, xpos, ypos, clicked clicked = True xpos = x ypos = y b, g, r = img[y, x] b = int(b) g = int(g) r = int(r) cv2.namedWindow('Machining Process Identification') cv2.setMouseCallback('Machining Process Identification', draw_function) while 1: cv2.imshow("Machining Process Identification", img) if clicked: cv2.rectangle(img, (20, 20), (380, 60), (b, g, r), -1) text = getColorName(r, g, b) cv2.putText(img, text, (50, 50), 2, 0.8, (255, 255, 255), 2, cv2.LINE_AA) if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyAllWindows() root.mainloop() -
NOT NULL constraint failed: forum_thread.title
i recently learn django and want to do some project and i thought lets a forum website but while making a discuss forum when i login and want to post query i got this error NOT NULL constraint failed: forum_thread.title models.py from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User from datetime import datetime class Thread(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) category = models.ForeignKey('category', related_name="Thread", on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() timestamp = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title class Category(models.Model): sno = models.AutoField(primary_key=True) name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) description = models.TextField() timestamp = models.DateTimeField(default=datetime.now, blank=True) class Meta: verbose_name_plural = "Categories" views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .models import Thread, Category def addThread(request): if request.method == "POST": thread_title = request.POST.get('threadtitle') thread_slug = request.POST.get('threadslug') thread_category = request.POST.get('threadcategory') thread_description = request.POST.get('threaddescription') user = request.user thread = Thread(title = thread_title, slug = thread_slug, category=thread_category, description = thread_description, user = user) thread.save() messages.success(request, 'thread added successfully') return redirect('home') -
Django get all the latest values of unique entries of a column in a Table
I want to get all the latest values of unique entries of a column in a Table. For Example I have a table like this, which is called Test |____id|____fk1|__created| | 1| 1| Nov 5| | 2| 1| Nov 2| | 3| 1| Nov 1| | 4| 2| Nov 4| | 5| 3| Nov 9| | 6| 3| Nov 7| Now I want to get all the entries in the table with unique 'fk1' values but the row where the 'created' column has the latest date. I want Django to return the queryset of the following rows |____id|____fk1|__created| | 1| 1| Nov 5| | 4| 2| Nov 4| | 5| 3| Nov 9| What is a efficient Django way to do this? -
How to hide password with ********* on swagger UI with Django
Can you please tell what should i do to to hide the password with ***** when i entering on the swagger UI , and value should be passed to the argument correctly -
Django model inheritance primary keys
I am using Django model inheritance. Similar to the example from the documentation: from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) Since "Each model corresponds to its own database table", how are primary keys assigned? Do I have any guarantee that there are no collisions between the restaurant _id values and the Place _id values? How strong is this guarantee (Will the DB enforce it)? -
How to Develop individual dashboard interphase for different users
Hello fellow developers, I am at an intermediate level in Backend Development using Django. I need to create a dashboard system whereby different users can create an account which automatically creates a Bar for them on which they can view their individual analytics on it. I am not sure of what specific keyword to use to search for my request, but I think it's somewhat close to a multivendor system. I would be glad to have recommendations as to how to get this done or references to simple systems similar to this or tutorials. Thanks in advanvce. -
Django or React for a website ? What should I use [closed]
I want to build a website but I can’t decide that should I use Django or React.js because they both are awesome but there is one thing that I can’t find In React and that is smtplib because the website I am building has to send mails to me and I know about Firebase but it has some limits, is there any good alternative to smtplib in React. -
why cant i access my django website on heroku
2020-12-07T09:11:23.229280+00:00 app[web.1]: File "", line 971, in _find_and_load 2020-12-07T09:11:23.229280+00:00 app[web.1]: File "", line 953, in _find_and_load_unlocked 2020-12-07T09:11:23.229284+00:00 app[web.1]: ModuleNotFoundError: No module named 'STOCK' 2020-12-07T09:11:23.229493+00:00 app[web.1]: [2020-12-07 09:11:23 +0000] [12] [INFO] Worker exiting (pid: 12) 2020-12-07T09:11:23.312182+00:00 heroku[web.1]: Process exited with status 3 2020-12-07T09:11:23.354768+00:00 heroku[web.1]: State changed from starting to crashed 2020-12-07T09:11:26.483885+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=stockwares.herokuapp.com request_id=886eaa6b-6294-49e8-a765-634918f2e93b fwd="223.236.7.136" dyno= connect= service= status=503 bytes= protocol=https 2020-12-07T09:11:28.426668+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=stockwares.herokuapp.com request_id=f89b8ecb-bbc3-4004-93a3-63dd230a3b73 fwd="223.236.7.136" dyno= connect= service= status=503 bytes= protocol=https 2020-12-07T09:12:41.759328+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=stockwares.herokuapp.com request_id=ab605bed-037f-4f76-b3b9-bccf30882066 fwd="223.236.7.136" dyno= connect= service= status=503 bytes= protocol=https 2020-12-07T09:12:42.571231+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=stockwares.herokuapp.com request_id=ab5dfcf0-beeb-4f3b-b65e-1ba34acde43c fwd="223.236.7.136" dyno= connect= service= status=503 bytes= protocol=http -
Python : name 'set_password' is not defined
Im trying to register users hashing their passwords before add to database as follows settings.py PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) Models.py from django.contrib.auth.models import AbstractBaseUser class Users(AbstractBaseUser): name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=255) Views.py name = form.cleaned_data.get('name') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') date_joined = date.today() if Users.objects.filter(email=email).exists() and Users.objects.filter(name=name).exists() : messages.info(request, 'User already exists') else: Users.objects.create(name=name, email=email, password=set_password(password), date_joined=date_joined) but when i actually trying to create the user i get Python : name 'set_password' is not defined What is wrong? do i need to import something at Views.py? -
Generate CSV while saving the django Model
In my django model I have start and end date once I filled and then click the generate button (Save modified as Generate) It will save and download the data as CSV. In my case I have done all the parts but the csv is not downloaded because the form is reloaded and then come back to list data page. I want to download the csv file after data saved. -
How to install Django on existing AWS Lightsail instance?
I'm looking for a replacement for Webfaction, which can no longer support Ghost or Django sites. I've picked AWS Lightsail as the pricing seems competitive and the documentation friendly. I've set up a Lightsail instance with Ghost pre-installed and successfully migrated my Ghost instance over there. However, I'd now like to migrate an existing Django site there and I'm not sure: Is it possible to have multiple sites with different URLs running on the same Lightsail instance? Can I add Django to an existing Lightsail instance using the Bitnami clickable installer, or will I need to install it from the command line? The documentation isn't clear. -
Why is My Django Project Hosting Static From myproject/static/django_restframework?
I am trying to access a script file in one of my templates and it is not loading in the template (default.html): <!DOCTYPE html> <html> <head> {% load static %} <script type="text/javascript" src="{% static 'static/js/main.js' %}"></script> <meta charset="utf-8" /> <title>Add a GeoJSON line</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no> <style> body { margin: 0; padding: 0; } #map { position: absolute; top: 0; bottom: 0; width: 100%; } </style> </head> <body> </body> </html> The path to static defined in settings.py is: STATIC_URL = '/static/' STATIC_ROOT = '/Users/me/dbapi/static' I have run collectstatic but the folder that the site gets the static files from is inside a folder called rest_framework, (located at /User/me/dbapi/static/rest_framework) which is not part of the path in settings.py. So in addition to not serving my files inside the static folder (which is located at /Users/me/dbapi/static/) it is choosing to only serve files from a path that is not defined in settings.py. Can anyone help me understand this? Here is my settings.py: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! … -
How to preview two queries in a autocomplete select2 dropdown
I have an autocomplete select2 dropdown as my django form field like bellow: which the form code is like below: class categories_form(forms.ModelForm): categories = forms.ModelChoiceField( queryset= categories.objects.none(), widget= autocomplete.ModelSelect2( url='load_categories', attrs={ 'data-placeholder': 'Select a category', 'data-html': True, 'style': 'min-width: 15em !important;', } ) ) class Meta: model = Post fields = ['categories'] def __init__(self, *args, **kwargs): super(category_form, self).__init__(*args, **kwargs) self.fields['categories'].queryset = categories.objects.all() But I what to add sub category to the same form, something like below which I took from select2: But I have no idea how to add another query to the form and handle it in template!! -
AttributeError at /products/1/buy/ 'OrderForm' object has no attribute 'save'
Im trying to build a django form for placing orders in my ecommerce website. But, when I press the Place Order button, I get this traceback error: Internal Server Error: /products/1/buy/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\apnibakery\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\Desktop\Django\apnibakery\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\Desktop\Django\apnibakery\bakery\apnibakeryy\views.py", line 33, in buy form.save() AttributeError: 'OrderForm' object has no attribute 'save' [07/Dec/2020 14:06:34] "POST /products/1/buy/ HTTP/1.1" 500 64996 Here is my OrderForm: class OrderForm(forms.Form): name = forms.CharField(max_length=30) email = forms.EmailField() address = forms.CharField(widget=forms.Textarea()) zip_code = forms.CharField(min_length=6,max_length=6) My view function that handles the orders: def buy(request,id): product = Product.objects.get(id=id) form = OrderForm() if request.method == 'POST': form = OrderForm(data=request.POST) if form.is_valid(): form.save() return HttpResponse("Your order has been successfully placed!!") context = { 'form':form, 'product':product, } return render(request, 'buy_page.html',context) I have never ran into this error before. Can someone help me out? -
How to migrate django users to firebase when the rounds are too high?
I'm looking to migrate user from Django to firebase, below is the code I'm using for testing. The issue I'm facing is that it seems that the passwords have been hashed using 150k rounds when the firebase docs says the maximum is 120k for SHA256: https://firebase.google.com/docs/auth/admin/import-users#python Is there an alternative? Here is the error I get: ValueError: rounds must not be larger than 120000. import firebase_admin from firebase_admin import auth, exceptions from passlib.utils import to_bytes server_path = '' fb_credentials = firebase_admin.credentials.Certificate(server_path + 'files/serviceAccount.json') firebase_admin.initialize_app(fb_credentials) old_hash = 'pbkdf2_sha256$150000$rsWX3Dbbd3K6$EYgXPBAz/Ero9PIgIFs/8pWGmGT+diTOQs1DZv4Ytjw=' email = 'user@gmail.com' rounds = int(old_hash.split('$')[1]) salt = old_hash.split('$')[2] users = [ auth.ImportUserRecord( uid='70sSUptkmkN95QTFJ0gWduzdlpP1', email=email, password_hash=to_bytes(old_hash), password_salt=to_bytes(salt) ), ] hash_alg = auth.UserImportHash.pbkdf2_sha256(rounds=rounds) try: result = auth.import_users(users, hash_alg=hash_alg) for err in result.errors: print('Failed to import user:', err.reason) except exceptions.FirebaseError as error: print('Error importing users:', error) -
Distinct element of foreign key in django ORM using annotate
I'm having three models . Here is the model structure class Product: size = models.CharField(max_length=200) class Make: name = models.CharField(max_length=200) product = models.ForeignKey(Product) class MakeContent: make = models.ForeignKey(Make) I am having a chart for that I am fetching the query like this qs = Make.objects.values('product__size').annotate( count=Count('product__size') ) // Here I'm getting data count as 65 only .... That's correct also How do I change query from the model MakeContent I have tried this qs = MakeContent.objects.values('make__product__size').annotate( count=Count('make__product__size'), ) // Here I'm getting data as 420 .... But it should be 65 or less than 65.... Because I need the product_size data of Table Make from Table MakeContent -
Should django health-check endpoint /ht/ be accessible from everybody?
From the documentation reported here I read This project checks for various conditions and provides reports when anomalous behavior is detected.The following health checks are bundled with this project: cache, database, storage, disk and memory utilization (viapsutil), AWS S3 storage, Celery task queue, Celery ping, RabbitMQ, Migrations and from use case section The primary intended use case is to monitor conditions via HTTP(S), with responses available in HTML and JSONformats. When you get back a response that includes one or more problems, you can then decide the appropriate courseof action, which could include generating notifications and/or automating the replacement of a failing node with a newone And then The /ht/ endpoint will respond aHTTP 200 if all checks passed and a HTTP 500 if any of the tests failed. From a security point of view: should this url (https://example.com/ht) be reachable from everybody? It seems to give away different information. -
Serving Video with DRF
I almost looked for every possible source but is not satisfied or not found optimum way or path. Actually i have to build a netflix clone (not exactly but a video on demand platform for one local client). The tech stack will be React at the frontend and DRF (Django Rest Framework) at the backend. I know the node will match my purpose at best, but this needs to be done on DRF. How should I return the video, should I return it in bytes, packets and what can sample code look like, how frontend should fetch it. It will really help if you put your insight, in general. Thank you