Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery - No result backend is configured while running in prod
I use ASGI aka uvicorn to run my django application in production and i'm also using celery to call specific tasks at my app. Now I configured a result backend so that I can see all my tasks results at the Django admin which is working fine if I use the Django development server. But if I switch to production mode and using uvicorn I get back the following error: Exception Value: No result backend is configured. Please see the documentation for more information. while waiting on a celery task I call like that at my views.py: my_task = gen_new.apply_async(kwargs={"user_pk": user.pk}) my_task.get(timeout=30, interval=1) my asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'App.settings') application = get_asgi_application() starting the ASGI server like so: gunicorn App.asgi:application \ --workers $UVICORN_WORKERS \ --bind=127.0.0.1:8000 \ --log-level info settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": [ str("redis://") + str(':') + env.str('REDIS_PASSWORD') + str('@') + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT') + str("/") + env.str('REDIS_CACHE_DB') ], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "SOCKET_CONNECT_TIMEOUT": 30, # in seconds "SOCKET_TIMEOUT": 30, # in seconds "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", "CONNECTION_POOL_KWARGS": {"max_connections": env.int('REDIS_MAX_CONN'), "retry_on_timeout": True} } } } BROKER_URL = str("redis://") + str(':') + env.str('REDIS_PASSWORD') + str('@') + env.str('REDIS_HOST') + str(":") + env.str('REDIS_PORT') CELERY_RESULT_BACKEND … -
Django can't extend to a template in another app
This is the structure of the project right now. webbshop templates webbshop base.html home templates home index.html In my "webbshop" settings which is the main app i have put the home as an installed app. But when i try to extend the base.html from index.html I get this error "django.template.exceptions.TemplateDoesNotExist: webbshop/base.html" On the page it shows this. https://i.stack.imgur.com/QUQbd.png It appears that it does not go and look for the template in the webbshop app. I searched around and that should work. This is my index.html {% extends 'webbshop/base.html' %} {% block content %} hey {% endblock %} -
"PL/SQL: ORA-02289: sequence does not exist" in django while doing loaddata. database is remote oracle 12c
while doing loaddata fixture, getting error PL/SQL: ORA-02289: sequence does not exist. Django version is 1.11.12. django.db.utils.DatabaseError: ORA-06550: line 10, column 17: PL/SQL: ORA-02289: sequence does not exist ORA-06550: line 10, column 9: PL/SQL: SQL Statement ignored in python shell, i can create objects but through fixtures, i couldn't. please help. -
Loop over tbody in Django views
I am trying to loop over a tbody in my django views to get the data from the form but when i print the items in the tbody it only shows the last one Here's the part I am trying to loop on <tbody class="player-instances"> <tr> <td><input type="text" name="form-0-pname" id="id_form-0-pname"></td> <td><input type="number" name="form-0-hscore" id="id_form-0-hscore"></td> <td><input type="number" name="form-0-age" id="id_form-0-age"></td> </tr> <tr> <td><input type="text" name="form-0-pname" id="id_form-1-pname"></td> <td><input type="number" name="form-0-hscore" id="id_form-1-hscore"></td> <td><input type="number" name="form-0-age" id="id_form-1-age"></td> </tr> </tbody> Views.py if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: print("item", item) print("form.cleaned_data", form.cleaned_data) player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() The output in terminal is the following: item {'pname': 'tt22', 'hscore': 8, 'age': 89} form.cleaned_data {'tname': 'tt1'} Why is it overriding the first input fields despite having different id? -
profile photo not updating after uploading a different photo in Django. request.FILES is always empty. Using Django 2.1
I am trying to update the profile photo of a customer. But it is not updating. request.FILES shows empty if I try to print. if I print request.POST file, it contains the uploaded file but It is not in request.FILES views.py @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def accountSettings(request): if request.method == 'POST': form = CustomerForm(request.POST, request.FILES, instance=customer) if form.is_valid(): form.save() else : form = CustomerForm(instance=customer) context = {'cust_form' : form} return render(request, 'accounts/account_settings.html', context) models.py class Customer(models.Model): cust_user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="default.png", null=True, blank=True) # blank=True => not required field date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name forms.py class CustomerForm(ModelForm): class Meta: model = Customer fields = '__all__' exclude = ['cust_user'] I found the cause of empty request.FILES is not adding enctype="multipart/form-data" in form. But I have added that too. accountSettings.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <style> .profile-pic{ max-width: 200px; max-height:200px; margin: 0 auto; border-radius: 50%; } </style> <br> <div class="row"> <div class="col-md-3"> <div class="card card-body"> <a class="btn btn-warning" href="{% url 'home' %}"> &#8592; Back to Profile</a> <hr> <h3 style="text-align: center">Account Settings</h3> <hr> <img class="profile-pic" src="{{request.user.customer.profile_pic.url}}" > </div> … -
Make success message disappear after few seconds of django form submission and display empty form
I have a Django form where the person needs to add their details to subscribe and I want the page to show successful submission message below the submit button for few seconds (lets say 3) and then it should disappear and the form fields should be displayed empty. The function definition in views.py is as follows : def new_customer(request): if request.method == "POST": form = customer_form(request.POST) if form.is_valid(): form.save() messages.add_message(request, message_constants.SUCCESS, '✔️ SUCCESSFUL SUBSCRIPTION') return HttpResponseRedirect('http://127.0.0.1:8000/subscribe/') else: form = customer_form() return render(request,"new_customer.html",{'form':form}) The Django template : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Subscribe</title> <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet"> <link href="{% static "nav.css" %}" rel="stylesheet"> <link href="{% static "form.css" %}" rel="stylesheet"> </head> {% include "navbar.html" %} <body> <form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit" class="btn">Subscribe</button> {% if messages %} <ul id ="successMessage" class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %} style="color:green; font-size: 20px; list-style-type: none;">{{ message }}</li> {% endfor %} </ul> {% endif %} </form> </body> </html> The current code helps display the message for successful submission, as well as empty form fields but does not make it disappear. Could anyone help ? -
Django React project structure
I have a project with Django as back-end. And for the client side I have 4 different sections: Django Admin Panel for super user which renders by Django itself. User Login and Signup section which is rendered by Django-Jinja template system. App admin panel which is a react app Main app front-end which is a react app The structure that I have in my mind is like this: ├── djangoproject │ ├── __init__.py │ ├── settings.py (can be folder) │ ├── urls.py │ └── wsgi.py ├── apps | ├── admin_panel | ├── core | ├── auth | └── ... ├── templates | ├── admin_panel (react) | ├── core (react) | └── auth ├── static └── manage.py I have two questions: 1- should I change the structure of my project (for example bring react folders outside or use frontend folder naming instead of templates?) 2- Is it common (or reasonable) to use git sub module for react apps and only commit build of them in main project? If it is can you give any example or best practice? -
how to host simple blog site made django framework by using termux?
Here is my logs . I had made a app on name called my blog on heroku . I had runtime.txt , requirements.txt and pocfile what i am missing https://del.dog/raw/ughuphivol -
How to connect Mongo DB from django?
I am trying to connect mongodb from django.which is settings.py. In setting.py i gievrn connection like DATABASES = { 'default': { 'ENGINE': 'django', 'NAME': 'mydb', } } Where i am executing command like: python manage.py makemigrations it is throwing error like django.core.exceptions.ImproperlyConfigured: 'django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Please tell me how to connect Mongodb from django. Thanks -
For a "Movie Ticket Booking Web App" I want django movie recommendations based on watch history. What will be the requirements for it?
System should recommend at least 4-5 movies based on user search/watch history. What will be requirements for that? I am using django framework in my app. -
OperationalError: no such column: django-modeltranslation. Django
I have a working app in English. I have started translating tables and istalled django-modeltranslation. I have 11 similar pre-populated tables with the similar content. 8 tables have successfully migrated via python3 manage.py makemigrations and python3 manage.py migrate Migration of remaining 3 tables causes the same error for all three tables. django.db.utils.OperationalError: no such column: rsf_dirt.dirt_en django.db.utils.OperationalError: no such column: rsf_application.application_en django.db.utils.OperationalError: no such column: rsf_dirtproperties.dirtproperties_en All tables properly work via admin panel. Please help. models.py from django.db import models from django.utils.translation import gettext_lazy as _ class FP_sealing(models.Model): value = models.CharField(_('Material Sealing'), max_length=10) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Seal: " + self.value) class FP_ventil(models.Model): value = models.CharField(_('Backflush valve'), max_length=20) descr = models.CharField(_('Description'), max_length=200, default="") aufpreis_el_ventil = models.IntegerField(_('Extra Cost el.Valve'), default=0) def __str__(self): return("Ventil: " + self.value) class FP_motor(models.Model): value = models.CharField(_('Motor Power'), max_length=20) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Motor: " + self.value) class FP_material_geh(models.Model): value = models.CharField(_('Material Housing'), max_length=25) descr = models.CharField(_('Description'), max_length=250, default="") def __str__(self): return("Mat.Geh.: " + self.value) class FP_coating(models.Model): value = models.CharField(_('Coating'), max_length=25) descr = models.CharField(_('Description'), max_length=250, default="") def __str__(self): return("Coating: " + self.value) class FP_color(models.Model): value = models.CharField(_('External Color'), max_length=25) descr = models.CharField(_('Description'), max_length=200, default="") def __str__(self): return("Color: " + self.value) class … -
Django Forms with a field based on a Foreign Key
I'm working on a Django Form that add new instances of a Model. The Model itself have a ForeignKey instance. Let's say I wanna record all work shifts of each worker. My Model: class WorkShifts(models.Model): date = models.DateField() check_in = models.TimeField() check_out = models.TimeField() person_name = models.ForeignKey(Worker, on_delete=models.DO_NOTHING) And this is my Form: class AddWorkShifts(forms.ModelForm): date = forms.DateField(initial=datetime.date.today, input_formats=['%d/%m/%Y']) check_in = forms.TimeField() check_out = forms.TimeField() class Meta: model = WorkShifts fields = '__all__' def __init__(self, *args, **kwargs): super(AddWorkShifts, self).__init__(*args, **kwargs) self.fields['date'].widget.attrs['class'] = 'form-control' self.fields['check_in'].widget.attrs['class'] = 'form-control' self.fields['check_out'].widget.attrs['class'] = 'form-control' self.fields['person_name'].widget.attrs['class'] = 'form-control' My HTML code: <form method="POST"> {% csrf_token %} {{ form.date }}<br /> {{ form.check_in }}<br /> {{ form.check_out }}<br /> {{ form.person_name }} <button type="submit">Load</button> </form> And my view: def load_shifts(request): form = AddWorkShifts() if request.method == 'POST': form = AddWorkShifts(request.POST) if form.is_valid: form.save() context = {'form': form} return render(request, 'users/wshifts.html', context) At this point, everything works fine. Notice that form.is_valid doesnt have the () signs. But since I have so many persons (the Foreign Key), I configured a JS Autocomplete plugin (EaseAutoComplete) and redesign the form like this: <form align="center" method="POST"> {% csrf_token %} <input type="text" class="p_name" id="provider-file" /> {{ form.date }}<br /> {{ form.check_in }}<br /> … -
Django - navbar not showing properly while user logged in
I have a website with the following paths : urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='pages/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='pages/logout.html'), name='logout'), path('mydata/', user_views.mydata, name="data"), path('', include('mysite.urls')), ] each coding section in views directory is preceding by: from django.contrib.auth.decorators import login_required [...] @login_required def profile(request): [...] @login_required def mydata(request): [...] My problem is that I wish the user to be able to only see 'profile' and 'logout', not 'login' or 'register', the logic works with every path, except for /mydata and I can't figure out why. As for my HTML file the base.html looks like this: {% if user.is_authenticated %} <a class="nav-item nav-link" href="/profile">Profile</a> <a class="nav-item nav-link" href="/logout">Logout</a> {% else %} <a class="nav-item nav-link" href="/login">Login</a> <a class="nav-item nav-link" href="/register">Register</a> {% endif %} I include it in my mydata.html file like this: {% extends "pages/base.html" %} {% block content %} [...] {% endblock content %} My question is, is there any workarounds this, to make sure the user is authenticated @ /mydata, I am still relatively new, so your input is welcome. -
Embedding PDF works in IE, but not Chrome
I'm currently using Django to write a simple website, and on one of my pages I'm trying to embed a PDF in the page. The code is pretty simple: <object data="/media/pdfs/my_pdf.pdf" type="application/pdf" style="width:600px; height:750px"> </object> This works on Internet Explorer, but not Chrome. Also, this does work on Chrome if I use a PDF that's hosted online instead of from localhost. Does anyone know why this would be? -
Is my Django model organization involving a ManyToManyField and list_display efficient
I'm trying to modelise the projects undertaken by a company, where each project can have an arbitrary number of tags which relate to specific aspects of the project. An example would be a project whose language would be French, therefore the project would have a language tag whose value is french. However, any project can have an arbitrary amount of tags which point themselves to an arbitrary value. My goal is customizing the ModelAdmin of Django so that the list_view will display a column for each tag pointed to by the ManyToMany field of the project handled by said ModelAdmin Here's what I have so far models.py from django import models class Tag(models.Model): category = models.CharField(max_length=500, blank=False) value = models.CharField(max_length=500, blank=False) class Book(models.Model): name = models.CharField(max_length=500, blank=False) tags = models.ManyToManyField(max_length=500) admin.py @admin.register(Book) @admin.register(Tag) class BookAdmin(admin.ModelAdmin): list_display = ('name', 'tags') def tags(self, object): tags = object.tags.all() output = "" for tag in tags: output += "{0} : {1}".format(tag.category, tag.value) return output For now the solution only works for displaying all tags in one column. Any possible paths I could take to solve this problem ? -
How can i add phone number and data of birth to this signup from?
i want to add phone number and date of birth(dd/mm/yyy) for this form how can i add it? Views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .forms import * def home(request): context = {} return render(request, 'authenticationapp/home.html', context) def signup(request): signup_form = SignUpForm() if request.method == 'POST': signup_form = SignUpForm(request.POST) if signup_form.is_valid(): signup_form.save() user = signup_form.cleaned_data.get('username') messages.success(request, 'Hi'+ ' '+user+ ' ' +'Your Account Created Successfully...') return redirect('signin') context = {'signup_form':signup_form} return render(request, 'authenticationapp/signup.html', context) forms.py from .views import * from .models import * from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] signup.html <h1>SignUp</h1> <form method="POST" action=""> {% csrf_token %} {{ signup_form.as_p }} <input type="submit" name="SignUP"> </form> i want to add phone number and date of birth(dd/mm/yyy) for this form how can i add it? -
how to display the values from .py file in web browser using django?
I am having the .py file which is printing values in command prompt when I run but I need it to be print in web browser can anyone say how can I achieve this? my .py file is # Here using selenium for scraping # importing necessary modules import selenium.webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By # the relevant url url = 'https://web.bet9ja.com/Sport/SubEventDetail?SubEventID=76512106' driver = webdriver.Chrome(r"c:/Users/SATYA/mysite/chromedriver") driver.get(url) driver.implicitly_wait(10) # seconds elements = [ item.text for item in driver.find_elements_by_css_selector("div.SEOddLnk.ng-binding")] print(elements[0:6]) names = [ item.text for item in driver.find_elements_by_css_selector("div.SECQ.ng-binding")] print(names[0:2]) values = [ item.text for item in driver.find_elements_by_css_selector("div.SEOddsTQ.ng-binding")] print(values[0:6]) driver.quit() output coming in command prompt is: ['3.60', '4.20', '1.87', '1.83', '1.19', '1.25'] ['1X2', 'Double Chance'] ['1', 'X', '2', '1X', '12', 'X2'] My requirement is to get the same output in the web browser can anyone help me? -
'docker-compose up' hangs when attaching files for running Django server in virtualization
I'm trying to run Django inside a Docker container and connect to it using VS code remote, but it keeps hanging at the attach part. Here is my Dockerfile FROM registry.gitlab.com/datadrivendiscovery/images/primitives:ubuntu-bionic-python36-v2020.1.9 ENV PYTHONPATH=$PYTHONPATH:/app WORKDIR /app/ EXPOSE 8000 COPY requirements.txt /app/requirements.txt WORKDIR /app RUN pip install --upgrade pip RUN pip install -r requirements.txt CMD ["sh", "-c", "python3 /app/manage.py runserver"] COPY . . My docker-compose.yml version: '3' services: web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" I don't have a database setup so I don't have that in the yml. -
In Django how to querry High, Medium, Low in order?
I want to querry my priority data in order(Low, Medium, High) but it doesnt querry well views.py @allowed_users(allowed_roles=['teamleader']) def bug_list(request): bug = Bug.objects.all().order_by('priority') total = Bug.objects.all().count() content = { 'form_list': Bug.objects.all(), 'total': total, } return render(request, 'app/bug_list.html',content) models.py class Bug(models.Model): priority_choices=( ('Low','Low'), ('Medium','Medium'), ('High','High'), ) status_choices=( ('New','New'), ('Pending','Pending'), ('Fixed','Fixed'), ) bugtitle = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) priority = models.CharField(max_length=10, choices=priority_choices,null=True, blank=True) status = models.CharField(max_length=10, choices=status_choices,null=True, blank=True) developer = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) screenshot = models.ImageField(upload_to='screenshot', null=True, blank=True) deadline = models.DateField(auto_now=True,null=True, blank=True) comment = models.TextField(null=True, blank=True) def __str__(self): return self.bugtitle I have tried using dictionary but it still fails -
I want to display all the products related to one particular shop in Django?
Views.py matching_product = Product.objects.filter(shop__shop_slug=single_slug) return render(request, 'products/shop_products.html',{"part_ones":matching_product}) urls.py path("<single_slug>",views.single_slug, name="single_slug") shop_products {% for shops in matching_product %} shop.html (for url) <a href="{{shop.shop_slug}}"><strong>{{shop.shop_location}}</strong></a> It is not displaying any products -
What is the best way to get all linked instances of a models in Django?
I am trying to create a messaging system in Django, and I came across an issue: How could I efficiently find all messages linked in a thread? Let's imagine I have two models: class Conversation(models.Model): sender = models.ForeignKey(User) receiver = models.ForeignKey(User) first_message = models.OneToOneField(Message) last_message = models.OneToOneField(Message) class Message(models.Model): previous = models.OneToOneField(Message) content = models.TextField() (code not tested, I'm sure it wouldn't work as is) Since it is designed as a simple linked list, is it the only way to traverse it recursively? Should I try to just get the previous of the previous until I find the first, or is there a way to query all of them more efficiently? -
Django TypeError 'ChoiceField' object is not iterable
I have written this by amalgamating other suggestions, which I thought might work for the logic that I'm using to produce this Select field. I want the first in the dropdown to be pulled from the Student model, if it isn't null. If it is null, then display the options without an initial attribute. Template: schedule.html <section id="AddEventPopup"> <form> <select name="teacher" id="teacher_select"> {% for teacher in teacher_availability_form.teacher_select_options %} {{ teacher.tag }} {% endfor %} </select> </form> <button class="AddEventPopup_close">Close</button> </section> forms.py class TeacherAvailabilityForm(forms.Form): def __init__(self, *args, **kwargs): sid = kwargs.pop('sid') default_teacher = StudentProfile.objects.has_default_teacher(sid) TEACHER_CHOICES_QUERYSET = TeacherProfile.objects.available_teachers() names = [] for teacher in TEACHER_CHOICES_QUERYSET: teacher_id = teacher[0] teacher_name = teacher[1] + ' ' + teacher[2] teacher_tuple = (teacher_id, teacher_name) if teacher[0] == default_teacher: names.insert(0, teacher_tuple) INITIAL_TEACHER = teacher_tuple else: names.append(teacher_tuple) TEACHER_CHOICES = tuple(names) super(TeacherAvailabilityForm, self).__init__(*args, **kwargs) if default_teacher: self.teacher_select_options = forms.ChoiceField( label='Pick a Teacher', initial=INITIAL_TEACHER, choices=TEACHER_CHOICES, widget=forms.Select, required=True) else: self.teacher_select_options = forms.ChoiceField( label='Pick a Teacher', choices=TEACHER_CHOICES, widget=forms.Select, required=True) class Meta: fields = ('teacher_select_options',) views.py def schedule(request): studentid = request.user.id form = TeacherAvailabilityForm(sid=studentid) args = {'student_id': studentid, 'teacher_availability_form': form} return render(request, 'students/schedule.html', args) I'm thinking the init function is causing the error and is not generating the iterable output that I was aiming … -
Django: modify model’s field before saving
I have a model, course, with an ImageField and FileField so I’d like to create a folder each time the user create a course. I think I can do this before the model is saved so here is my question. How can I access a model’s fields in a method? Models.py Class Course(models.Model): Thumbnail = model.ImageField(upload_to=“...”,...) def save(self, *args, **kwargd): ... #How can I alter here the ImageField parameters? super().save(*args, **kwargs) -
How to add a custom serializer to Djoser token field when using Simple JWT?
In the Djoser docs they show you how to add custom serializers to various fields including token and token_create (djoser docs) however I can't seem to be able to add a custom serializer for the token field when using Simple JWT. -
Django FreedTDS: Adaptive Server is unavailable or does not exist
I'm trying to connect Django 3.0 with sql_server.pyodbc but I have next error: jango.db.utils.OperationalError: ('08S01', '[08S01] [FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist (20009) (SQLDriverConnect)') My DATABASES settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': '....', 'USER': 'sa', 'PASSWORD': '....', 'HOST': '....', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server' } } } Can you help me to find the bug, please? Is there another way to connect django wiht SQL Server?