Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-cms admin url 404 after language change
I recently started learning Django & Django CMS, and was trying to change the language of my website from English to Dutch, I migrated over my pages using Page.objects.filter(languages='en-us').update(languages='en') Title.objects.filter(language='en-us').update(language='en') CMSPlugin.objects.filter(language='en-us').update(language='en') In my settings.py I also changed LANGUAGE_CODE to 'nl' and set my languages and CMS languages as follows LANGUAGES = ( ## Customize this ('nl', 'Nederlands'), ) CMS_LANGUAGES = { ## Customize this 1: [ { 'code': 'nl', 'name': 'Nederlands', 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, }, ], 'default': { 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, }, } This works like a charm for the normal pages, but as soon as I try to open the admin interface I get the following error Request Method: GET Request URL: http://localhost:8000/nl/en/admin/cms/page/?language=en Raised by: cms.views.details Using the URLconf defined in PinManagementSite.urls, Django tried these URL patterns, in this order: sitemap.xml nl/ admin/ nl/ ^cms_login/$ [name='cms_login'] nl/ ^cms_wizard/ nl/ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] nl/ ^$ [name='pages-root'] ^media/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, /nl/en/admin/cms/page/, didn't match any of these. As far as I can see I configured it all correctly, but when I go to the admin pages it tries to route me through /nl/en instead of just /nl/ and I can't figure out why. For completeness … -
Access a field's custom class in Django's ModelForm
I'm working on a ModelForm in Django that uses a Model, which has a custom CharField. When handling form errors I want to show the user valid examples (I thought this shouldn't be part of the raised ValidationError). However, when I try to access the fields using myform.fields by getting the invalid fields and the corresponding error messages using myform.errors.items() type(myform.fields["myfield"]) returns <class 'django.forms.fields.CharField'> instead of my custom MyField. Therefore myform.fields["myfield"].test() raises AttributeError: 'CharField' object has no attribute 'test'. How do I get the correct MyField instance from form.fields? class MyField(models.CharField): pass class MyModel(models.Model): myfield = MyField(max_length=20) class MyForm(forms.ModelForm): class Meta: exclude = tuple() model = MyModel myform = MyForm() print(type(myform.fields["myfield"])) -
please i'm doing a django project and i keep getting this on my browser
AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.8 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: C:\Users\iyiol\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\middleware\clickjacking.py, line 26, in process_response Python Executable: C:\Users\iyiol\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\iyiol\blog', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\python39.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\iyiol\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\Users\iyiol\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1264.0_x64__qbz5n2kfra8p0\lib\site-packages'] Server time: Wed, 28 Apr 2021 16:26:40 +0000 -
Django and get user locations
My question is can I get every user location and display it on map and if I could do it which framework support this with django -
Adding CSS to Django template email
I am using Django rest framework, want to send an email to user. html_message = render_to_string('emails/activate.html', {'email': email, 'role': role}) mail_template = strip_tags(html_message) send_mail( 'Activate your account', mail_template, 'sender', [email], fail_silently=False, ) return Response({'message': 'Activation email sent to ' + email},200) It works and I sent to my HTML file however it doesn't see any CSS and render it very badly. This is an example template I want to send. <!DOCTYPE html> <html lang="en" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <meta charset="utf-8"> <meta name="x-apple-disable-message-reformatting"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="format-detection" content="telephone=no, date=no, address=no, email=no"> <!--[if mso]> <xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml> <style> td,th,div,p,a,h1,h2,h3,h4,h5,h6 {font-family: "Segoe UI", sans-serif; mso-line-height-rule: exactly;} </style> <![endif]--> <title>Verify Email Address</title> <link href="https://fonts.googleapis.com/css?family=Montserrat:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet" media="screen"> <style> .hover-underline:hover { text-decoration: underline !important; } @keyframes spin { to { transform: rotate(360deg); } } @keyframes ping { 75%, 100% { transform: scale(2); opacity: 0; } } @keyframes pulse { 50% { opacity: .5; } } @keyframes bounce { 0%, 100% { transform: translateY(-25%); animation-timing-function: cubic-bezier(0.8, 0, 1, 1); } 50% { transform: none; animation-timing-function: cubic-bezier(0, 0, 0.2, 1); } } @media (max-width: 600px) { .sm-leading-32 { line-height: 32px !important; } .sm-px-24 { padding-left: 24px !important; padding-right: 24px !important; } .sm-py-32 { padding-top: 32px !important; … -
Request can only be served after Gunicorn Worker Timeout and new Worker is booted
I have a Django application in Docker using Gunicorn to run the web server. If I request any URL, say app.com/dashboard, the page loads for 30 seconds. The reason it loads for 30 seconds is because that's how long the Gunicorn web worker to timeout, exit, and boot a new worker with a new pid. This is what shows up in the logs after a request and waiting for the worker to timeout. web_1 | [2021-04-28 17:51:57 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7) web_1 | [2021-04-28 12:51:57 -0500] [7] [INFO] Worker exiting (pid: 7) web_1 | [2021-04-28 17:51:57 +0000] [9] [INFO] Booting worker with pid: 9 Once the new worker is booted, the page is served instantly. Has anyone experienced something similar to this before? -
Result type from cursor.fetchall() is list of tuples, but doc shows tuple of tuples
from django.db import connection conn = connection.cursor() conn.execute("some select query..") print( conn.fetchall() ) This shows that result from cursor.fetchall() is list of tuples, though in docs there is example: >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2"); >>> cursor.fetchall() ((54360982, None), (54360880, None)) That shows that result is not list, but tuple of tuples. Little bit confused, What I'm missing here? Thanks -
Guys help can any one please tell the best framework for web development [closed]
iam so confused about choosing the best and easiest framework for web development . i want expert brother to give me advices as a beginner. And I what is the best RDMS sql or MySQL thanks -
Can't get attribute 'DeprecationDict' on <module 'sklearn.utils.deprecation' from
enter image description here Can't get attribute 'DeprecationDict' on <module 'sklearn.utils.deprecation' from 'C:\Users\xyzxy\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\utils\deprecation.py'> -
DJango use templates from seperrate AWS S3 Bucket
I have a Django server running in an elastic beanstalk environment. I would like to have it render HTML templates pulled from a separate AWS S3 Bucket. I am using the Django-storages library, which lets me use static and media files from the bucket, but I can't figure out how to get it to render templates. The reasoning for doing it like this is that once my site is running, I would like to be able to add these HTML templates without having to redeploy the entire site. Thank you -
Apache httpd and Easy Apache 4 (Installing mod_wsgi for python app)
It's been a while but I am running into an issue and could not find any answers elsewhere. I pay for a dedicated server that is running Easy Apache 4 with Centos 7. I have root access to everything so no limitations. I am in the process of deploying a Python/Django app on the server for a client. When trying to install mod_wsgi it errors out stating it needs the package httpd-mmn. I can install the httpd module using yum but I am worried about conflicts since the server is using Easy Apache 4. Is this a relevant concern? I have a bunch of php sites on my server and I am afraid I'll break it. For the record, I do not want to use the experimental easy apache mod wsgi as it's, well...experimental and a use at your own risk situation. Any thoughts or recommendations would be great. -
Pinax announcement not showing for all users?
I have successfully created an announcement by the superuser account but the announcement won't display for all uses? Why so? -
todo list editable in django admin
i want to create todo editable only by admins in django admin interface. But i don't know how to do it personally for every user. i.e Every user should have a personal todo with checkboxes created in admin panel (the same checkboxes but for each user their own todo) I have created models but this is not what i want class CustomUser(AbstractBaseUser, PermissionsMixin): ... todo = models.ForeignKey(TodoList, null=True, on_delete=models.CASCADE) class TodoList(models.Model): title = models.CharField(max_length=128) class CheckBox(models.Model): title = models.CharField(max_length=128) is_complete = models.BooleanField(default=False) checkbox = models.ForeignKey(TodoList, related_name='todo', default=None, null=True, on_delete=models.CASCADE) -
Error binding parameter 1 - probably unsupported type django
I am trying to take the https path for an image from a csv file, download and store it in a CloudinaryField I tried r.content (it content the byte of the image) but CloudinaryField don't know,tried r.raw too nothing. If there is a best way to do that let me know thanks. this is the model class ArticleUnite(models.Model): libelle = models.CharField(max_length=255) image= CloudinaryField('image', overwrite=True, resource_type="image", transformation={"quality": "auto:eco"}, format="jpg", blank=True, null=True) image2 = CloudinaryField('image', overwrite=True, resource_type="image", transformation={"quality": "auto:eco"}, format="jpg", blank=True, null=True) reference = models.CharField(max_length=255,blank=True, null=True) description = models.CharField(max_length=255,blank=True, null=True) auteur = models.CharField(max_length=255, blank=True, null=True,default="sans auteur") prix_unitaire_article = models.IntegerField(default=1500) is_livre = models.BooleanField(default=False) is_cahier = models.BooleanField(default=False) is_accessoire = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.libelle) this is the code where I download the file then trying to store it in the database but that gives me an error binding #print(df['prix']) for x in df.index: #print(type(df.loc[x,'prix'])) c = float((df.loc[x,'prix'])) #cent = 700 #ct = float(cent) #print(ct) #print(c) if c < 999.0: print("<999") print(c*1000) price = int(c*1000) print(price) print(df.loc[x,'titre']) if df.loc[x,'is_livre']: cat_livr = CatalogueLivre.objects.get(libelle="livres") print(cat_livr) r = requests.get(df.loc[x, 'img'], stream=True) if r.status_code == 200: r.raw.decode_content = True print(type(r)) with tempfile.NamedTemporaryFile(mode="wb") as f: for chunk in r.iter_content(): f.write(chunk) print(f.name) … -
Select only the options that are related to another model in Django
I'm building a student/school app in which a student can belong to only one school and can choose Course options for that School they're in. Currently, I'm doing it the wrong way by having the course field at Student relate do Course, which will of course provide the entire list of courses in my app. What I'd like my app to be able to do is select only from courses that that school have added as their courses. How to do that? class Course(models.Model): name = models.CharField(max_length=32) class School(models.Model): name = models.CharField(max_length=32) courses = models.ManyToManyField(Course) class Student(models.Model): name = models.CharField(max_length=32) school = models.ForeignKey(School, on_delete=models.CASCADE) course = models.ManyToManyField(Course) # change 'Course' for ??? -
How to display content from many-to-one relationship
So I'm going crazy trying to figure out what seems like it should be a dead-simple task. I'm making a portfolio site. It has 2 models, Project and Image. Project contains most of the data for each project, while Image is in a many-to-one relationship to supply Project with a variable number of images per Project. On the homepage, I would like to show each project in its own section, and the images for each project in their respective sections. Currently, I have the projects displayed, and I'm able to display all the images from the database under each section: {% for image in images.all %} <img src="{{ image.image.url }}" alt=""> {% endfor %} I cannot, for the life of me, figure out how to display just the images for each respective section in the template, despite diving through pages of documentation, stack answers, and web posts. I've seen so many examples of how to query a model in this type of relationship from the views/model layers, but none of these seem to work in the template layer. I also don't know how I would perform the query on a different layer and send that through to the template, if … -
Django session variable not working when using AJAX
I have to delete an item and, for that, the user clicks in some "Delete" button in the page and Javascript makes an AJAX request (including the CSRF token in the header of the request) for a Django view to proceed with the deletion. My Django view is processing the request properly and deleting the item. But, in the same view, I do the following: Delete the item Put a message on the request.session['message'] Redirects to the 'list page' The 'list page' view checks if there is some 'message' in request.session and returns it to the page to show in some alert to the user. However, this mechanism is not working for this case, when using AJAX. It is like both the 'delete' view session and the 'list page' session are not the same, because it does not find the 'message' in the request.session. Here are some of the files involved. urls.py: ... urlpatterns = [ path('agenda', views.agenda, name='agenda'), path('<int:reuniao_id>/excluirReuniao', views.excluirReuniao, name='excluirReuniao'), ] views.py: def agenda(request): reunioes = ReuniaoEmpresa.objects.all() if 'message' in request.session: message= request.session['message'] del request.session['message'] else: message= '' context = { 'reunioes' : reunioes, 'message' : message } return render(request, 'agenda/agenda.html', context) def excluirReuniao(request, reuniao_id): reuniao = get_object_or_404(ReuniaoEmpresa, … -
Django - struggling to submit input data to database
I'm having some trouble sending data from a form to my database. The form: <form method="POST"> {% csrf_token %} <div class="banner" style="border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px;"> <h1 style="font-family: 'Baloo Chettan 2', cursive; font-size: 50px;">Title</h1> </div> <div class="colums" style="padding-left: 8px; padding-top: 20px;"> <div class="item"> <label for="i1"> Input One<span>*</span></label> <input id="i1" type="text" name="i1" placeholder="Data point 1" required/> </div> <div class="item"> <label for="i2"> Input Two<span>*</span></label> <input id="i2" type="text" name="i2" placeholder="Data point 2" required/> </div> <div class="item"> <label for="i3">Input Three<span>*</span></label> <input id="i3" type="text" name="i3" placeholder="Data point 3" required/> </div> <div class="item"> <label for="i4">Input Four<span>*</span></label> <input id="i4" type="text" name="i4" placeholder="Data point 4" required/> </div> <div class="btn-block"> <button type="submit" value="CalcData" style="width: 1052px; align-content: center; background-color: #3E828F;">Calculate</button> </div> </form> views.py: def save_data(request): if request.method == 'POST': if request.POST.get('i1') and request.POST.get('i2') and request.POST.get('i3') and request.POST.get('i4'): data=CalcData() data.i1= request.POST.get('i1') data.i2= request.POST.get('i2') data.i3= request.POST.get('i3') data.i4= request.POST.get('i4') data.save() return render(request, 'home.html') else: return render(request,'home.html') models.py: class CalcData(models.Model): i1 = models.DecimalField(max_digits = 100, decimal_places = 5) i2 = models.DecimalField(max_digits = 100, decimal_places = 5) i3 = models.DecimalField(max_digits = 100, decimal_places = 5) i4 = models.DecimalField(max_digits = 100, decimal_places = 5) datetime = models.DateTimeField(default=timezone.now) This POST doesn't end up in my database, so I'm not sure where it's going. I … -
Django rest_framework User Authentication with Android Firebase Auth
I want my users to login in my AndroidApp with Firebase Auth via their email or their Googleaccount. When the User logged in successfully how i authenticate the user in my django rest_framework backend? Can anyone help or found a tutorial to follow?? I really appreciate it. Thanks for help -
Django ModuleNotFoundError: No module named 'multiselectfield'
Just like the heading says. Everything works when I run the server locally but when I deploy i get this error. First time posting and I am very new to Django. I have re installed multiselectfield using pip3 and I have checked the version. I have also run pip freeze to check all the packages and I can see that multiselectfield is there. I checked my migrations and i can see it added to the database. File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'multiselectfield' from django.db import models from django.urls import reverse from phone_field import PhoneField from multiselectfield import MultiSelectField import datetime WEEKS = ( ('1', 'Week 1'), ('2', 'Week 2'), ('3', 'Week 3'), ('4', 'Week 4'), ('5', 'Week … -
TypeError: Cannot read property 'map' of undefined - react js
Please help me! I am stacked with this problem as I am undergoing this React + Django E-commerce project. This happens when I try bringing Redux to the Home Screen. The list of products in my store are unable to load and returns "TypeError: Cannot read property 'map' of undefined". Below are my codes, please help me. Thanks. FIRST CODE import React, { useState, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Row, Col } from "react-bootstrap"; import Product from "../components/Product"; import { listProducts } from "../actions/productActions"; function HomeScreen() { const dispatch = useDispatch(); const productList = useSelector((state) => state.productList); const { error, loading, products } = productList; useEffect(() => { dispatch(listProducts()); }, []); return ( <div> <h1>Latest Products</h1> <Row> {products.map((product) => ( <Col key={product._id} sm={12} md={6} lg={4} xl={3}> <Product product={product} /> </Col> ))} </Row> </div> ); } export default HomeScreen; SECOND CODE import axios from 'axios' import { PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_LIST_FAIL } from '../constants/productConstants' export const listProducts = () => async (dispatch) => { try{ dispatch({ type: PRODUCT_LIST_REQUEST}) const { data } = await axios.get('/api/products/') dispatch({ type:PRODUCT_LIST_SUCCESS, payload: data }) }catch(error){ dispatch({ type:PRODUCT_LIST_FAIL, payload:error.response && error.response.data.message ? error.response.data.message : error.message, }) } } Screenshot … -
how do I create a regex for this in urls.py?
I want to create a regex that matches urls like this filmslist?name=allaboutmymother?director=pedroalmodovar in urlpatterns, I've put this: path('api/filmslist\?name=?P<name>(.*)\?director=?P<director>(.*)', views.filmslist) but it doesn't match. Thanks in advance -
Http redirects to https even though on free dyno
For some reason, even though I'm using the free dyno, my website still redirects http to https. This is what I want to happen, but I just don't understand why it is, since doesn't this only work for paid dynos? (I'm using Django and followed this guide to do the redirecting) Thank you. -
Django join sqlite
Hi fellow devs i have 3 simple tables which i want to retrive in one list as single objects and i have no clue how to start it. My models are: class Person(models.Model): name= models.CharField(max_length=50) surname= models.CharField(max_length=50) class Phone(models.Model): person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE) phone= models.CharField(max_length=50) class Email(models.Model): person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE) email = models.EmailField() -
'NoneType' object is not iterable problem solving
I want to show a list of question on my quiz.html templates... Here is my models.py from django.db import models # Create your models here. DIFF_CHOICE = ( ('easy','easy'), ('medium','medium'), ('hard','hard'), ) class Quiz(models.Model): name = models.CharField(max_length=120) topic = models.CharField(max_length=120) number_of_question = models.IntegerField() time = models.IntegerField(help_text="Duration in Minutes") required_score_to_pass = models.IntegerField(help_text="Required Score to Pass in %") difficulty = models.CharField(max_length=6,choices=DIFF_CHOICE) def __str__(self): return f"{self.name}-{self.topic}" def get_questions(self): self.question_set.all()[:self.number_of_question] class Meta: verbose_name_plural = 'Quizes' Here is my views.py def quiz_data_view(request,pk): quiz = Quiz.objects.get(pk=pk) questions = [] for q in quiz.get_questions(): answers = [] for a in q.get_answers(): answers.append(a.text) questions.append({str(q):answers}) return JsonResponse({ 'data' : questions, 'time' : quiz.time, }) and here is my quiz.html....and here i want to show my question list {% extends "base.html" %} {% load static %} {% block scripts %} <script src="{% static 'quizes/quiz.js' %}" defer></script> {% endblock scripts %} {% block title %} {{obj.name}} {% endblock title %} {% block content %} {{obj.name}} <hr> <form id ="quiz-form" class="mt-3 mb-3"> {% csrf_token %} <div id="quiz-box"></div> <button type="submit" class="btn btn-primary mt-3">Save </button> </form> {% endblock content %} Here is my js file...in my js file i used ajax... const url = window.location.href const quizBox = document.getElementById('quiz-box') let data $.ajax({ type: 'GET', …