Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DateField format in DjangoTemplate
I am using paginator to divide reviews on pages, my model has DateField created = models.DateField(auto_now_add=True) I am using ajax to do it without refreshing page. When i put it in my template like this {{review.created}} It displays in format like 06 June 2021 But with ajax, where i pass 'date':obj.created It displays in format 2021-06-06 How can i made it to display similiar in one of these formats? I prefer first format, but second will be acceptable too -
Issue installing and configuring GeoDjango
I am following the following tutorial with creating a Geo Location based web app. Although, I've ran in to a few challenges which I've been trying to figure out how to resolve. Reference to GeoDjango tutorial: https://realpython.com/location-based-app-with-geodjango-tutorial/ Per the instructions (on the link provided above) - I have included django.contrib.gis as apart of my Installed Apps. Although, Gunicorn is failing to start when this include is in place. So I'm guessing it will most likely be because I need to install other relevant libraries in order to get GeoDjango working. I did a little digging online and came across this link - https://docs.djangoproject.com/en/3.2/ref/contrib/gis/install/geolibs/ Which seems to references the libraries which need to be installed. I have managed to install GEOS and PROJ perfectly fine. Although, the final requirement is to install GDAL. So I found the relevant install command for GDAL pip3 install gdal but I am receiving the following error when installing this library within the SSH console. Running setup.py install for gdal ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3.6 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xjvcvnos/gdal_5ab038f0da3b44488d8b78e9cb9b461a/setup.py'"'"'; __file__='"'"'/tmp/pip-install-xjvcvnos/gdal_5ab038f0da3b44488d8b78e9cb9b461a/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code … -
testdriven.io django docker tutorial error on test CI section
Cannot get the CI section complete because pytest fails. looking at the logs of the test build it errors with a sqlite3 error when it's supposed to be connecting to the postgres container that's launched for the tests. need some help figuring out where the error might be. I made my gitlab project public and will include a link directly to the error. https://gitlab.com/hectormalvarez1/mgdusa/-/jobs/1322478542 -
Request.user has no attribute user when used in settings.py
request.user generates a AttributeError: 'WSGIRequest' object has no attribute 'user' error when I try to use it in my settings.py file. Am I doing something wrong? Settings.py: def show_toolbar(request): if DEBUG: return True #if not request.is_ajax() and request.user and request.user.UserSettings.debugger: # return True return False DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': 'acacia2.settings.show_toolbar', } -
How to solve decimal.InvalidOperation on the server?
Info: I have a project where frontend is on ReactJS, and backend is on Django. The problem: When customer placing an order, the server returns 500 InvalidOperation at /api/orders/ [<class 'decimal.InvalidOperation'>] Additional info: It works perfect on test server, but fails on live. The docker containers and back/front code are the same. Taken efforts: rows like round(Decimal((obj.total_price * 100)) / discount_revers - Decimal(obj.total_price), 2) i transform into round(((Decimal(obj.total_price) * Decimal(100))) / discount_revers - Decimal(obj.total_price), 2) and the error still the same. The Question: How to solve this? -
Django testing custom signal arguments with assertIsInstance: AssertionError: <class 'path.to.Foo'> is not an instance of <class 'path.to.Foo'>
I am using Django 3.2 I have written an app that raises custom events, and I am writing tests for the apps. Here is the relevant section of my code: class TestAppModel(TestCase): # .. set up instance variables etc. def test_liked_signal_emits_correct_data(self): self.signal_was_called = False self.sender = None self.instance = None self.event_type = None self.actor = None def handler(sender, instance, event_type, actor, **kwargs): self.signal_was_called = True self.sender = sender self.instance = instance self.event_type = event_type self.actor = actor item_liked.connect(handler) self.daddy.like(self.admin_user) # Check that the sender is a Foo self.assertIsInstance(self.sender, Foo) # <- Nonsensical error emitted here When I run the test, I get the error message: AssertionError: <class 'social.models.Foo'> is not an instance of <class 'social.models.Foo'> Which obviously, is a nonsensical error message that doesn't help me solve the problem. My question is why am I not able to check the instance type using assertIsInstance, and how do I check the class type in the signal receiver? -
How do i resolved user's post name which display email instead of their full name in a social media app am creating?
Am currently working on a social media up in Django but am facing a challenge with the post model app since it displays their email address, when they post a pic or a write feed post instead of their full name! My user model authenticate with email address rather than users name. I don't know if this is the actually course of the problem! How do i get users full name on their post instead? I still want to be able to authenticate users with email but their post should be displayed in their full name. Here my user's model class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email,username,last_name, password, **extra_fields): values = [email,username] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, username=username, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, username, first_name,last_name, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email,username, first_name,last_name, phone_number, password, **extra_fields) def create_superuser(self, email, username,phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email,username,phone_number, password, **extra_fields) class User(AbstractBaseUser, … -
DNS record look up with Python / Django [dnspython]
I am trying to get DNS records of particular domain. So, I found dnspython package where it could be easily done. It works fines when I run it from my computer. However, when I call it from Django views it shows the previous records (old records) which means it's not updating. Is it some kind of caching in OS level? Note that, I am also using Docker. Restarting docker and clearing cache in Django didn't help, still shows old records. Here's the sample code for checking records: import dns.resolver result = dns.resolver.resolve("domain.com", "TXT")[0].to_text() The code snippet above works and shows any update in TXT record, when I run it from my computer. However, in Django it stucks in old records and not updating. Thanks for any help. -
Im not able to install mysqlclient on macOS
Im trying to connect Django with mySql, but I'm running into an error. I already have mySql installed, and I've already try reinstalling openssl, but I'm still getting the same error. Im on macOs 11.4 and I'm using python 3.9.2 alongside Django 3.2.3. Im getting the following error message when typing on terminal pip3 install mysqlclient: Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB) Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-record-6ggb6_as/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9/mysqlclient cwd: /private/var/folders/g9/pvrsfhg9113bbcp23bllwyhw0000gn/T/pip-install-z7ib1rf7/mysqlclient/ Complete output (44 lines): mysql_config --version ['8.0.25'] mysql_config --libs ['-L/opt/homebrew/Cellar/mysql/8.0.25_1/lib', '-lmysqlclient', '-lz', '-lzstd', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/opt/homebrew/Cellar/mysql/8.0.25_1/include/mysql'] ext_options: library_dirs: ['/opt/homebrew/Cellar/mysql/8.0.25_1/lib'] libraries: ['mysqlclient', 'zstd', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/opt/homebrew/Cellar/mysql/8.0.25_1/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,0,3,'final',0)"), ('__version__', '2.0.3')] running install running build running build_py creating build creating build/lib.macosx-10.9-universal2-3.9 creating build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-universal2-3.9/MySQLdb creating … -
How to assign multiple classes to the django form widget's parameter - "attrs"?
This is my simple forms.py: class SearchForm(forms.Form): search = forms.CharField( label="", max_length=100, widget=forms.TextInput( attrs={ "class": "form-control me-2", "type": "search", "aria-label": "Search", } ) ) form.html: <form class="d-flex" method="GET" action="."> {% csrf_token %} {{ form.as_p}} <!-- <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> --> <button class="btn btn-outline-success" type="submit">Search</button> </form> I need my input tag have two bootstrap classes "form-control" and "me-2", but separating them with whitespace in widget's attrs dictionary seems doesn't work. Any suggestions? -
Django or NodeJS for long-term web and business project?
Good afternoon all, we are struggling to decide which way to go for a project and would like to have some insight from people who have been dealing with this. We have to invest in training/time for the two people who are working on our business and we would like to understand which way to go. The people Both have a good understanding of HTML, CSS, SASS and some JS One has some experience with PHP One has more experience with Python The Project Database driven website that will host and display hundreds of products (laboratory products which will need specific templates for each product Shopping chart for reagents and lower cost products A section with a knowledge base The website(s) will be multilingual, with different products for different countries Integrated CRM, connected to the products, stock management and shopping chart Potentially (desirable, but not necessary) an APP for the phone An application that will link all the components AI services and big data analytics (as a separate product) The timeline 2-3 years, potentially 4 for completion This is to move what we are doing manually at the moment (and what we are planning to do) to something that is … -
best way to handle websocket jwt authetication using django channels for backend and android kotlin?
I have learned how to make a simple chat app with Django channels and android with Kotlin. I'm using rest framework in Django. What is the best way to handle authentication in both platforms? I couldn't find anything useful in the internet. -
what is a 'no such table' error in Django for creating a register page?
I'm trying to create a registration page. I'm getting this error the views.py: def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: return render(request, "auctions/login.html") def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: print("momooo!") user = User.objects.create_user(username, email, password) print(("more mooomoo")) user.save() except IntegrityError: return render(request, "auctions/register.html", { "message": "Username already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/register.html") the register.html page: {% extends "auctions/layout.html" %} {% block body %} <h2>Register</h2> {% if message %} <div>{{ message }}</div> {% endif %} <form action="{% url 'register' %}" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="username" placeholder="Username"> </div> <div class="form-group"> <input class="form-control" type="email" name="email" placeholder="Email Address"> </div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <div class="form-group"> … -
How do I get the value from the field in a one-to-one relationship tabularinline
How do I get the value from the field in a one-to-one relationship. The tables Ojbects and Object_Info are linked using TabularInline. And I want to get a value from a field by OneToOneField relationship. How to do it with signals. In this case I'm using post_save. I get an error. class Ojbects(models.Model): title = models.CharField(max_length=10) class ServerInfo(models.Model): data = models.TextField() object = models.OneToOneField(Ojbects, on_delete=models.CASCADE, related_name="data") @receiver(post_save, sender = Ojbects) def create(instance, sender, **kwargs): print(instance.data) -
Django structure with directories don't load views
I'm coming from the larvae on Django and I have a problem on this side and I can't say 100% of the documentation that I understand exactly the structure. Do I have to make a directory for each part of the application, for example? For example for the user a special directory, for the management of the application another one and so on? Or can I have a main application like I did acm and have in it a folder view with several views.py and import them in urls? Because I can't do that, I get an error. For example this is my structure structure This is the error AttributeError: module 'main.views' has no attribute 'pages_views' Url function from main from django.contrib import admin from django.urls import path from django.urls import include from rest_framework_jwt.views import obtain_jwt_token from . import views urlpatterns = [ path('', views.pages_views.index, name='index'), ] AttributeError: module 'main.views' has no attribute 'pages_views' And url acces from project_management (core app I think) from django.contrib import admin from django.urls import path from django.urls import include from rest_framework_jwt.views import obtain_jwt_token from . import views urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls) ] -
How can upload word or pdf file in django
I am trying to upload word/pdf file but it's not working. My form submit successfully but file not store in document field. It show empty field and it also not show any error during submit the form, i don't know where is the issue and how can i fix the issue. I add the MEDIA URL in setting and also define the path in urls View.py class SaloonRegistration(TemplateView): template_name = 'saloonRegistration.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): saloon = SaloonRegister( saloon_name=self.request.POST.get('saloon_name'), owner_name=self.request.POST.get('owner_name'), address=self.request.POST.get('address'), contact_no=self.request.POST.get('contact_no'), document=self.request.POST.get('document') ) saloon.save() return redirect('menu') Model.py class SaloonRegister(models.Model): saloon_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() document = models.FileField(upload_to='doc/') is_active = models.BooleanField(default=False) Template {% extends 'home.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="saloon_name">Saloon Name <input type="text" name="saloon_name" placeholder="Enter Your first name"> </label> <label for="owner_name">Owner Name <input type="text" name="owner_name" placeholder="Enter Your last_name"> </label> <label for="address">Address <input type="text" name="address" placeholder="Enter email address"> </label> <label for="contact_no">Contact No <input type="number" name="contact_no" placeholder="Enter your username"> </label> <label for="document"> upload Doc <input type="file" name="document" id="document"> </label> <button type="submit">Submit</button> </form> {% endblock%} -
django.db.utils.IntegrityError: null value in column "session_key" of relation "e_commerce_cart" violates not-null constraint
I'm trying to get a session_key from my React app (front-end) where Django-rest-framework is used for Backend. But it shows server error. Views.py: @api_view(['GET']) def addToCartForSession(request, pk): product = get_object_or_404(Product, pk=pk) mycart, __ = Cart.objects.get_or_create(session_key=request.session.session_key) mycart.product.add(product) return Response({'response':'ok'}) urls.py: path('addToCartForSession/<str:pk>/', views.addToCartForSession, name='addToCartForSession'), When I go to this url directly from browser search bar, it works fine. But if I call this function(addToCartForSession) from my React app, it shows server error like this: django.db.utils.IntegrityError: null value in column "session_key" of relation "e_commerce_cart" violates not-null constraint DETAIL: Failing row contains (54, null, null) in React: addToCart=()=>{ var id = this.props.id var url2 = 'http://127.0.0.1:8000/addToCartForSession/'+id+'/' fetch(url2,{ method:'GET', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': this.csrftoken } }).then(res=>res.json().then(result=>{ if(result.response === 'ok'){ this.props.dispatch({ type: 'itemInCart', }) this.setState({addedToCart: true}) } })) } So, How can I get a session_key from front-end with drf? -
request cart_obj in template tag filter Django
Is it possible to add a cart_obj request in a Django Template filter I currently have in my template tag: @register.filter def existing_product(product): return CartItem.objects.filter(item_id=product.id).exists() and in my template: {% if product|existing_product %} {% endif %} the only problem is that this filter only finds the item_id that is equal to the product.id , I want to be able to add an additional filter that looks for the item_id in the cart_obj. views.py cart_obj, new_obj = Cart.objects.new_or_get(request) basically my template tag would be something like: return CartItem.objects.filter(item_id=product.id, items_cart_id=cart_obj).exists() with the addition of filtering the 'items_cart_id', but I'm not sure how to do this and what to put in the template 'if' condition. Any ideas? Thanks -
How to call the value of a key in JavaScript?
I am learning Django. I have an app name quizes In the models.py section I have this: from django.db import models DIFFICULTY_CHOICES = ( (1, 'easy'), (2, 'intermediate'), (3, 'difficult') ) class Quiz(models.Model): difficulty = models.IntegerField(choices=DIFFICULTY_CHOICES) This is how views.py looks like: from django.shortcuts import render from .models import Quiz from django.views.generic import ListView class QuizListView(ListView): model = Quiz template_name = 'quizes/main.html' def quiz_view(request, pk): quiz = Quiz.objects.get(pk=pk) return render(request, 'quizes/quiz.html', {'obj': quiz}) Now in the main.html I have a button that calls these values and it looks like this: <button type="button" class="btn btn-primary modal-button" data-difficulty="{{obj.difficulty}}" data-bs-toggle="modal" data-bs-target="#quizStartModal"> {{obj.name}} </button> When the user clicks on the button, I would like to display the value of the key in difficulty. the key is fetched by the button using the data-difficulty method. In the JavaScript part, this is what I am doing: const modalBtns = [...document.getElementsByClassName("modal-button")] const modalBody = document.getElementById("modal-body-confirm") modalBtns.forEach(modalBtn=> modalBtn.addEventListener('click', ()=>{ const difficulty = modalBtn.getAttribute('data-difficulty') modalBody.innerHTML = ` <div> difficulty: <b>${difficulty} </div> ` So I am getting the output as 1 for easy, 2 for intermediate and so on. But I want to output the value of those keys instead of those keys themselves. How do I do that? -
Connect create-react-app to django backend without having to run build
I connected my react app that I made with create-react-app to django by passing it in as a template. I followed the steps shown here: https://studygyaan.com/django/django-react-setup-best-project-structure. This works but if I want to try out a full backend server by running manage.py runserver, I have to do npm run build on the frontend app all the time. Is there a way to get it so that I could maybe connect the development components to django instead of the build components? Running the build command always takes a bit of time. -
Django - Can you overwrite the form.as_p or form.as_table methods? Or create your own?
I was wondering if something like this would be possible. I like to display my forms in tables, but not the same as the out of the box .as_table method. I have so far been iterating over each field, and doing it myself. But now that I'm doing my own error displays as well (form.non_field_errors and field.errors), it is a ridiculous amount of code to copy and paste for each form. I just want to be able to do form.as_....., where I can just have it display my own custom way in html, and with my own custom error message styling. Can this be done. Thanks so much! -
Python Django TypeError: 'Module' object is not callable
I am trying to setup my database using dj_database however I am getting the error db_from_env = dj_database_url(conn_max_age=600) TypeError: 'module' object is not callable The code that the traceback is calling is db_from_env = dj_database_url(conn_max_age=600) DATABASE['default'].update(db_from_env) If you have any knowledge on why this would be happening the help would be appreciated. -
Store the uploaded .txt file with newlines in a variable Django
I wanted to store the content of an uploaded .txt file (with newlines) in a variable, so that I could call my other functions on that variable. But I can not find a way to achieve this. I tried all the methods, but it doesn't work Here is the simple code example: Template <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="txt"> <button type="submit" name="encode">Encode</button> </form> View from .algorithms.algo import encoder def encoder(request): context = {'encoded':''} if request.method == 'POST': text = request.FILES['txt'].read() encoded = encoder(text) context['encoded'] = encoded return render(request, 'template.html', context) Also, when I tried to output the file, it showed me some strange text instead of the actual content of the file. Please admins don't close this question, I've surfed all over the internet, but didn't find the answer for my question -
How to use If else in queryset in django
I need to use if else condition for Value1 in my queryset..I have found average for my records in the queryset..I need to apply condition like..If my Value1 is between 90 and 110 then I have to get message as "great" and if its below 90 it must print as "low" and if above 140 it must print as "high" I need to be print this output on my html file Models.py: from django.db import models from django.contrib.auth.models import User class graphinput(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) Month = models.CharField(max_length=30) Value1 = models.IntegerField() Value2 = models.IntegerField() urls.py: def average(request): userid = None if request.user.is_authenticated: userid = request.user.id print(userid) dataset = graphinput.objects.filter(user=userid) \ .values('Value1') a=dataset.aggregate(Sum('Value1')) b=dataset.aggregate(Avg('Value1')) print(a) print(b) return render(request, 'profile.html') -
how to i pass this to django views? for example the url will call generateGamesNumber(), the parameters of the second function come from a form
how to i pass this to django views? for example the url will call generateGamesNumber(), the parameters of the second function come from a form esse é o princípio do que quero def gerarNumerosJogos(): """ valores da lista A """ vetorA = [] """ Gerando números aleatórios no vetor A sem repetição """ x = 0 while True: numAleatorioA = randint(1, 25) if numAleatorioA not in vetorA: vetorA.append(numAleatorioA) x += 1 if x == 15: break vetorA = sorted(vetorA) return vetorA I validate vetorA and return True or False: def validandoParametros(jogoGerado,result,minImpar,maxImpar,minRep,maxRep,minPrimo,maxPrimo,minMold,maxMold, minFibo,maxFibo,minMult,maxMult): *** I have some more code here to validade *** return valida