Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get list of all fields corresponding to a model saved in content type framework in django
I have this requirement in which I have to show two dropdown fields on Django admin page. The first field will be the dropdown of all the table names available in my project, and the second field will be a dropdown all the available fields of the table selected in 1st dropdown. The second field will be dynamic based on the selection of the first dropdown. I am planning to handle this by overriding change_form_template. Now, I can show the dropdown of table names by fetching them through content type Django model, But not able to fetch corresponding fields as content type model save the model name as a string. So is there any way not necessarily using Content-Type to achieve such a requirement? Any help around that will be highly appreciated. Thank you. -
Saving many-to-many fields from the excel file in Django
I'm trying to save the student data from an excel file. I'm reading the excel file row-wise and mapping the data to the model fields. Now the problem is that there is a foreign key and a many-to-many field which I don't know how to save. Though I figured out the foreign key part but not able to solve the second part. Here are the files. views.py def fileUpload(request): if request.method=="POST": form= UserDataUploadView(request.POST, request.FILES) try: excel_file= request.FILES["excel_file"] except MultiValueDictKeyError: # In case the user uploads nothing return redirect('failure_page') # Checking the extension of the file if str(excel_file).endswith('.xls'): data= xls_get(excel_file, column_limit=10) elif str(excel_file).endswith('.xlsx'): data= xlsx_get(excel_file, column_limit=10) else: return redirect('failure_page') studentData= data["Sheet1"] print("Real Data", studentData) # reading the sheet row-wise a_list= studentData list_iterator= iter(a_list) next(list_iterator) for detail in list_iterator: # To find out empty cells for data in detail: if data==" ": print('A field is empty') return redirect('user_upload') print("DATA: ", detail) user=User.objects.create( firstName = detail[6], lastName = detail[7], password = detail[8], username = detail[9], ) # instance=user.save(commit=false) # Student.batch.add(detail[0]) student=Student.objects.create( user = user, email = detail[1], rs_id = detail[2], dob = detail[3], address = detail[4], age = detail[5], ) student.save() return render(request, 'classroom/admin/success_page.html', {'excel_data':studentData}) # iterating over the rows and # getting … -
I cannot understand that how to change font family in forms in django
how do I change the font family in the content portion ? -
Django Error Module 'Whitenoise' not found
I'm using whitenoise to deploy static files in prod, so according to whitenoise's docs, it's recommended to use it in development too. So I followed the documentation and added the following to my settings.py file: INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', ...other ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ...other ] But when I run the server using python manage.py runserver 0.0.0.0:8000, I get the error ModuleNotFoundError: No module named 'whitenoise' Full stack trace: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/path/to/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/path/to/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/path/to/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/path/to/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/path/to/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/path/to/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/path/to/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/path/to/venv/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'whitenoise' I checked using pip freeze … -
Migrations Error = No changes detected in app 'myapp'
I have included 'myapp' at myproj/setting.py INSTALLED APP, and I have tried to add some model and stuff but it still return the error No changes detected in app 'myapp', what should I do????? this is the step that lead to the error hostname $ python pip install django hostname $ django-admin startproject myproj hostname $ cd myproj hostname $ python manage.py startapp myapp hostname $ python manage.py makemigrations myapp -
django @login_required decorator for a last_name, only users with last_name == 'kitchen' entry
Is there a decorator in django similar to @login_required that also tests if the user has lastname == kitchen? Thanks -
Django + Apache(httpd): Error loading MySQLdb module
I have tried to figure this out for a day now and cannot seem to make any headway. I'm getting the following Apache error: [wsgi:error] django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. [wsgi:error] Did you install mysqlclient? [wsgi:error] [remote 10.10.10.90:35990] mod_wsgi (pid=14165): Target WSGI script '/var/www/vhosts/project_vision/web/web/wsgi.py' does not contain WSGI application 'application'. File structure is this (web is the name of the Django project within the larger Project_vision project): /var/www/vhosts/project_vision |- venv/ |- web/ |- static |- templates |- vision_web |- models/ |- migrations/ |- ... |- web |- settings.py |- wsgi.py |- ... /var/www/vhosts/project_vision/web/web/wsgi.py import os import signal import sys import time import traceback from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/vhosts/project_vision') sys.path.append('/var/www/vhosts/project_vision/web') sys.path.append('/var/www/vhosts/project_vision/venv') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web.settings') try: application = get_wsgi_application() except Exception: # Error loading applications if 'mod_wsgi' in sys.modules: traceback.print_exc() os.kill(os.getpid(), signal.SIGINT) time.sleep(2.5) /etc/httpd/conf.d/vision.conf <VirtualHost *:80> ServerName my_project_vision.com DocumentRoot /var/www/vhosts/project_vision/web Alias /static/ /var/www/vhosts/project_vision/web/static/ <Directory /var/www/vhosts/project_vision/web/static> Require all granted </Directory> WSGIDaemonProcess my_project_vision.com \ processes=2 threads=15 display-name=%{GROUP} \ python-home=/var/www/vhosts/project_vision/venv \ python-path=/var/www/vhosts/project_vision/web WSGIProcessGroup my_project_vision.com WSGIApplicationGroup %{GLOBAL} # Insert the full path to the wsgi.py-file here WSGIScriptAlias / /var/www/vhosts/project_vision/web/web/wsgi.py <Directory /var/www/vhosts/project_vision> AllowOverride all Require all granted Options FollowSymlinks </Directory> </VirtualHost> Where in the world am I going wrong? It must be something minor but important... -
how to share DB connection across threads in Django out of standard request/response thread
Thanks for reading this. I understand that in the Django request/response framework, connection is controlled by Django. Such as closing connection basing on the CONN_MAX_AGE. our project has backend and GUI. GUI part is ok, connection is handled by Django. The backend uses too many connections. As Django will create new connection for each new thread. and never close it. So I am trying to share db connection across threads in backend. I create a global connection(with allow_thread_sharing=True) and guard it with Threading.RLock. The issue now is when to acquire and release this lock. I still get SEGMENTATION fault with acqure/release around get_queryset, execute_sql: Manager.get_queryset = share_conn_decorator(Manager.get_queryset) SQLCompiler.execute_sql = share_conn_decorator(SQLCompiler.execute_sql) SQLUpdateCompiler.execute_sql = share_conn_decorator(SQLUpdateCompiler.execute_sql) SQLInsertCompiler.execute_sql = share_conn_decorator(SQLInsertCompiler.execute_sql) Can you suggest that whether sharing db connection is doable? if so when/where should I lock the connection? Thanks -
Starting with Django: can't raise 404 or find the questions
i'm totally new to Django and i'm doing the tutorial. My issue is that I cannot find the questions that I've created, when i go to the URL http://127.0.0.1:8000/polls/1/ it won't show neither the question nor the 404 error that I coded. These are the relevant files (please say so if I'm missing one) views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] models.py from django.db import models import datetime from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Thanks in advance! -
Want to execute a function after keyboard interrupt(CTRL+C) in django?
Basically I write data to file after processing using python script in django but I want to call that write to file function even after I press press keyboard interrupt. How to achieve this as on pressing ctrl+c django closes -
Django Rest universal linking -- json file path not found
I have a Django REST framework that is integrating universal app linking for iOS https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html The main point is that I have a json file called "apple-app-site-association" in my root directory (as instructed) that controls the redirect. When I put this through an aasa validator https://branch.io/resources/aasa-validator/ it returns a 400. My server logs show Not Found: /.well-known/apple-app-site-association I can't find any resources doing this with django, so I'm a little stuck on what to try or do next. -
expecting one result, but django .filter() returns multiple
I am chaining the filters and expecting one result to return -because according to the conditions result should be one- but it returns related rows as well... // taking the ID from the parent table. pid = Budgets.objects.filter(project_name=direct["project_name"]).values("id")[0]["id"] // checking the row exist or not. exists = Advertisements.objects.filter(budgets_id=pid).filter(saved_date="2020-02").filter(ad_kind="gsn").exists() if exists == True: // if it's exist then return it with the according criterias value = Advertisements.objects.filter(budgets_id=pid).filter(saved_date="2020-02").filter(ad_kind="gsn").values_list("ad_kind", flat=True)[0] print(value) // the problem occurs here. normally filter(ad_kind="gsn") should filter it till gsn left. But it doesn't. And it return other kinds too... Any idea what can be causing this problem? -
How to POST on Postman without having to change DEBUG = True to false in Django settings?
Getting an issue when running "python3 manage.py runserver" link -
Which URL does CreateView in Django redirects to when the success_url is not provided?
I am learning Class-based views in Django(inheriting from generic views) and stumbled upon a code for CreateView which did not provide any success_url. But after creation, I am getting redirected to DetailView (i.e, the page describing a particular object, in this case the object just created). I am not sure how this redirection is happening. Can anyone help me with this? # ...other imports... # ... from django.views.generic.edit import CreateView #... other views... class TweetCreateView(FormUserNeededMixin, CreateView): form_class = TweetModelForm template_name = "tweets/create_view.html" class TweetDetailView(DetailView): model = Tweet #...other views... Thanks. -
Asking user to select a local directory
I've been looking everywhere in the hope of finding a good implementation of allowing a user to select a local directory for, in this case, selecting where to download files. The best method I found was through tkinter with the filedialog method but I thought this couldn't be the best approach. -
Error in Django ModelForm. Select a valid choice. That choice is not one of the valid choices
I have a Model and a ModelForm. The ModelForm has a dependent dropdown list implemented with JQuery. The category dropdown changes accordingly each time a choice from the gender dropdown is selected (Done with JQuery). Whenever I try to save the ModelForm in my views, I get an error saying that the choice that I have selected is not valid. Does it have to do with the choices/options to the category dropdown being added after a choice from the gender dropdown has been selected? Does it cause some conflict with the default empty two-tuple of the category field? The errors occur on the category field. In models.py, GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female'), ] class Person(models.Model): name = models.CharField(max_length=50, unique=True) gender = models.CharField(max_length=7, choices=GENDER_CHOICES) category = models.CharField(max_length=20, choices=[('', ''), ]) In forms.py, class PersonForm(ModelForm): class Meta: model = Person fields = [ 'name', 'gender', 'category', ] In views.py, def personform_page(request): context = {} if request.method == 'POST': personform = PersonForm(request.POST) if personform.is_valid(): personform.save() return redirect('personform_page') context['personform'] = personform else: personform = PersonForm() context['personform'] = personform context['male_categories'] = MALE_CATEGORIES context['female_categories'] = FEMALE_CATEGORIES return render(request, 'app1/personform_page.html', context=context) In app1/personform_page.html, <form class="form-class" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in … -
Import Error when running task on python anywhere
I am trying to create a task to run daily using python anywhere and keep getting the error: Traceback (most recent call last): File "/home/10Cents/10-cents-app/Django/10cents/webdesign/cent/tasks.py", line 3, in from . import views ImportError: attempted relative import with no known parent package file structure -
Too much view logic in django template
i am currently building an e commerce platform. I am working on the Order part of the app which creates an order after two people agree to enter into a transaction. Issue is that the order model has a lot of fields and as i want my template to look different depending on many values such as; has payment been made? Has the product been shipped? has a dispute been raised? I also want the page to look different depending on if its the buyer viewing the page or the seller. Obviously if the seller is viewing the page i dont want him to see the checkout button, or the buyer to see the mark item as posted etc. So i currently have this working however there is a LOT of if statements in my template to do so and the view has a lot of logic as well. My question is, is there a better (more efficient and faster) way to do this as i know most logic should be kept out of the template. If this won't slow my site down then that is acceptable but if it is then i really need to change it. The Model … -
type object 'User' has no attribute 'get_user_by_token' in flask python
I am trying to combine Flask-User and Flask-Login but when I try logging in I get this error: File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 2446, in wsgi_app response = self.full_dispatch_request() File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1820, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\_compat.py", line 39, in reraise raise value File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request rv = self.dispatch_request() File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1935, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Users\asus\Desktop\group-17-electronic-voting-system\vote\routes.py", line 12, in home return render_template('home.html',title='Home') File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\templating.py", line 136, in render_template ctx.app.update_template_context(context) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 838, in update_template_context context.update(func()) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask_login\utils.py", line 379, in _user_context_processor return dict(current_user=_get_user()) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask_login\utils.py", line 346, in _get_user current_app.login_manager._load_user() File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask_login\login_manager.py", line 318, in _load_user user = self._user_callback(user_id) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask_user\user_manager.py", line 130, in load_user_by_user_token user = self.db_manager.UserClass.get_user_by_token(user_token) AttributeError: type object 'User' has no attribute 'get_user_by_token' Any help would be appreciated. -
django.db.utils.OperationalError: could not connect to server: Con nection refused
I have dockerized aplication build in Django and using as database postgis but when I'm trying to run containers I'm getting error "django.db.utils.OperationalError: could not connect to server" There are logs from Docker Terminal: $ docker-compose up Recreating database ... done Recreating boss_support_web_1 ... done Attaching to boss_support_postgres_1, boss_support_web_1 postgres_1 | Add rule to pg_hba: 0.0.0.0/0 postgres_1 | Add rule to pg_hba: replication replicator postgres_1 | Setup master database postgres_1 | 2020-03-19 00:04:22.426 UTC [28] LOG: listening on IPv4 address " 127.0.0.1", port 5432 postgres_1 | 2020-03-19 00:04:22.428 UTC [28] LOG: listening on Unix socket "/ var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2020-03-19 00:04:22.451 UTC [35] LOG: database system was interru pted; last known up at 2020-03-18 23:43:38 UTC postgres_1 | 2020-03-19 00:04:22.486 UTC [40] postgres@postgres FATAL: the dat abase system is starting up postgres_1 | psql: FATAL: the database system is starting up postgres_1 | 2020-03-19 00:04:22.594 UTC [35] LOG: database system was not pro perly shut down; automatic recovery in progress postgres_1 | 2020-03-19 00:04:22.596 UTC [35] LOG: redo starts at 0/40FDE210 postgres_1 | 2020-03-19 00:04:22.597 UTC [35] LOG: invalid record length at 0/ 40FDE248: wanted 24, got 0 postgres_1 | 2020-03-19 00:04:22.597 UTC [35] LOG: redo done at 0/40FDE210 postgres_1 … -
Why is my Django serializer telling me an attribute doesn't exist when I see it defined in my model?
I'm using Python 3.7 and the Django rest framework to serialize some models into JSOn data. I have this data = { 'articlestats': ArticleStatSerializer(articlestats, many=True).data, and then I have defined the following serializers ... class LabelSerializer(serializers.ModelSerializer): class Meta: model = Label fields = ['name'] ... class ArticleSerializer(serializers.ModelSerializer): label = LabelSerializer() class Meta: model = Article fields = ['id', 'title', 'path', 'url', 'label'] class ArticleStatSerializer(serializers.ModelSerializer): article = ArticleSerializer() class Meta: model = ArticleStat fields = ['id', 'article', 'score'] I have defined my Label model like so ... class Label(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Meta: unique_together = ("name",) but I'm getting this error when Django processes my serialize line ... AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `LabelSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'name'. Not sure why it's complaining. The "name" attribute is right there. What else should I be doing? -
Creating .ebextensions directory in Django on Mac
I am trying to add an .ebextensions directory to my site root in Django. In the terminal I was able to create the file with no error, cd into the directory, and then add a django.config file (following this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb) However, when I view the parent directory of the .ebextensions directory, the file is not there! When I try recreating the directory in the terminal I get the following error: "mkdir: .ebextensions: File exists" When I try to manually create a folder titled .ebextensions in Finder, I get the following error: "You can't use a name that begins with a dot "." because these names are reserved for the system. Please choose another name." Any advice? -
Django uploading image in custom template
forms.py from django import forms from .models import VideoPost class PostForm(forms.ModelForm): class Meta: model = VideoPost fields = ('category', 'title', 'slug', 'content', 'video', 'image',) models.py class VideoPost(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique = True) author = models.ForeignKey(User, on_delete=models.CASCADE) video = models.CharField(max_length=100, blank=True) content = RichTextUploadingField() image = models.ImageField(upload_to='images', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) def _get_unique_slug(self, *args, **kwargs): self.slug = slugify(self.title) super(VideoPost, self).save(*args, **kwargs) def __unicode__(self): return self.title views.py def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return render(request, 'stories/post_detail.html') else: form = PostForm() return render(request, 'stories/post_new.html', {'form': form}) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) LOGIN_REDIRECT_URL = 'home' MEDIA_URL = 'static/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') This is not on django built in admin page, I wanted to make a custom post template. All other form inputs work just fine, and all the data are stored in db correctly except image. the image field in database is always blank no matter what image I put in there, and even in my static/media/image path, it's empty. Any help would be much appreciated. -
django-taggit-autosuggest in non admin page
So I've implemented the autosuggest for taggit, however I cant seem to get it to work on my form page and not just my admin page.I've followed the instructions as best I could but still seem to get no results, any help is appreciated. I'm using Python 3 if that makes any difference and Django 3.0.3 Taggit-autosuggest install guide: https://pypi.org/project/django-taggit-autosuggest/ head of HTML <head> <meta charset="utf-8"> <script src="jquery-3.4.1.min.js"></script> <link href='{{ STATIC_URL }}jquery-autosuggest/css/autoSuggest-upshot.css' type='text/css' media='all' rel='stylesheet' /> <script type='text/javascript' src='{{ STATIC_URL }}jquery-autosuggest/js/jquery.autoSuggest.minified.js'> </script> <link rel="stylesheet" href="{%static 'guide/style.css'%}"> {% if title %} <title>{{title}}</title> {% else %} <title>Audit Help center</title> {% endif %} </head> Form HTML {% extends 'guide/base.html' %} {% block content %} {% load static %} <div class ='content-section'> <form method="POST"> {% csrf_token %} <fieldset class ="form-group"> <legend class ="border-bottom mb-4">Post 1</legend> {{form|safe}} </fieldset> <div class="form-group"> <button class = "btn" type="submit">Save</button> </div> </form> </div> {% endblock content %} -
Volunteer search for an app related to the corona virus
Corona-Help.org is an initiative of volunteers. The initiative has the goal of connecting People in Need (elderly people, high risk people) with volunteers, which offer to go shopping, dog walking etc. to protect the People in Need to get in contact with the environment too much. The goals of the project: Offer a phone hotline for People in Need (elderly people, high risk people) for registering as Person in Need Offer a web application to Street Volunteers where they can find and connect to People in Need At the moment, we need people who have experience with django3/python3 specifically django rest framework. Others are also welcome. If you are interested in helping us join corona-helporg.slack.com. Thanks