Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's list_select_related does not show foreign key's attributes
Basically I am trying to have the attributes of a foreign key available both in the list_display and in the admin editor. However, even using the list_select_related (I have also tried modifying the queryset with the select_related method) the foreign key attributes do not appear in any of the mentioned admin screens. Toy example: class BookAdmin (admin.ModelAdmin): list_select_related = ('author',) Where the book model has a OneToOne relationship with author, and author has some attributes (first_name, last_name, etc.) that I want to display in the admin site. Am I forgetting something? I know I could do lookups to list and inlines to edit, but it doesn't seem like a very optimal solution ... Thank you very much! -
Render PHP through Django
Is there any way to render PHP files through Django for code Reusability. I have tried through django_php module and it was 10 year old module, so it does not support latest python versions (3.9) Any help is appreciated .Thanks -
Django servers not starting after installing live server
reloading the site every time was very frustrating to me so i thought to look for a live server for djanglo Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "C:\Users\piyush\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 52 except ImportError,e: ^ SyntaxError: invalid syntax and this is the error popping now when i used python manage.py runserver command https://pypi.org/project/django-liveserver/ the server i installed -
Django User Login Error -login() missing 1 required positional argument: 'user'
views.py def loginUser (request): if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/") else: return render(request,'login.html') -urls.py urlpatterns = [path('',views.index,name='home'), `path('login',views.login,name='login')] -
Order of returned django records changed after upgrading to postgrers12?
Our Django project has been running on Postgres 10.15 for a while and now we need to upgrade to Postgres12. While running the unit tests, one of them broke. Turns out, the reason for this is that after fetching objects using xyz.abc_list.all(), (abc references xyz with the related name abc_list) the order of the returned objects have changed (PS. the model class abc does not have any ordering in meta). I have been trying to go through the changelog of postgres but have not been able to find anything that gives a solid reason for the change in this behavior. AFAIK, the django does not ensure any ordering if not mentioned.. Can there be proper reasoning established for this change in behavior? -
Django AJAX Infinite Scroll Error on page reload
I'm trying to implement infinite scroll with django and jquery(Waypoint). I have a ListView with a pagination of 5, but when waypoint loads second page, AJAX requests are no longer performed so I added the AJAX function on the onAfterPageLoad which helps bring back AJAX function to the newly loaded page. That's fine, but then it introduces a bug to my code making the page loaded initially (First Page) no longer perform AJAX functions very well. It makes AJAX on the first page run 3 times if I just loaded a third page and makes AJAX on the second page run twice and so on depending on the number of pages loaded already. I don't know if there are any cool ways to achieve this because I tried using just jquery without waypoint, but still get same errors as I get when using just waypoint making it an error. This is kinda tricky so far. {% extends "base.html" %} {% block content %} {% load static %} <div class="container" style="max-width:700px"> <div class="px-3 pt-md-5 pb-md-4 mx-auto text-center"> <h1 class="display-4">All Groups</h1> <p class="lead">List of groups</p> </div> <div class=""> <div class="row infinite-container"> {% for group in groups %} <div class="col-md-12 infinite-item"> <!-- <img … -
Django create user profile
I created a user profile model for my system. I created all models and It works perfectly. I have a form and form works too. But when I look user create form from admin page, It doesn't look the same. There are some missing parts like rank, comp_name. How can I fix it? models.py class UserProfile(models.Model): ranks = ( ('xxx', 'xxx'), ... ) comp_name = models.CharField(max_length=200, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500) first_name = models.CharField(max_length=200, default=None) last_name = models.CharField(max_length=200, default=None) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) forms.py class SignUpForm(UserCreationForm): comp_name = forms.CharField(label='What is your company name?') email = forms.CharField(max_length=254) rank = forms.ChoiceField(label='What is your rank?', choices=UserProfile.ranks) first_name = forms.CharField(max_length=250) last_name = forms.CharField(max_length=250) comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all()) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'comp_name', 'password1', 'password2', 'rank' admin enter image description here -
Django Admin Interface Upload Multiple Images at once
I would like to upload upload up to 10 images at the same time to ImageField or FileField in Django Admin Interface. I know that there is some JavaScript libraries like Dropzone.js but I don't know how to use it in admin interface -
Django Models how to add unique constraint
Unsimilar to for example this case I am trying to allow only one entry in a database for one user: class Station(models.Model): serial = models.CharField("serial", max_length = 31, unique = True) user = models.ForeignKey(User, on_delete = models.CASCADE, ) What I want is that one user can only have zero or one Station (serial). -
How to avoid abusing TRY EXCEPT when check API parameters requested?
I have an API which is a POST This API has a lot of optional parameters, so obviously, my code would be something like this: input_data = request.data try: optional_parameter_1 = input['parameter_1'] except: **do sth ............................................. try: optional_parameter_2 = input['parameter_1'] except: optional_parameter_2 = something ................................................ In my code there are a lot of it, and I think I am abusing try and except too much. I wonder if there is any alternatives way which is short, simple and clean then using try and except -
(Django - Python) "Select a valid choice. That choice is not one of the available choices." - Django Admin Error
I have to register two models on the site administration of Django but when I choose the element and click on save I get this error: Select a valid choice. That choice is not one of the available choices. I put here my code of: - models.py from django.db import models from django.contrib.auth.models import User from djongo.models.fields import ObjectIdField class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE) datetime = models.DateTimeField (auto_now_add=True) price = models.FloatField() quantity = models.FloatField() - admin.py from django.contrib import admin from .models import Order, Profile admin.site.register(Order) admin.site.register(Profile) Can you help me please, thanks to everyone! -
How can I check if an user is superuser in django
I'm listing registered users on a ListView page and I'm trying to show if user is superuser or not. My main user is created with "manage.py createsuperuser" command and I'm sure it is a superuser beacuse I've checked from admin panel too. When I try to print if it is superuser or not my code always shows a "False" output. Here are my codes: views.py @method_decorator(staff_member_required, name='dispatch') class Uyeler(ListView): model = User paginate_by = 40 ordering = ['-pk'] template_name = "panel/uyeler.html" and in template file: {% for obj in object_list %} {% if obj.is_superuser %}SuperUser {% else %} Not SuperUser {{ obj.is_superuser }} {%endif%} {% endfor % And my html output is "Not SuperUser False" for all users including my superuser account. Any ideas? -
Creating Gunicorn docker file with Postgress without DB name error
I'm building my container like this FROM python:3.7.4-alpine3.10 ADD mediadbin/requirements.txt /app/requirements.txt RUN set -ex \ && apk add --no-cache --virtual .build-deps postgresql-dev build-base python3-dev gcc jpeg-dev zlib-dev\ && python -m venv /env \ && /env/bin/pip install --upgrade pip \ && /env/bin/pip install --no-cache-dir -r /app/requirements.txt \ && runDeps="$(scanelf --needed --nobanner --recursive /env \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u)" \ && apk add --virtual rundeps $runDeps \ && apk del .build-deps ADD mediadbin /app WORKDIR /app ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH EXPOSE 8000 CMD ["gunicorn", "--bind", ":8000", "--workers", "3", "mediadbin.wsgi:application"] which works, but when I run Django's makemigrations to populate my DB in the container I'm getting an error django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? my env file look like this DJANGO_SECRET_KEY=somekey DEBUG=True DJANGO_ALLOWED_HOSTS=* DATABASE_ENGINE=django.db.backends.postgresql_psycopg2 DATABASE_NAME=django_db DATABASE_USERNAME=somename DATABASE_PASSWORD=somepass DATABASE_HOST=127.0.0.1 DATABASE_PORT=5432 DJANGO_LOGLEVEL=info I found here that I can't connect to localhost inside of the container and I should set service name for the db to connect to, but I'm not using a yml file so … -
How to assign a permissions system to my roles with django?
So I have two models which depict roles. class GlobalRole(models.Model): """ Represents a Global-Role object. Roles have their own: - Hex Color Code [Integer Representation] - Name [&] - Permissions. """ objects = RolesManager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) name = models.CharField(max_length=512, db_index=True) hex_color_code = models.IntegerField(db_index=True) position = models.IntegerField(db_index=True) parent = models.ForeignKey('api_backend.DataSheetsCluster', on_delete=models.CASCADE, db_index=True, editable=False) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) REQUIRED_FIELDS = [name, parent, position] class LocalRole(models.Model): """ Represents a Local-Role object. An one-to-one related model with Global role. Roles have their own: - Hex Color Code [Integer Representation] - Name [&] - Permissions. Role permissions for individual datasheets override global parent permissions. """ objects = RolesManager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) global_role = models.OneToOneField('api_backend.GlobalRole', on_delete=models.CASCADE) parent = models.ForeignKey('api_backend.DataSheet', on_delete=models.CASCADE, db_index=True) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) REQUIRED_FIELDS = [global_role, parent] Roles have a set of permissions of their own, and can be assigned to users. Roles have a position field. The lowest position depicts the user's highest role, and vice versa. The permissions for the user's highest role is taken as the user's permissions. I have this system of clusters and datasheets, too. Clusters can contain multiple datasheets. So now roles can be created for clusters, and these … -
Serve voice files like with Youtube features
I want server large voice files, and I need to make them like Youtube; it means the client can have a seek bar, all voice files should have chunked and can be accessed while playing. Like I want to get in the middle of a voice without getting the whole file. Any solutions? Any keyword can help me? -
Cross-Origin Request Blocked Django and React
I have installed pip install django-cors-headers still not working added into the settings.py file INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] Django Rest Framework -
Django: Heroku server status 500 when debug=False
I deployed my application to Heroku and I keep getting a 500 error (Server Error (500)) when I set debug =False. I have researched every stackoverflow article about this subject but I cant manage to find the solution. I assume that there is a problem inside my Settings file somewhere. import os import django_heroku import dj_database_url from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'planning.apps.PlanningConfig', 'kalender.apps.KalenderConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django_filters', 'bootstrap3', 'django_popup_view_field', 'access_tokens', 'django_expiring_token', 'django_cleanup', # this one automatically deletes old profile pictures after a new one has been set. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'storages' ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'django_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True WSGI_APPLICATION … -
trying to run python script from a django form can any one please help me out.iam new to django
creating a simple ui which takes 2 files as input and if we press submit button then trying to run script.py(which is python script) and render output on screen or some output folder #forms.py from django import forms class AwsForm ( forms.Form ): Aws_SourceFile = forms.FileField () Aws_RefernceFile = forms.FileField () #views.py from django.shortcuts import render from .forms import AwsForm import subprocess def home_view(request): context = {} context [ 'form' ] = AwsForm () return render ( request , "home.html" , context ) def submit_view(request): info = request.POST [ 'info' ] def my_view(request): if request.method == 'GET': form = AwsForm () else: if form.is_valid (): info = request.POST [ 'info_name' ] output = script_function ( info ) return render ( request , 'myapp/home.html' , { 'info': info , 'output': output , } ) return render ( request , 'myapp/home.html' , { 'form': form , } ) def script_function(post_from_form): print ( post_from_form ) return subprocess.check_call ( [ '\script_18122020.py' , post_from_form ] ) #urls.py from django.contrib import admin from django.urls import path from myapp.views import home_view, submit_view urlpatterns = [ path('', home_view ), path('submit', submit_view), ] #home.html {% block main_content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> … -
Filter the foreign key in generic CreateView
I have a DetailView list for Course Model. path('<slug:url>/', views.CourseDetailView.as_view(), name='course'), path('<slug:url>/update', views.CourseUpdateView.as_view(), I do have one more Model for Enrollment. And i want to format my URL something like this path('<slug:url>/enroll', views.EnrollmentCreateView.as_view(), Above, I used CreateView for enrollemnt. I have 3 main model, Course, Batch and Enrollment model, class Course(models.Model): name = models.CharField(max_length=100, unique=True) url = models.CharField(max_length=100, unique=True) description = models.TextField(blank=True, null=True) duration = models.IntegerField(blank=True, null=True) fee = models.IntegerField(blank=True, null=True) image = models.ImageField(default='course.jpg', upload_to='course_pics') order = models.IntegerField(blank=True, null=True) def __str__(self): return f'Course {self.name}' class Batch(models.Model): class Meta: unique_together = (('course', 'batch_no'),) course = models.ForeignKey(Course, on_delete=models.CASCADE) batch_no = models.IntegerField(blank=True) centre = models.ForeignKey(Centre, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() instructor = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='instructor_name', limit_choices_to={'role': 'staff'}) def __str__(self): return f'Batch: {self.batch_no} ({self.start_date} - {self.end_date})' class Enrollment(models.Model): class Meta: unique_together = (('batch', 'student'),) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) student = models.ForeignKey( CustomUser, on_delete=models.CASCADE, limit_choices_to={'role': 'student'}) completed_date = models.DateField(blank=True, null=True) certificate_no = models.CharField(max_length=30, blank=True) payment_reference = models.CharField( max_length=50, blank=True, null=True) payment_notes = models.CharField( max_length=50, blank=True, null=True) def __str__(self): return f'{self.batch.course.name}: Student: {self.student.username}' I want to pass the course url from the path path('<slug:url>/enroll', views.EnrollmentCreateView.as_view()) to the EnrollmentCreateView, so that I can filter the batch that belongs to particular course. I dont know … -
Django-Rest-Framework Serializer validate data return None
I'm having trouble getting data in validate() function of Serializer for my API. I'm using django AbstractUser Model Django = "^3.1.3" djangorestframework = "^3.12.2" My serializers.py: class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(max_length=255, required=True) new_password = serializers.CharField(max_length=255, required=True, write_only=True) new_password_confirm = serializers.CharField(max_length=255, required=True, write_only=True) def validate_old_password(self, value): if not self.context['user'].check_password(value): # got data raise serializers.ValidationError("Incorrect Old Password") def validate_new_password(self, value): try: # validate the password and catch the exception validators.validate_password(password=value) # got data # the exception raised here is different than serializers.ValidationError except exceptions.ValidationError as e: raise serializers.ValidationError(list(e)) def validate_new_password_confirm(self, value): try: # validate the password and catch the exception validators.validate_password(password=value) # got data # the exception raised here is different than serializers.ValidationError except exceptions.ValidationError as e: raise serializers.ValidationError(list(e)) def validate(self, data): if data['new_password'] != data['new_password_confirm']: # both return None raise serializers.ValidationError({'message': ["Your password and confirmation password do not match."]}) return data views.py: class change_password(APIView): def post(self, request): received_json_data=request.data user = request.user serializer = ChangePasswordSerializer(data=received_json_data, context={'user': user}) if serializer.is_valid(): user.set_password(received_json_data['new_password']) # got new_password return JsonResponse({ 'message': 'Password changed.' }, status=200) else: return JsonResponse({'message':serializer.errors}, status=400) The problem is in validate(self, data) the data currently return as OrderedDict([('old_password', None), ('new_password', None), ('new_password_confirm', None)]) so it skipped the custom validation, but in other validation methods … -
Bulk create with multi-table inheritance models
I'm using multi-table inheritance models. from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class Cinema(Place): sells_tickets = models.BooleanField(default=False) sells_popcorn = models.BooleanField(default=False) class Coffee(Place): sells_tea = models.BooleanField(default=False) I have a view that creates several different models: items = [ Restaurant(...), Restaurant(...), Restaurant(...), Cinema(...), Cinema(...), Coffee(...), Coffee(...), # + 1.000 other items ] for item in items: item.save() Obviously, this is really inefficient since it creates a lot of queries. Unfortunately, Django doesn't provide a bulk-create method for multi-table inheritance yet (there is an open pull request for it). What is the best way to optimize this code? Do I have to write a raw SQL query or is there another way? -
ImportError while rendering PHP files through Django Views
For code reusability, I'm trying use the previously created php file to render in django when I access the url.I have tried some installing django_php module as mentioned Here I'm getting the following error while rendering InvalidTemplateLibrary at / Invalid template library specified. ImportError raised when trying to load 'django_php.templatetags.php': No module named 'popen2' Any help is appreciated. Thank you. -
config Tiny Editor in django
i use tiny editor and i wanna use 'js': ['path/to/editor.js', 'path/to/plugin.js'] instead of 'js': ['//cdn.ckeditor.com/4.14.0/standard/ckeditor.js'] now don't know how i can, I copy code from cdn to my static path : static/jquery/my-js/script.js Try to use this path instead of cdn but it didn't work, try to override the source but i can't. how to load from static and change it main code? and i don't want use script in html i config it in my settings.py. how it possible?? thanks. -
Django OperationalError table has no column named user_id
I created a signup system. Firstly it was working but then I added name and surname to my models then it stopped work. I delete all migrations and I apply makemigrations and migrate. Bu I get an error. I use Sqlite. OperationalError at /admin/auth/user/add/ table register_companyprofile has no column named user_id models.py class CompanyProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) comp_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) comp_name = models.CharField(max_length=200) class UserProfile(models.Model): ranks = ( ('analyst', 'Analyst'), ('seniorAnalyst', 'Senior Analyst'), ('lead', 'Lead'), ('manager', 'Manager'), ('seniorManager', 'Senior Manager'), ('director', 'Director'), ('regionalDirector', 'Regional Director'), ('cfo', 'Chief Financial Officier'), ) companies = () comp_name = models.CharField(max_length=200, choices=companies, default="Choose") user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True) username = models.CharField(max_length=500) name = models.CharField(max_length=200, default=None) surname = models.CharField(max_length=200, default=None) password = models.CharField(max_length=50) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200, choices=ranks) forms.py class SignUpForm(UserCreationForm): comp_name = forms.CharField(label='What is your company name?') email = forms.CharField(max_length=254) rank = forms.ChoiceField(label='What is your rank?', choices=UserProfile.ranks) name = forms.CharField(max_length=250) surname = forms.CharField(max_length=250) class Meta: model = User fields = ('username', 'name', 'surname', 'email', 'comp_name', 'password1', 'password2', 'rank') views.py def signup(request): form_class = SignUpForm if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.save() raw_password = … -
Working with composite primary key and foreign keys in django project with legacy database
In this question, e4c5 suggests updating tables in the legacy database with a single primary key to work with Django. However, every table referencing the updated table will be using the composite primary key as reference and will therefore not work in Django. Is there a way to either update the tables so they would use the new primary key, or a workaround for this?