Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django for tag doesn't work without a model
I want to use a for bucle in Django but with my own list (not using de model): This works great: {% for book in book_list %} {{ book.title }} {% endfor %} But this doesn't work: {% for book in ['Lord of the rings', 'Django for Beginners', 'Harry Potter'] %} {{ book }} {% endfor %} -
Checking if the filter-form is empty in django
I have a problem with filtering in Django. I have a database which I want to filter and return the result on the screen but when I submit empty filed it shows all the database. I would like to have an empty page when the user submit an empty filed and does not filter at all. I already used if not queryset but no difference. I appreciate your help. the View : def advanceFilter2(request): books = Setup2.objects.all() # filter setting form = ManipulationForm() filtering = Setup2Filter(request.GET, queryset=books) if not filtering: return render(request,'AdvanceFilter2.html') books = filtering.qs sprache = Setup2.sprache # if filtering: # return render(request, 'Test.html') context = {"filtering": filtering, 'books': books, 'form': form, 'sprache': sprache} if request.method == 'GET' and sprache != '&' : context.update({'post_output': request.GET.get('books','')}) return render(request, 'AdvanceFilter2.html', context) HTML file : {%load static%} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{%static 'testApp\Buecher.css'%}" type="text/css"> </head> <form method="get"> {{filtering.form}} <input type="submit" name="submit" value="Submit" /> </form> {% if request.GET.submit and filtering%} {%for i in books%} {{ i.sprache }} {%endfor%} {% endif %} ``` filter.py: `` import django_filters from .models import * class Setup2Filter(django_filters.FilterSet): class Meta: model = Setup2 fields = ['sprache'] forms.py: from .models import * from django.forms import ModelForm … -
Graphene-django api responds methos OPTIONS not allowed when POST is dent from React
I am following this tutorial to create a graphene-django endpoint, and everything seems fine (I can test the endpoint with graphene tool): from django.contrib import admin from django.urls import path from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView urlpatterns = [ path('admin/', admin.site.urls), path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True))), ] The problem comes when I try to send a POST from a React app: export const fetchApplicationComposite = async () => { const requestString = graphql_api_url; const form = { query: '{hello}', variables: null } try { const Response = await axios.post(requestString, form); return { data: Response.data, message: null }; } catch (Error) { return Error.message; } } This POST returns the following error: Request URL: http://localhost:8000/graphql Request Method: OPTIONS Status Code: 405 Method Not Allowed Remote Address: 127.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin I can't find a solution to this problem. -
I keep getting server error 500 and on debug = True, the actual error is "TemplateDoesNotExist at /createaccount/ Bootstrap4/uni_form.html"
I deployed my django app to heroku but I keep getting server error 500 and on debug = True, the actual error is that "TemplateDoesNotExist at /createaccount/ Bootstrap4/uni_form.html" when trying to open the 'login'and 'register' pages. TemplateDoesNotExist However, other pages are working that have specified links the url.py file. Here's my url.py file. from django.contrib import admin from django.urls import path , include from createaccount import views as c from myBlog import views as m from django.contrib.auth import views as auth_views urlpatterns = [ path ( 'admin/' , admin.site.urls ) , path ( '' , m.IndexView.as_view () , name='home' ) , path ( 'createaccount/' , c.createaccount , name='create' ) , path ( '' , include ( 'django.contrib.auth.urls' ) ) , path ( 'reset_password/' , auth_views.PasswordResetView.as_view ( template_name='myBlog/password_reset.html' ) , name='reset_password' ) , path ( 'reset_password_sent/' , auth_views.PasswordResetDoneView.as_view ( template_name='myBlog/password_reset_sent.html' ) , name='password_reset_done' ) , path ( 'reset/<uidb64>/<token>/' , auth_views.PasswordResetConfirmView.as_view ( template_name='myBlog/password_update.html' ) , name='password_reset_confirm' ) , path ( 'reset_password_complete/' , auth_views.PasswordResetCompleteView.as_view ( template_name='myBlog/password_reset_done.html' ) , name='password_reset_complete' ) , path ( '<slug:slug>/' , m.post_detail, name='post_detail' ) , ] Here's the files tree. -
Django application is not recognized when running
I am new to Django and I am following this tutorial: https://www.youtube.com/watch?v=1aJ49vtM3nQ&list=PLMyNvIPi_kYF8oUnMiyTk_M92gJz9WvZt&index=30 I added a new application called firstapp, but it seems like it is not recognized and i don't know why. I added it to the INSTALLED_APPS: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstapp', ] but when trying to import it only works if i add the main project in front of it: in which case i get an error when trying to run the server. in which case i get a "not found" error. I mention that I activated a virtual environment using Anaconda Prompt based on the tutorial, but I am not sure how to check if that is the problem. -
Pass Swagger-UI url in drf-spectacular settings
I have a project written in Django 2.x. I want to add automatic documentation to it using drf-spectacular. I'm using drf-spectacular=0.15.1 at the moment. I'm running my project in Docker, and the build context for my api container is set as the root folder of the api project. When I run the command to generate the schema, ./manage.py spectacular --file schema.yml, the script creates a schema.yml file in the root of my api project, but my Django settings.py are found one level below, in a folder called my_website. The structure of the project is like this: main-project \api \_my_website __init__.py apps.py settings.py urls.py schema.yml \client docker-compose.yml So in settings.py I added specific settings to tell Swagger-UI where from to take the schema, as specified in the drf-spectacular documentation: SPECTACULAR_SETTINGS = { 'SWAGGER_UI_SETTINGS': { 'url': 'schema.yml' }, } Once I try to access the swagger-ui url in my project to check that the schema is loaded there, I get the error: **Fetch error** Not Found schema.yml. I tried passing the schema url in various ways, for example through relative url ../schema.yml but that didn't work either. Maybe somebody can give me an idea of what I'm doing wrong. Thanks! -
How to design Models for Product and its Feature (Options) in Django for online store in right way?
I`m trying to create online store by myself (just a training project). There are models Product, Feature and ProductFeature. Product may have different features (every new product may have from zero to infinity specifications) with different values (so I need some flexiable solution). Features names could be same for different Product (for ex. color or size). In short: User choose existing option or add new option, then sets value for this feature. Profit) My Feature model stores only only names for options. I created ProductFeature to connect Product with Features and to set values. At first it looks ok. But in admin panel user has access to all objects (name-value) in ProductFeature. It looks a bit confusing. Are there any variants to hide existing options for new Product in admin panel (keep only add new databes record to ProductFeature)? Or maybe there are any other variants to design models and connections? class Product(models.Model): name = models.CharField(max_length=300, verbose_name='Название товара') description = models.TextField(verbose_name='Описание товара', blank=True) main_category = TreeForeignKey( Category, on_delete=models.CASCADE, related_name='main_products', verbose_name='Основная категория' ) main_image = models.ImageField(verbose_name='Изображение', null=True, blank=True) features = models.ManyToManyField( 'ProductFeature', related_name='product', verbose_name='Характеристики', blank=True ) created = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') updated = models.DateTimeField(auto_now=True, verbose_name='Дата изменения') class Feature(models.Model): name = models.CharField(max_length=300, … -
ValueError when loading the page with objects without image
I receive this error after creating a Bb object without image: "The 'image' attribute has no file associated with it." When I restart the debug server I get the same error until I provide Bb object with an image using django admin panel. Possible solution I came up with: add default static image: <img default="default.jpg"> But I want to know why there's an error even when null=True and blank=True are passed in models.py models.py: class Bb(models.Model): title = models.CharField(max_length=50, verbose_name='Product', error_messages={'blank' : 'Wrong product name'}) content = models.TextField(null=True, blank=True, verbose_name='Description') price = models.FloatField(null=True, blank=True, verbose_name='Current price') published = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Published in') # Image image = models.ImageField(verbose_name='Image', null=True, blank=True) views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import loader from django.urls import reverse_lazy, reverse from django.template.response import TemplateResponse from django.core.paginator import Paginator from .forms import BbForm, ImgForm, ImgNonМodelForm from .models import Bb, Rubric, Img def index(request): bbs = Bb.objects.all() # Paginator paginator = Paginator(bbs, 4) if 'page' in request.GET: page_num = request.GET['page'] else: page_num = 1 page = paginator.get_page(page_num) context = {'bbs' : page.object_list, 'page' : page} return TemplateResponse(request, 'bboard/index.html', context=context) def create_bb(request): if request.method == 'POST': form_bb = BbForm(request.POST, request.FILES) form_images = ImgNonМodelForm(request.POST, request.FILES) if … -
How do I get the form field name from a queryset list in django
I am trying to create a application which will have a list of tasks against which float values have to be entered, (something like a excel sheet). I am unable to map the name of the form field to the desired value. Here is the code which I have written so far. Models.py class SubTask(models.Model): subtask_id = models.IntegerField(default=0, blank=True, null=True) subtask_name = models.CharField(max_length=120, null=False) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return self.subtask_name class Attendance(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subtask = models.ForeignKey(SubTask, on_delete=models.CASCADE) value = models.FloatField(default=0.0) non_billable_hours = models.FloatField(default=0, blank=True, null=True) billable_hours = models.FloatField(default=0, blank=True, null=True) total_hour = models.FloatField(default=0, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse("attendance", kwargs=None) Forms.py from django import forms from .models import Attendance, SubTask class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['subtask'] #'non_billable_hours', 'billable_hours', 'total_hour',] def __init__(self, *args, **kwargs): user = kwargs.pop('user', '') super(AttendanceForm, self).__init__(*args, **kwargs) self.fields['subtask']=forms.ModelChoiceField(queryset=SubTask.objects.all()) self.fields['value']=forms.FloatField() Views.py from django.shortcuts import render from .forms import AttendanceForm from .models import SubTask, Attendance def attendanceView(request): form = AttendanceForm(request.POST or None) subtask_list = SubTask.objects.all() context = { 'form': form, #'subtask_list': subtask_list, } if form.is_valid(): attendance = form.save(commit=False) attendance.user = Attendance.objects.get(user=request.user) attendance.save() return render(request, "attendance/attendance.html", context) I want the app to look … -
Not Found: /post/12/responses/
What i am trying to do is i want to access perticular posts all comments in Responses Url. This is my view which i want pass to url class CommentDetailView(DetailView): model = Comments template_name = 'CovidHelp/comment_response.html' context_object_name = 'comments' paginate_by = 10 def get_queryset(self): post = get_object_or_404(Post, id=self.kwargs.get('pk')) return Comments.objects.filter(post=post).order_by('-date') Url is path('post/<int:pk>/responses/', CommentDetailView.as_view(), name='responses') comment models is class Comments(models.Model): post = models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE) name = models.CharField(max_length=50) date = models.DateTimeField(default=timezone.now) content = models.TextField() def get_absolute_url(self): return reverse('Home') post model is class Post(models.Model): title = models.CharField(max_length = 100) content = models.TextField() date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Althought i am getting post_id from url which i can see in error Not Found: /post/12/responses/ But My comments Models not able to show it Need Help.. -
Django route with multi string parameters
I have two separate route re_path( r"something/(?P<slug>name_one|name_two)/$", views.SomeView.as_view(template_name='some_template.html'), name='something' ), re_path( r"something/(?P<slug>name_one|name_two)/(?P<params>p_one|p_two)/$", views.SomeView.as_view(template_name='some_template.html'), name='something_extera' ), I want these route accepts specific string as far as you can see in route above. for example something/name_one something/name_two something/name_one/p_one something/name_one/p_two ... but i get error django.urls.exceptions.NoReverseMatch: Reverse for 'something' with arguments '('',)' not found. 1 pattern(s) tried: ['something/(?P<slug>name_one|name_two)$'] -
Django User model throws duplicate key value violates unique constraint "user_user_username_key" on user creation
I am testing my user model to see if it's signal works correctly however, I am getting an error: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "user_user_username_key" DETAIL: Key (username)=() already exists. Currently my test is: class UserTestCase(TestCase): obj1 = None obj2 = None def setUp(self): self.obj1 = User.objects.create(first_name="james", last_name="adams", email="jamesadams@gmail.com") self.obj2 = User.objects.create(first_name="amy", last_name="", email="12amy_123jackson@hotmail.com") And my signals file is: @receiver(pre_save, sender=User, dispatch_uid="set_username_of_user") def set_username(sender, instance, **kwargs): """ Every time a user is saved, ensures that user has a certain username This method avoids users having username field set to null """ if not instance.username: email = instance.email email_without_domain = email[:email.find("@")].replace("-","_").lower().strip()[:20].replace(' ','') username = create_username(email_without_domain) print(username) if User.objects.filter(username=username).exists(): while User.objects.filter(username=username): username = create_username(email_without_domain) instance.username = username instance.save() I can confirm that the signal is being called however, it still throws that error. What could be causing this issue? -
How can I start and view a zoom meeting with python Django and zoom api?
I'm trying to create a LMS system with Django and I need to be able start and view zoom meetings from the website using zoom api. I found a python library called zoomus for python to connect to the api but they don't give any documentation. does anyone have an idea how to do this ? Thank you! -
Unable to locate react static files when running collectstatic in python and uploading to heroku
I'm trying to add a Django backend and a react frontend to Heroku. Following this tutorial. I'm using whitenoise for serving static files. When runnning python manage.py collectstatic I keep getting the same error: django.core.exceptions.SuspiciousFileOperation: The joined path (C:\Users\Obenheimer\Documents\combined_connect\static\media\background-pattern.f6347303.png) is located outside of the base path component (C:\Users\Obenheimer\Documents\combined_connect\staticfiles) This command is also run by heroku python hooks when deploying. The python hook runs after the react hook, so the react build folder is definitely there. For testing purposes I also ran build locally for when I call the collectstatic command. The problem is something to do with how I'm defining static roots, but for the life of me I can't figure it out. I've used multiple tutorials, the django docs on static files, and the heroku dev docs on static files. Why is it looking for my media files (background-pattern.png etc.) in static? On collectstatic everything gets put into the staticfiles directory. No matter what I change the file names or variables to, that error about the lookup conflict between staticfiles and static always happens. Here's how I'm defining them: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], # pointing to … -
How to explicitly instruct PyTest to drop a database after some tests?
I am writing unit-tests with pytest-django for a django app. I want to make my tests more performant and doing so is requiring me to keep data saved in database for a certain time and not drop it after on test only. For example: @pytest.mark.django_db def test_save(): p1 = MyModel.objects.create(description="some description") # this object has the id 1 p1.save() @pytest.mark.django_db def test_modify(): p1 = MyModel.objects.get(id=1) p1.description = "new description" What I want is to know how to keep both tests separated but both will use the same test database for some time and drop it thereafter. -
Auto Refresh Token Middleware for Django Graphql
I am trying to build a site using React with Apollo Client on the frontend and Django GraphQl on the backend and I am using django-graphql-auth with jwt token to handle authentication. Now I am trying to write a middleware with gets access and refresh token through http headers and I want to refresh the tokens if the access token is expired using the refresh token. I was able to do the basic steps like get the access and refresh token from the request, but couldn't able to figure out how to refresh access token. def refreshTokenMiddleWare(get_response): # this middleware functionality is check the validity of the # token and if the access token is expired then the access token # is refreshed and set the appropriate headers def middleware(request): # implement the logic # get token and refresh token AUTH_HEADER = request.headers.get('authorization') refreshToken = request.headers.get('X-Refresh-Token') token = get_http_authorization(request) # check if the tokens are valid try: payload = jwt_settings.JWT_DECODE_HANDLER(token) except jwt.ExpiredSignature: pass except jwt.DecodeError: raise exceptions.JSONWebTokenError(_('Error decoding signature')) except jwt.InvalidTokenError: raise exceptions.JSONWebTokenError(_('Invalid token')) # check if token is expired # refresh token # add appropriate headers response = get_response(request) return response return middleware I couldn't able to figure out … -
Variable not updating along other attributes in template
I'm writing a webapp that pings a list of IP's retrieved from a model in the app. The issue I'm having is when the code that pings the IP and stores its status code (Either 0, 256, or 512) in a variable, the template just takes the last stored value and displays that. Here's my code: models.py from django.db import models # Create your models here. class NewServer(models.Model): name = models.CharField(max_length=200) ip = models.CharField(max_length=200) def __str__(self): return self.ip return self.name views.py from django.shortcuts import render from django.http import HttpResponse from .models import NewServer import os # Create your views here. def index(request): servers = NewServer.objects.order_by('id') for ids in servers: #get object from NewServer get_server = NewServer.objects.get(id=ids.id) #setup the ping command, with the IP being #grabbed from get_server.ip ping = "ping -c 1 " + get_server.ip + " > /dev/null" #set/run command to the status_code variable status_code = os.system(ping) #for debugging purposes: sstring = f"{get_server.name} is: {status_code}" print(sstring) context = {'servers':servers, 'status_code': status_code} return render(request, 'monitor/index.html', context) index.html {% extends 'monitor/base.html' %} {% block content %} <table> <tr> <th> Server Name: </th> <th> Status: </th> <th> Up/Down </th> </tr> {% for server in servers %} <tr> <td>{{server.name}}</td> <td>{{server.ip}}</td> {% if status_code … -
NGINX and Django (Can't load Django app after server reboot)
I'm just experimenting around at the minute getting use to Django which is fully installed on my VPS. Everything has been working fine, but I needed to reboot my server - After rebooting, the default NGINX (Welcome to Redhat Enterprise) page appeared again. I just wanted to pick people's brains with what people believe is the most suitable way to load in a custom NGINX conf.d file after a server reboots? Within the /etc/nginx/conf.d I do have a custom service file configured which worked as intended before my server was rebooted. The custom service file directs traffic through proxy_pass to the default location of where my app.sock file is located. After rebooting my server, I noticed that the default NGINX (Welcome to Redhat Enterprise) was displaying. After doing a little digging, I found a solution whereby a gentleman recommended that it would be a good idea to comment out the default server within the nginx.conf file. (Which did work and my Django app did reppear) - However, is this the most suitable way to default the nginx server to the server I have specified within my custom conf.d service file? Thanks, Jay -
How to filter active users connected using an extended model class field
I have extended the user model to a model class 'Student' using OneToOne relation. Now I want to filter all active students with a field in the 'Student' class such as 'name'. Tried this in django shell: Student.objects.filter(user.is_active == True) Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'user' is not defined my View: def entry(request): user = request.user if request.user.is_active: print("Already logged in") return redirect('home') else: return render (request, 'entry.html') my Models: class Student(models.Model): name = models.CharField(max_length=200) branch = models.CharField(max_length=200, choices=BRANCHES) sem = models.CharField(max_length=200, choices=SEMESTERS) reg_no = models.CharField(max_length=200, unique = True) balance = models.IntegerField(default=0) pin_no = models.CharField(max_length=200, unique = True) college = models.ForeignKey(Institute, on_delete=models.CASCADE ) user = models.OneToOneField(User, on_delete=models.CASCADE) -
wrong attributes for <pdf:font> xhtml2pdf
I am trying to specify a font for my xhtml2pdf file. By i get this error wrong attributes for <pdf:font> I am not sure the correct way to specify the attributes for the font? I have tried searching for a solution to this, but can't find anything. <!DOCTYPE html> <html> <style> @import url('https://fonts.googleapis.com/css2?family=Itim&display=swap'); </style> <style> @media print { .pagebreak { page-break-before: always; } /* page-break-after works, as well */ } @page { size: a4; margin: 1cm; @frame footer { -pdf-frame-content: footerContent; bottom: 0cm; margin-left: 9cm; margin-right: 9cm; height: 1cm; } @font-face { font-family: 'Itim', cursive; src: url('https://fonts.googleapis.com/css2?family=Itim&display=swap'); } </style> <body> <p style="font-size:1.3rem;font-family: Itim,sans-serif;">We have generated your PDF!</p> </body> -
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/task-list/
I'm working on a vuejs and django rest single page application. the problem is so clear, that I'm getting the Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource error. My vuex code be like: mutations:{ addTask: function(){ axios({ url: 'http://127.0.0.1:8000/api/task-list/', method: 'POST', headers: { 'X-CSRFToken': getCookie('csrftoken') } }).then(response => { console.log(response.data); }).catch(err => { console.log(err.response); }) } }, and my django rest urls.py, in my django application urls: urlpatterns = [ path('task-list/', TaskList.as_view()), path('task-create/', TaskCreate.as_view()) ] and my main app urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('task.urls')), path('api/', include('authentication.urls')), path('home/', returnHome) ] my views.py code: class TaskList(APIView): def get(self, request): tasks = Task.objects.all() serialized = TaskSerializer(tasks, many=True) return Response(serialized.data, status=200) my vue app is running on http://localhost:8080, so I installed django cors headers, configured it like the below code: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # rest api 'rest_framework', 'rest_framework.authtoken', 'corsheaders', # my apps 'authentication', 'task' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8080' 'https://localhost:8080' ] Although, I'm still getting the Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/task-list/. (Reason: CORS request did not succeed) Error! I … -
Django models DB queries optimisation (using select_related / prefetch_related). run 1-2 queries instead of multiple queries
I have this one-to-many relation models [each domain can have several kpis]. i use MySQL DB. class Domains(models.Model): class Meta: managed = True db_table = 'edison_domains' id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) display_name = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) class Kpis(models.Model): class Meta: managed = True db_table = 'edison_kpis' id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, unique=True) MORE FIELDS... domain_id = models.ForeignKey(Domains, on_delete=models.CASCADE, db_column='domain_id') What i want is to present for each domain, the list of its KPIs. I tried lots of combinations of select_related and prefetch_related but it always end up that the DB perform a query for each domain, instead of 1 or 2 queries. I tried to read about it here. My main goal is to reduce the number of DB calls and improve the overall performance time. My current code: (views.py) class DomainsAndKpisDescriptionsPage(View): def __init__(self): self.resource = 'domains_kpis_descriptions' def get(self, request, *args, **kwargs): final_list = [] domains_list = Domains.objects.all().prefetch_related('kpis_set').order_by('display_name') kpis = Kpis.objects.select_related('domain_id').values('id', 'display_name', 'number_display_format', 'description', 'calculation_type').order_by('display_name') for domain in domains_list: # For each domain, get all related KPIs domain_kpis = kpis.prefetch_related('domain_id').filter(domain_id=domain.id).order_by('domain_display_order') final_list.append({'name':domain.name, 'display_name':domain.display_name, 'description':domain.description, 'kpis':domain_kpis}) context = {'domains_and_kpis_data':final_list} return render(request, 'tests_details/domains_kpis_descriptions.html', context=context) And my HTML template <div class="row"> <div class="col-lg-3 col-xlg-2 col-md-4"> <div class="stickyside"> <h3> Domains … -
Django settings settings module programmatically at runtime based on environment
I have a dev and prod environment, I am trying to programmatically assign the settings module based on an environment variable DEV so fat my settings have the following structure: project --settings ----__init__.py ----common.py ----dev.py ----prod.py inside my __init__.py I have: import os if os.environ['DEV_ENV']: os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.dev' else: os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings.prod' However, when I run python3 manage.py migrate I get this error: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. however if I run with --settings flag manually, it works python3 manage.py migrate --settings=project.settings.dev -
Django Foreign key to not loaded object
Hello I have a problem that I want to link foreign key to model's related object in other words I want to link foreign key to not loaded object's fields. class Category(models.Model): ... filter_option_content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, limit_choices_to=( models.Q(app_label='catalog', model='FrameSize') | models.Q(app_label='catalog', model='ShoeSize') | models.Q(app_label='catalog', model='ClothSize') ), null=True) ... class Product(models.Model): ... category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) ... class ProductItem(models.Model): ... model = models.ForeignKey(Product, verbose_name='Модель', on_delete=models.CASCADE, related_name='productitem') size = models.ForeignKey('model.category.filter_option_content_type', on_delete=models.SET_NULL, null=True) ... And sure i got this error: ValueError: Invalid model reference 'model.category.filter_option_content_type'. String model references must be of the form 'app_label.ModelName' is it possible to do relation like this wtihout using GenericForeignKey instead of ForeignKey? -
How do i remove html tags in tinymce
How do I remove HTML tags which show in my browser as a result of being entered in the django administration using timymce