Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; you have 0.10.1. error whille using mysql in dajngo
I am using dajngo 3.1.0 and i get this error when i use mysql as database on deploy server. My server is apache server and uses Cpanel. I have tried installing mysqlclient and PyMySQL and adding below code to __init__.py file. import pymysql pymysql.version_info = (1, 3, 13, "final", 0) pymysql.install_as_MySQLdb() -
how to sum in django model fields
I have two models here one is contains subject info and another one course info, i want to sum how many credits(total) have in this course,to show in template. i have tried but didn't work. thank you so much class Course(models.Model): name = models.CharField(max_length=200, unique=True) prefix = models.CharField(max_length=20) code = models.CharField(max_length=20) subject = models.ManyToManyField('Subject', related_name='subject_list', blank=True) def tota_credit(self): total = 0 for cred in self.subject_set.all(): total += cred.credit return total # doesn't work :( def __str__(self): return self.name another model class Subject(models.Model): name = models.CharField(max_length=50) code = models.PositiveIntegerField(unique=True) credit = models.IntegerField(blank=True) def __str__(self): return self.name views.py class Course_detail(generic.DetailView): model = Course template_name = 'course_detail.html' context_object_name = 'queryset' def get_context_data(self, **kwargs): self.profile = Student.objects.all() context = super().get_context_data(**kwargs) context['profile'] = self.profile return context -
how to fix Error during template rendering
enter code here enter code here widget_tweaks' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz 1 {% extends "poll/base.html" %} 2 {% load widget_tweaks %} Blockquote -
Django - Automatic task performace at specific time
My app consists of posts with upvote counter. I would like to set automatic task for Django to zero upvote counter for each post at midnight. What is the best way to achieve it? Is there any built-in or external libraries for such purposes? -
Graphviz django probelm
I'm a Python Developer currently in the process of making a family website. I am developing a website using the Django framework in Python. I have planned to make an interactive family tree using the Graphviz package in Django. I am able to create a .SVG graph for the family tree from the Python command terminal directly. But when I integrate Grapgviz with Django using django-extensions, it is NOT working. Without implementing this family tree, my website can not be complete. Has anyone in the users group faced similar problems? Any help in this regard will be highly appreciated -
Error Failed to import test module: tests.test_models prints when using python tests in Pycharm
I am having an issue which throws the following error when I go to run tests in pycharm: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. It appears the issue is with pycharm as I just ran ./manage.py test and the tests executed successfully. I have sifted through SO and have tried everything from modifying imports, checking INSTALLED_APPS, and ensuring the configurations are ok for the Python unittests. Nothing Project Hierarchy Configurations which I have set using pycharm are: Script path:/MainFolder/MainProjects/project1-backend/tests Environment Variables: PYTHONUNBUFFERED=1; DJANGO_SETTINGS_MODULE=project1backend.settings note the folder to which this belongs to is project1backend not project1-backend Python interpreter: Python 3.8(MainFolder) ~/MainFolder/MainProjects/bin/python Working Directory:/Users/myname/MainFolder/MainProjects/project1-backend Add contentroots to PYTHONPATH: notselected Add source roots to PYTHONPATH: selected Error Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/case.py", line 60, in testPartExecutor yield File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/case.py", line 676, in run self._callTestMethod(testMethod) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/case.py", line 633, in _callTestMethod method() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 34, in testFailure raise self._exception ImportError: Failed to import test module: tests.test_models Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/myname/MainFolder/MainProjects/project1-backend/tests/test_models.py", line 2, in … -
Django compilemessages not discovering 3rd party apps
For some reason, Django's compilemessages is not discovering the locale folders of the 3rd party apps I have installed. Here is my basic project structure: project - setup.py - requirements.txt - virtual environment - project_name - apps - manage.py - translation - project_name - settings The locale_paths are set to LOCALE_PATHS = os.getenv('LOCALE_PATHS', BASE_DIR + '/translation'), When running manage.py makemessages and compilemessages on my localhost, from the base directory where manage.py is located, it will only discover the translation folder, but moving one level up to the project folder and running project_name/manage.py compilemessages will discover and compile the translation folder as well as any installed 3rd party apps' locale folders. This would be fine, if slightly strange, if it worked consistently, but this solution does not hold when we run the build script to deploy to a server. Even when moving up a level, compilemessages will only discover the translation folder with our custom translations and not any 3rd party apps. Does anyone know what could be causing this problem? -
Readability Django app, issues sending results to model
Im trying to analyze a text provided by the user via a form input, that text is saved on a model, and then analyze it to finally show the results on a results.html, and save the info on the results model. --------- VIEWS.PY ---------------------- from django.shortcuts import render from django.http import HttpResponseRedirect from .models import TestedText, TestResults from textatistic import Textatistic import time # Create your views here. def readtest(request): return render( request, 'test.html' ) def addtext(request): a = TestedText(title=request.POST['title'], content=request.POST['content']) a.save() def result(request): text = addtext(content) s = Textatistic(text) r = TestResults( Flesch = (s.flesch_score, request.POST['Flesch']), DaleChall = (s.dalechall_score, request.POST['DaleChall']), Fleschkincaid = (s.fleschkincaid_score, request.POST['Fleschkincaid']), gunningfog = (s.gunningfog_score, request.POST['gunningfog']), smog = (s.smog_score, request.POST['gunningfog']) ) r.save() return render(request, 'results.html') ----------- MODEL.PY --------------------------------------- from django.db import models # Create your models here. class TestedText(models.Model): title = models.TextField(max_length=50, default=None) content = models.TextField(max_length=500, default=None) class TestResults(models.Model): character_count = models.IntegerField(default=None) DaleChall_list = models.IntegerField(default=None) polysylables = models.IntegerField(default=None) sentences = models.IntegerField(default=None) sybles = models.IntegerField(default=None) words = models.IntegerField(default=None) Flesch = models.IntegerField(default=None) DaleChall = models.IntegerField(default=None) Fleschkincaid = models.IntegerField(default=None) gunningfog = models.IntegerField(default=None) smog = models.IntegerField(default=None) -
How do I 'Move' a whole Django project 'down' a URL prefix i.e. (localhost ---> localhost/APP_NAME/)?
I'm aware I'm probably not using the correct terminology, but when i developed my Django project it would sit on the root URL i.e. http://localhost whereas now I'm moving it into production it needs to sit - http://localhost/APP_NAME This is the structure of my project APP_NAME ----APP_NAME ----SECOND_APP I've tried the following, from APP_NAME/urls.py to get to SECOND_APP - ORIGINAL ATTEMPT path('', include('second_app.urls')) --to--> url(r'^APP_NAME/', include('second_app.urls')), but I keep getting a 404 error, so it's obviously not working! In SECOND_APP/urls - path('', login_required(views.home), name='SECOND_APP'), Where am I going wrong here? -
Is it possible to create the database prior to django running any migration commands?
I spun up a MySQL database but I've noticed I have to manually connect to it and run CREATE {DB} and then run my migrations. If I don't the database can't be found. Does django provide some form of utility that lets me run CREATE {DB}? -
Not getting reponse after POST request through axios in react.js
I am creating register and login page in react.js, but after sending post request from axios, I am not able to get back the response, and the .then function does not executes. Also the POST requests works correctly only some of the times(data is added to database). And an error occurs in the backend, during the POST request - Exception occurred during processing of request from ('127.0.0.1', 25074) Traceback (most recent call last): File "c:\python\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\python\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\python\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\MUKUND\.virtualenvs\react-IVhYBaaI\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\MUKUND\.virtualenvs\react-IVhYBaaI\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\python\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine import React, { Component } from 'react'; import axios from "axios"; class Register extends Component { constructor(props) { super(props); this.state = { activeItem: { username:"", email: "", password: "" } }; } handleSubmit = (event) => { alert(this.state.activeItem.email) //console.log("cred = ") //console.log(cred) var data = { username: this.state.activeItem.username, email: this.state.activeItem.email, password: this.state.activeItem.password } axios .post("http://localhost:8000/api/register/", data) .then(res => { alert("registered") console.log("response = ",res) }) … -
Django project problems after upgrading to python 3.8
I developed a Django webapp project using Django 2.2.1 in python 3.7.2 in a pipenv version 2018.11.26 virtual environment in MacBook Air. After an unintentional update to python 3.8 using brew upgrade , there were problems to work on my webapp and launching it. I installed pipenv pip3 install pipenv , and copied and pasted project folder, and used it with an another name, deleted Pipfiles, and ran pipenv install , but there were error: I googled this but found a similar problem but nothing as a solution. Would you please look at these messages and show my correct way to launch my django webapp project? -
How to make inner join on parent field in Django
For data models shown as below, given the product_name, how shall I do a query with Django ORM to get objects containing "distance, city name, price" sorted by distance, price? ### models.py ### class Province(models.Model): name = models.CharField() class City(models.Model): name = models.CharField() distance = models.IntegerField() province = models.ForeignKey(Province) class Price(models.Model): product_name = models.CharField() province = models.ForeignKey(Province) price = models.IntegerField() Same price apply to all cities within a province -
django rest Error: Missing required positional argument in creating objects
I have these serializer classes and I'm trying to create doctor and user together class UserSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = '__all__' extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): print(validated_data) user = User( email=self.validated_data['email'], first_name = self.validated_data['first_name'], last_name=self.validated_data['last_name'], phone_number=self.validated_data['phone_number'], social_id=self.validated_data['social_id'], gender=self.validated_data['gender'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords do not match.'}) user.set_password(password) user.save() return user class DoctorSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Doctor fields = '__all__' def create(self, validated_data): user_data = validated_data.pop('user') print(user_data) user = UserSerializer.create(**user_data) doctor = Doctor( user=user, mc_code=self.validated_data['mc_code'] ) doctor.save() return doctor and I send these json data to these serializers { "user": { "email": "test@test.com", "first_name": "john", "last_name": "doe", "phone_number": "12345678901", "social_id": "1234567890", "password": "password", "password2": "password" }, "mc_code": 123448 } But it gives me this error: Exception Type: TypeError Exception Value: create() got an unexpected keyword argument 'password2' this create() is the create function for UserSerializer I read docs but I couldn't solve the problem. What am I doing wrong? view function just in case @api_view(['POST', ]) @permission_classes(()) def doctor_registration_view(request): if request.method == 'POST': serializer = DoctorSerializer(data=request.data) data = {} if serializer.is_valid(): doctor = serializer.save() else: … -
Django order events by calendar date instead of date posted
I have a newsletter home page that has an events calendar on the side. Sometimes events come up and I need to insert them between two other events. Is there a way I can do this automatically in Django? I know how to order by date posted - for things like blog posts - but I don't see anywhere in the docs how to do this by actual calendar date. This is the code from my view: class HomeView(ListView): model = NewsLetter template_name = 'home.html' def events(self): return Event.objects.all() class PastEventView(ListView): model = PastEvent template_name = 'events.html' ordering = ['event_date'] The past events is alright, but I don't know how to code the order by for the events function under the HomeView class. Any help here would be greatly appreciated. -
how to redirect to a page with pk
i have this function def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/profile') else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'store/edit_profile.html', args) i want it to redirect to this function def view_profile(request, pk): data = cartData(request) cartItems = data['cartItems'] shippingAddress = ShippingAddress.objects.get(id=pk) # orderItem = OrderItem.objects.get(id=pk) args = {'user': request.user, 'cartItems': cartItems, 'shippingAddress': shippingAddress} # 'orderItem': orderItem return render(request, 'store/profile.html', args) the urls path('profile/<str:pk>/', views.view_profile, name="view_profile"), path('profile/edit', views.edit_profile, name='edit_profile'), i want the first function to redirect to the second but i got 'Page not found' i know the problem with the pk. so i want it to redirect to profile/id. is there a way to solve it? -
How can i write this if statement?
i have some problems with my if statement. {% for user in users %} {% if tournament.tournament_name != user.user_tournament %} {% else %} <p>{{ user.user_first_name }} {{ user.user_last_name }}</p> {% endif %} {% endfor %} class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) tournament_info = models.TextField(max_length=10000) def __str__(self): return self.tournament_name I would like to write something in the form of an entry to a particular tournament where the user after clicking on the "join" button is moved to a sheet where the user is asked to enter their name and choose which tournament they want to join. Is it possible to write a conditional instruction that checks if the name of a given tournament is equal to the name of the tournament that the user has chosen and using it to list the users assigned to the given tournament. -
Django post request looping on same route when using more than 1 replica on Kubernetes cluster
I'm new to kubernetes and was trying to deploy a django app in a shared kubernetes cluster on Kubesail. I was pulling a docker image to run as a container on the cluster. Everything worked as expected until I increased the number of replicas to 2 instead of 1. When I made it 2, my post requests started looping. Meaning, If I'm trying to login into my application, I was again taken back to the login page despite entering the right credentials. Also no user session was created making my app completely inaccessible since all the routes require login. When I made the replicas revert back to 1, everything was normal and app was functioning as expected. Can someone explain why is it so? or can maybe tell what I did wrong? -
How to connect to external MySQL without using models.py in Django
I have my report dashboard that I'm developing using Django and I want to connect it to my MySQL database without using models.py or migrations. Basically, here's what I've done so far. views.py import configparser config = configparser.ConfigParser() config.read('db.ini') def getConnection(): host = config['ord']['host'] port = config['ord']['port'] database = config['ord']['database'] password = config['ord']['password'] user = config['ord']['user'] connection = pymssql.connect(host=host, user=user, password=password, database=database) cursor = connection.cursor() print("Connection Succesfull") return cursor def fill_weight(request): try: sql = u """ SELECT * FROM fill_weight; """ sql =sql.encode('utf-8') cursor.execute(sql) cursor.fetchall() db.ini [oof_ord] host = localhost port = 3306 database = xxxxxxxxxxx user = xxxxxxxxxxx password = xxxxxxxxxxx default-character-set = utf8 The reason why I want to do this is because I don't have the official database that I'm going to use for this system and I want to easily access it by putting it's database credentials to my db.ini and access it to show the data without doing any migrations. Is there anyone that can help me ? -
CSRF verification fails when uploading file in admin inline
In django 2.2.12 I have a simple TabularInline, where I add comments to my main model. As soon as I try to add a file to my comment I get a CSRF error. class Material(models.Model): name= models.CharField(max_length=80) class Comment(BaseModel): material = models.ForeignKey(Material, on_delete=models.SET_NULL, blank=True,null=True,related_name = "comments") comment = models.TextField(null=True, blank=True) document = models.FileField(upload_to='docs/', blank=True, null=True) Admin.py class CommTab(admin.TabularInline): model = Comment extra = 0 class MatAdmin(admin.ModelAdmin): inlines = (CommTab,) If I save it without a file there is no problem. The source code of the page seems to be fine (csrf token is in the form). -
URL Tags to link from another installed app in Django
Running Django 3.0.7 on Python 3.8 I am logging into a Django project in an app: SupplierPortal and am trying to link a Nav button to CashMgmnt. Here is that href in base.py: <li ><a href="{% url 'CashMgmt:customer-detail' pk=id %}">Cash Management</a></li> Here is the urls.py: urlpatterns = [ path('customer/customerdetail/<int:pk>', views.AppCustomerCstDetailView.as_view(), name='customer-detail'), ] Here is the views.py: class AppCustomerCstDetailView(generic.DetailView): model = AppCustomerCst paginate_by = 10 def get_absolute_url(self): return reverse('customer-detail', args=[str(self.id)]) When loading I'm getting the following error: Reverse for 'customer-detail' with no arguments not found. 1 pattern(s) tried: ['customer/customerdetail/(?P<pk>[0-9]+)$'] -
Django-Plotly-Dash multiple users/browser tabs causing mixing of data on plots
I am creating an app in Django that uses Dash and Plotly components. To test some functionality, I dumbed the app down to a page that has a dropdown where a user chooses “latitude” or “longitude” and then the script calls an ISS location API that plots the latitude or longitude of the ISS depending on what the user chooses. This is a live plot that gets updated using dcc.Interval every 3 seconds. This works great, until I open two instances of the app in my browser. If the first browser tab has “latitude” and the second browser tab has “longitude” the plots will mix the data and bounce back and forth plotting both values. Has anybody ever run into this? I have been playing with clientside callbacks and some other things but I am not sure how to get it to not have this bug anymore. I will include the code and what the plot behavior looks like below. data = deque(maxlen=30) timeStamp = deque(maxlen=30) liveOut = DjangoDash("LiveOutput") liveOut.layout = html.Div([ dcc.Dropdown(id='graph-indicator', style={'display': 'block'}, options=[ {'label':"latitude", 'value':"latitude"}, {'label':"longitude", 'value':"longitude"}, ],), dcc.Graph(id='graph', style={'width':'49%', 'display': 'inline-block'}), html.Div(style={'width':'1%', 'display': 'inline-block'}), html.Div(id='hidden-div', style={'display':'none'}), dcc.Interval( id='graph-update', interval=3000, n_intervals=0 ), ]) @liveOut.callback( Output('hidden-div','value'), [Input('graph-indicator','value')],) def … -
Deploy a Django project to AWS EB using Docker and nginx
Currently, I try to deploy a Django project to AWS EB but I'm facing a lot of problems. I could dockerize the project and deploy it on the AWS elastic beanstalk. But when I try to access the site I always see: 502 Bad Gateway. Locally, the project runs smoothly. I am not really into nginx and I have no idea how to solve this problem. This is my project structure: Project structure This is my Dockerfile: # Creating image based on official python3 image FROM python:3 MAINTAINER Jaron Bardenhagen # Sets dumping log messages directly to stream instead of buffering ENV PYTHONUNBUFFERED 1 # Creating and putting configurations RUN mkdir /config ADD config/app /config/ # Installing all python dependencies RUN pip install -r /config/requirements.txt # Open port 8000 to outside world EXPOSE 8000 # When container starts, this script will be executed. # Note that it is NOT executed during building CMD ["sh", "/config/on-container-start.sh"] # Creating and putting application inside container # and setting it to working directory (meaning it is going to be default) RUN mkdir /app WORKDIR /app ADD app /app/ This is my docker-compose file: # File structure version version: '3' services: db: image: postgres environment: … -
Can't run django server in ATOM
I'm trying to run server in atom but I can't! https://i.stack.imgur.com/1OnMY.png -
Django rest framework, migrating from session authentication to token authentication
So this is a generic question, in our django project we have been using session authentication all along. Now for a few reasons, we are planning to move to token based authentication for our project. What are all the things that i should consider while doing this move? I know that we have to add rest_framework.authtoken to our installed apps and change the authentication in REST_FRAMEWORK in settings file. Are there any other steps that i should consider while making this move