Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can django superuser first and last name be updated? If yes, how do I go about it?
I'm want to render superuser first and last name on my html page. But django tutorials don't show how to add these fields to the superuser. How can I go about it? Thanks -
How can I get some value from the select option django form?
I would like to know if django-forms have some way to get the value from select > option html tag. I know I can do it using something like JQuery, but I would like to know if there is some way to handle this in the client side using any django feature. -
ImportError: Could not import 'formshare.libs.authentication.DigestAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
My Django Application is not giving any error when I run python manage.py runserver but still not running after full set-up. Below is the error log trace back. class APIView(View): File "/opt/formshare/lib/python2.7/site-packages/rest_framework/views.py", line 88, in APIView authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES File "/opt/formshare/lib/python2.7/site-packages/rest_framework/settings.py", line 197, in __getattr__ val = perform_import(val, attr) File "/opt/formshare/lib/python2.7/site-packages/rest_framework/settings.py", line 149, in perform_import return [import_from_string(item, setting_name) for item in val] File "/opt/formshare/lib/python2.7/site-packages/rest_framework/settings.py", line 165, in import_from_string raise ImportError(msg) ImportError: Could not import 'formshare.libs.authentication.DigestAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: No module named related. Installed application requirements # Django pybamboo==0.5.8.1 Django>=1.6,<1.7 django-guardian==1.2.4 django-registration-redux==1.1 django-templated-email==0.4.9 gdata==2.0.18 httplib2==0.9 mock==1.0.1 httmock==1.2.2 modilabs-python-utils==0.1.5 Pillow==2.5.3 poster==0.8.1 psycopg2==2.8.3 pymongo==2.7.2 lxml==3.4.0 django-nose==1.4.2 pandas==0.20.3 South==1.0 django-reversion==1.8.4 xlrd==1.1.0 xlwt==0.7.5 openpyxl==2.0.5 celery==3.1.23 django-celery==3.1.17 librabbitmq==1.5.2 python-digest==1.7 django-digest==1.13 requests==2.4.1 elaphe==0.5.6 # sms support dict2xml==1.3 # api support djangorestframework==2.4.3 djangorestframework-csv==1.3.3 # cors django-cors-headers==0.13 Markdown==2.5 django-filter==0.7 # captcha recaptcha-client==1.0.6 unicodecsv==0.14.1 dpath==1.2-70 # tagging django-taggit==0.12.1 # oath2 support django-oauth-toolkit==0.7.2 # spss savReaderWriter # JSON data type support jsonfield<1.0 django-db-readonly==0.3.2 # memcached support pylibmc==1.3.0 kombu==3.0.35 billiard==3.3.0.23 python-dateutil==2.6.0 Any advice on how to fix this would be highly appreciated. Thank you. Collins -
Want to make a user detail page as 'example.com/username' displaying their info, posts etc
I'm making a django site and using 'allauth' module for authentication. I've used the adapters so that the user is redirected to example.com/username but instead of it leading to homepage, i want it to lead to a page dedicated to the user profile containing their posts, info etc. and they can add more info to it. I have tried searching on the internet but couldn't find an appropriate solution. this is the adapter code i've used to redirect after login, i found this code in the documentation of allauth. class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): path = "/{username}/" return path.format(username=request.user.username) So, I want to know how can i create a separate profile page for users, and when someone not logged in opens that profile link, they can see their posts etc. like in instagram. -
Manually add form errors in between inputs
I left some space between the inputs because I want to manually add form errors there, however extra space is appearing below the error message. I am trying to make the error message exactly fit available space without form resizing. This is happening because I applied padding-bottom: 10px; on my <td> but I'm not sure how could I accomplish this otherwise. I have tried to use CSS grid instead of the table, and set grid-row-gap: 10px; but the result was similar. How can I make the error message fit the available space without form resizing? The error message is in this format: <ul class='errorlist'> <li>Please use another email, this one is already taken.</li> </ul> ...and it does not exist until the button is pressed and the invalid form was submitted. Here is my code: forms.py from django import forms from django.contrib.auth.models import User class RegistrationForm(forms.ModelForm): email = forms.EmailField(max_length=200, help_text='Required') password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords do not match.') return cd['password2'] def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise forms.ValidationError( 'Please use another Email, that is … -
How to enable user to use toggle field with django boolean field
I'm new to Django. Please help me out. I have an Ideas model which has an 'is_public' boolean field which is true by default whenever a user posts an idea in the platform. I want to enable the user to be able to toggle between this choice in the templates. How would I do this? This is my models.py class Ideas(models.Model): IDEA_STATUS = ( ('Approved', 'Approved'), ('Pending', 'Pending'), ('Declined', 'Declined'), ) objects = IdeaManager() balance_objects = IdeaBalanceManager() idea = models.AutoField(primary_key=True) user = models.ForeignKey(User,blank=True, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=400) problem_statement = models.TextField(max_length=2000) executive_summary = models.TextField(max_length=2000) objectives = models.TextField(max_length=2000) status = models.CharField(max_length=100, choices=IDEA_STATUS) limitations = models.TextField(max_length=2000) date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='idea_likes') # view_count = models.PositiveIntegerField(default=0) category = models.ForeignKey(Industry_category, on_delete = models.CASCADE) is_public = models.BooleanField(default=True) -
How to run django local host and activate virtual env by using single command?
I M New to Django, Whenever I open my project, everyday i type CMD to activate virtual env then, to open local server i use runserver, but I want to open my local host by using single command. Is there any way to do that? -
UnboundLocalError: local variable 'latest_comments_list' referenced before assig nment
from django.http import Http404, HttpResponseRedirect from django.shortcuts import render from .models import Article from django.urls import reverse def index(request): latest_articles_list = Article.objects.order_by('-pub_date')[:5] return render(request, 'articles/list.html', {'latest_articles_list': latest_articles_list}) def detail(request, article_id): try: a = Article.objects.get( id = article_id ) except: raise Http404("статья не найдена") latest_comments_list = a.comment_set.order_by('-id')[:10] return render(request, 'articles/detail.html', {'article': a, 'latest_comments_list': latest_comments_list}) def leave_comment(request, article_id): try: a = Article.objects.get( id = article_id ) except: raise Http404("статья не найдена") a.comment_set.create(author_name = request.POST['name'], comment_text = request.POST['text']) return HttpResponseRedirect( reverse('articles:detail', args = (a.id,)) ) -
Issue with installing virtualenv for
I am installing virtualenv for my DJango project. I have used: virtualenv venv virtualenv venv -p {myPath}Python/Python37-32/python but all of theese have thrown the same error: Complete output from command E:\DJango\firstTutor...2\Scripts\python.exe - setuptools pip wheel: Traceback (most recent call last): File "<stdin>", line 3, in <module> ModuleNotFoundError: No module named 'pkgutil' I am using the latest versions of Python, pip and virtualenv. -
RuntimeError when i try to integrate pythonBB
I try to integrate djangobb in my project. I find and follow the step of this guide [How to integrate djangobb in an existing project? but i have a RuntimeError: RuntimeError: Model class djangobb_forum.models.Category doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Please help me. here my settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'XXXXXX' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', #my app 'account', #my app 'django_summernote', 'tinymce', 'django.contrib.sites', # SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'giz.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'giz.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'XXX', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'fr' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) LOGIN_URL = '/account/connexion/' MEDIA_URL = '/media/' … -
how to sum all the consummations?
I already calculate, the total of one consummation, now i just want to sum all the consumaations ` class Consommation(models.Model): food = models.ManyToManyField(Food) consomme_le = models.DateTimeField(default=timezone.now, editable=False) vipcustomer = models.ForeignKey(VipCustomer, models.CASCADE, null=True, blank=True, verbose_name='Client prestigieux', related_name='vip_consommations') ` to calculate one consummation: ` def total(self): return self.food.aggregate(total=Sum('price'))['total'] ` Food class : ` class Food(models.Model): nom = models.CharField(max_length=100, verbose_name='Mon menu') price = models.PositiveIntegerField(verbose_name='Prix') category = models.ForeignKey(FoodCategory, models.CASCADE, verbose_name="Categorie") ` vipcustomer class: ` class VipCustomer(models.Model): first_name = models.CharField(max_length=150, verbose_name='Prénom') last_name = models.CharField(max_length=100, verbose_name='Nom') matricule = models.PositiveIntegerField(verbose_name='Matricule', default=0) adresse = models.CharField(max_length=200, verbose_name='Adresse', blank=True) telephone = PhoneField() company = models.CharField(max_length=100, verbose_name='La société') service = models.CharField(max_length=100, verbose_name='Service', null=True, blank=True) numero_badge = models.IntegerField(verbose_name='Numero du badge', null=True, blank=True) ` I expect to get the total of all the consummations. Many thanks for your help. -
upgrading python for django site running on Apache & wsgi
I'm trying to switch a django site from running in python 3.6 to python 3.7 on Ubuntu 16.04. To do so I created a new environment in the same path as the old and have re-installed all of the dependencies. The Apache server, however, fails with the following error: Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Which error, after a bit of research, seems to be due to the WSGI configuration, as per: You cannot for example force mod_wsgi to use a Python virtual environment created using Python 3.5 when mod_wsgi was originally compiled for Python 2.7. This is because the Python library for the Python installation it was originally compiled against is linked directly into the mod_wsgi module. In other words, Python is embedded within mod_wsgi. When mod_wsgi is used it does not run the command line python program to run the interpreter and thus why you can’t force it to use a different Python installation. from: https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html thanks to: Django Apache wsgi changes python version The OP in the above ended up just wiping the setup clean and starting from scratch. This seems a bit extreme to me, as it … -
How to autopopulate fields with data in django forms
wondering if you could help me out, or at least point me in the right direction! I'm having a bit of trouble getting and of my fields to autopopulate with data. reviews/forms.py: from django import forms from .models import Review class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ['course','user_name', 'rating', 'comment', 'pub_date'] reviews/models.py from django.db import models from courses.models import Course from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) course = models.ForeignKey(Course, primary_key=True) pub_date = models.DateTimeField(null=True, default=timezone.now) user_name = models.CharField(max_length=100, blank=True) comment = models.TextField(max_length=300, blank=True, null=True) rating = models.IntegerField(choices=RATING_CHOICES, null=False) reviews/views.py from django.shortcuts import render, get_object_or_404, reverse, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ReviewForm from .models import Review from django.conf import settings from django.utils import timezone from courses.models import Course import datetime # Create your views here. def course_review(request, course_id): """ Gets the most recent 10 reviews for the course """ course = get_object_or_404(Course, pk=course_id) reviews= Review.objects.filter(course = course_id).order_by('-pub_date')[:10] return render(request, "review.html", {"reviews":reviews, "course":course}) def add_review(request,course_id): """ To display the review form to the user """ if request.method == "POST": form = … -
Django Model field default from Model
Consider two models in my models.py: Roles: class Role(models.Model): role = models.CharField(max_length=255) nickname = models.CharField(max_length=255) is_hero = models.BooleanField(default=False) def __str__(self): return self.role and Players: class Player(models.Model): name = models.CharField(max_length=255) role = models.ForeignKey(Role, on_delete=models.CASCADE) nickname = models.CharField(max_length=255, default="Use the default nickname from the role you just chose but also be able to change it from within this model.") is_hero = models.BooleanField(default="Use the default is_hero from the role you just chose but also be able to change it from within this model.") def __str__(self): return self.name Also consider that I already made a role called "Dumbo" with the nickname "Dunm" and is_hero being False. I now go ahead and try to use the role in my new player after setting my player name, I choose my role but how do I use the values of my now chosen role in my new player as the default for nickname and is_hero and at the same time, allow them to be overridden if feel so? Thanks, -
Django - filtering model objects
I have some model: class Reservation(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=50) date_start = models.DateTimeField(default=timezone.now) date_stop = models.DateField(default=timezone.now) I try to filter all Reservations: @login_required def reservations_list_view(request): reservations = Reservation.objects.all() return render(request, 'reservations/reservations_list.html', {'reservations': reservations}) At this moment - i skipped this filter: reservations = Reservation.objects.filter( ... ) - I dont know what should I use. I'd like to see all Reservations e.g. after today (start_date) and here is my problem. Could u help with it? -
PythonAnywhere Issue: Your processes have been killed because a process exceeded RAM Limit
I am getting this warning email from PythonAnywhere on every single request to my website. I am using spaCy and Django and have just upgraded my account. Everything seems to work fine, though. Except I am receiving warning emails, that is. I have only 2 GB RAM on my local machine and it can run my app along with a few other apps too without any issues. Then why is 3 GB RAM not enough on PythonAnywhere? (I also have 3 GB disc space on PythonAnywhere, of which only 27% is used up.) I have tried searching for the answers on their forum and on the internet in general but I have not got any clue about the issue. -
Python process doesn't work asynchronous on uwsgi with nginx but working well on manage.py runserver
I try to build asynchronous function with callbacks it work fine when I try python manage.py runserver but when I use it on server with uWSGI and nginx the code is run synchronous and main process wait for child's process to done I tried to use threads instead process it work fine but in my code I use some global system function which doesn't work well on threads like - sys.stdout import time import sys def my_process_func(arg, arg2): sys.stdout = open(arg+".txt", 'a+', encoding='utf8') print("Running process! Args: " + arg + ', ' + arg2) time.sleep(10) print("Done!") p = Process(target=my_process_func, args=("p1", "test")) p2 = Process(target=my_process_func, args=("p2", "test2")) p.start() p2.start() print("Spun off process") the result when I run this code using python server is creating two txt files with output Spun off process p1.txt Running process! Args: p1, test Done! p2.txt Running process! Args: p2, test2 Done! but using uwsgi the result is Running process! Args: p1, test Done! Spun off process -
how to get entire current url in django
I have some trouble getting current url in django. current url is 'https://localhost:8000/?#access_token=EAAJ0Dqh2BJ0BABNKWfkqmiIr3uWwKvpkVeCAVQTZBQSEFG87GKjXunsoofixxKS11ZCicElsZBRMKHL4Dk5nGeBa5lBkYvzw3YKrzZAyZAvhlvd1pAtxzZBPlD4PJaD7JFz4UCjOEIyo5ZCfyBIysva1PCK0XZAN7FpXCDRpDxlEVxtnN9RrbZAt26ZChHV3LRupoZD&data_access_expiration_time=1576926047&expires_in=7153' i used several url getting functions such as request.get_full_path() and request.build_absolute_uri(), but they did only returns 'https://localhost:8000' How can i get the string following '#' such as access_token? -
Can't see Angular project inside Django
I am trying to run Angular inside Django project. I successfully installed it and have no errors when I run the Django server. However I do not see my Angular. app.component.html. I see my index.html of folder "templates" instead. templates/index.html {% extends "base.html" %} {% load staticfiles %} {% block content %} <p>This is a mini-blog application using a back-end built on Django 2.0 and Django Rest Framework. It illustrates how to create and send JSON Web Token authentication headers with the HTTP requests.</p> <app-root>Loading the app...</app-root> <script type="text/javascript" src="{% static 'clientapp/runtime.js' %}"></script> <script type="text/javascript" src="{% static 'clientapp/polyfills.js' %}"></script> <script type="text/javascript" src="{% static 'clientapp/styles.js' %}"></script> <script type="text/javascript" src="{% static 'clientapp/vendor.js' %}"></script> <script type="text/javascript" src="{% static 'clientapp/main.js' %}"></script> {% endblock %} Obviously, something is missing. Thanks in advance. -
How to make a request using jQuery to a django server to refresh infos on page
I made a website in python using Django. My site allows you to control lights while indicating if the light is on or not. I'm looking for a solution that could make a simple request with data to the server and send data back to the client without updating the entire page but only a part of it. My ideal would be for the client to make a request to the server with identification data. Then, the server returns the updated data that the user is allowed to have. Is that possible to make a JavaScript to do that ? And the server, how it can return data to the client ? -
How to merge queryset instances of one object to another?
I have a Django model known as Ingredient and i want to merge ingredient objects returned by queryset selected by the user in Django admin. I have created an action in Django admin known as "Merge selected" in which user select ingredients and click on the action created by me. i m very new to django and i m stuck on this problem from since. Below i m attaching model class. class Ingredient(models.Model): name = models.CharField(max_length=1000) purpose = models.TextField(verbose_name="How does it work", blank=True) molecular_weight = models.CharField(max_length=100,null=True,blank=True) functions = models.ManyToManyField(Function,blank=True) comedogenity = models.IntegerField(blank=True,null=True) irritant = models.IntegerField(blank=True,null=True) ewg = models.CharField(verbose_name="Safety", max_length=100, blank=True,null=True) ref_url = models.CharField(max_length=1000) notes = models.ManyToManyField('Note',blank=True) uva = models.CharField(max_length=100,blank=True,null=True) uvb = models.CharField(max_length=100, blank=True, null=True) cir = models.CharField(max_length=100, blank=True, null=True) families = models.ManyToManyField('Family',blank=True) is_excluded = models.BooleanField(default=False) slug_identifier = models.CharField(db_index=True, default=generate_slug, editable=False, unique=True, max_length=16) @property def slug(self): slug_string = self.name + " " + str(self.slug_identifier) return slugify(slug_string) @staticmethod def deslugify(slug): slug_identifier = str(slug.split('-')[-1]) return slug_identifier @property def alt_names(self): alt_names = AlternativeName.objects.filter(parent_ing=self).values_list('name', flat=True) if alt_names: return ' / '.join(alt_names) return "" def __str__(self): return str(self.pk) + " : " + self.name def get_absolute_url(self): return reverse('single_ingredient',args=[str(self.slug)]) At the end i want the union of two objects into one object returned by queryset and save … -
Store data from a dynamic form in an arrayfield (postgrsql)
New in python/django development, i'm stopped by a problem. I have a model 'Order' who stores ... orders class Order(models.Model): datecom = models.DateTimeField(default=timezone.now, verbose_name="Date de commande") when = models.ForeignKey(OrdTime, on_delete=models.CASCADE, blank=True, null=True) stand = models.ForeignKey(Group, on_delete=models.CASCADE) user = models.CharField(max_length=100, blank=True, null=True) products = JSONField(default=defaultlist) status = models.BooleanField(default=False) dateliv = models.DateTimeField(verbose_name="Date de livraison", blank=True, null=True) slug = models.SlugField() class Meta: verbose_name = "- Commande" verbose_name_plural = "- Commandes" ordering = ['dateliv'] def get_products(self): return format_html_join('', '{} : {} <br>', ([(product, score) for score, product in self.products])) def __str__(self): return self.slug As you can see, 'stand' is an ArrayField (Postgresql) who stores a list of product, with, for each one, a quantity. Like this: def defaultlist(): return [ (15, "Product 1"), (1, "Product 2"), (2, "Product 3") ] I am creating a public (but user authenticated) form who can store data to ordering products. This form have to store order date, name of the 'stand' etc. and (this my problem) store product name and quantity for each product. Only products with quantity > 0 have to be stored. It's a mess for me. How can I display input field for each row product/quantity in a model form and format this inputs to … -
Model based caching instead of view based caching in django
I am working on a django application. The main task of the application is providing suggestion like "Should I go outside today?". There is only a single endpoint to get the suggestion such as example.com/. The main logic for providing the suggestion is: Does the user has any pending task today? (querying from UserTaskModel) Is today's weather is comfortable? (calculating weather forecasting) If two user try to fetch data at the same date then the UserTask query will be different. But weather forecast query task will be same. If I use view based django caching then the weather forecast query will be execute for each user. But I want to cache the weather query data for all user at a same date. It can view implement by creating different view for the weather. But I don't want to use another endpoint for the weather. Django cache set-get method can be use for this task. But is this way is the best way to do this type of task? In my example I use a simple weather calculation query depending the the date. But is this technique is good for complex query? -
change datalist input when another changes
I have two datalist input like this. <input list="Province" name="Province" id="1"> <datalist id="Province"> {% for item in province_list %} <option >{{item.Name}}</option> {% endfor %} </datalist> <input list="City" name="City" id="2"> <datalist id="City"> {% for item in city_list %} <option >{{item.Name}}</option> {% endfor %} </datalist> i want when user select Province, i show list of that province city in input2. -
Get ImportError when trying to runserver
I have a django application which works when I runserver in local. My problem is that I copied my project packages in server and now when I try to runserver I get ImportError I searched a lot and I tried everything but they did not work. things including : 1- activating virtual env 2- installing django(pip install django cmd and sudo pip install django as well) 3- using python and python3 in cmd I get the error when I try to run this command: python3 manage.py runserver File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?```