Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customizing django admin panel
So I have a very simple and new Django site up and running, and I'm really wanting to customize the look of the admin panel. I would basically like it to extend from my base.html. I have read the docs on Overriding admin templates but it hasn't quite answered my question as I don't believe the file I am looking for (base.html) is listed in their files that you're able to override. I've done the only thing I had in mind which was copying the templates/admin/base.html and pasting it in my own templates/admin directory, extending my base, and removing their header sadly this is what I got from that, which is close but not really. -
Django deploy to Heroku No module named 'django_heroku'
I'm tryin to deploy to Heroku and before this error I was getting: ModuleNotFoundError: No module named 'django-tables2' Then I installed django-heroku via pip install django-heroku, followed the instructions on how to set it up. I disabled the collect static for heroku pushed my master branch and everything is fine, but once I do: heroku run python manage.py migrate I get the: ModuleNotFoundError: No module named 'django_heroku' the complete traceback is this: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 225, in close_all for alias in self: File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 219, in __iter__ return iter(self.databases) File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File … -
Submiting a form using JavaScript in Django is not working
I try to submit a form by Javascript in Django. The form is working The Javascript is working The submit() function is not working. My testing HTML code: <form method="post" id='testForm' action="www.google.com"> {% csrf_token %} <a onclick="onDeleteButtonClick()" href="">Delete</a> <input type="submit" value="Submit"> </form> My testing Javascript code: <script type="text/javascript"> function onDeleteButtonClick(){ console.log("before"); document.getElementById("testForm").submit(); console.log("after"); } </script> 3 Results: This part of the web page looks like this: enter image description here Really simple A When I click the Submit button: It is working, the form is been submit. B When I click the delete link: It is not working. The log in Javascript works, I can see "before" and "after" in the console. C I also test this on a normal web page (without Django framework), the Submit button, and the Delete link is all working. So I think it must be something related to Django. If anyone knows why this happened, please let me know~ Thank you! -
My css file doesn't work properly on my django template! How can I fix it?
Hello everyone I have a question about the css file working with django template. I don't know why but I have done several projects with django and the problem is that sometime the css file didn't work properly on my django template. When I made change on the css file and I reload the browser page nothing happend but when I restart my computer or turn off and turn on again the things that I changed on the css file now happen and if I make some changes again the css file and reload the browser, nothing happen again unless I restart my computer or turn off and turn on again. This problem happened to me quit often, I have no idea what's wrong with django. How can I fix it? This is my setting.py file """ Django settings for beyDimensions project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # 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 … -
django.urls.exceptions.NoReverseMatch: 'courses' is not a registered namespace
I have a problem since I tried to use get_absolute_url(self): to enter in a url beyond a photo. When I used , my index.html stopped running. Here I have the top level url.py from django.contrib import admin from django.urls import path, include from simplemooc.core import views, urls from simplemooc.courses import views, urls from django.conf import settings from django.conf.urls.static import static urlpatterns = [path('admin/', admin.site.urls), path('', include(('simplemooc.core.urls', 'simplemooc'), namespace='core')), path('cursos', include(('simplemooc.courses.urls', 'simplemooc'), namespace='courses'))] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here courses/url.py from django.urls import path from simplemooc.courses import views urlpatterns = [path('', views.index, name='index'), path('/<slug:slug>/', views.details, name='datails')] Here courses/model.py from django.db import models from django.urls import reverse class CourseManager(models.Manager): def search(self, query): return self.get_queryset().filter( models.Q(name__icontains=query) | \ models.Q(description__icontains=query) ) class Course(models.Model): name = models.CharField('Nome', max_length=100) slug = models.SlugField('Atalho') description = models.TextField('Descrição Simples', blank=True) about = models.TextField('Sobre o Curso', blank=True) start_date = models.DateField( 'Data de Início', null=True, blank=True ) image = models.ImageField( upload_to='courses/images', verbose_name='Imagem', null=True, blank=True ) created_at = models.DateTimeField( 'Criado em', auto_now_add=True ) updated_at = models.DateTimeField('Atualizado em', auto_now=True) objects = CourseManager() def __str__(self): return self.name def get_absolute_url(self): return reverse('courses:datails', (), {'slug': self.slug}) class Meta: verbose_name = 'Curso' verbose_name_plural = 'Cursos' ordering = ['name'] And here courses/views.py from django.shortcuts import render, get_object_or_404 … -
Docker can't open file to run the python application in a container with django using docker-compose
I'm new to Django. I want to run the code of the example at https://github.com/wsvincent/djangoforprofessionals/tree/master/ch1-hello. The container is created but it doesn't run because it got interrupted since Docker can't start the application showing the following error. Creating ch1-hello_web_1 ... done Attaching to ch1-hello_web_1 web_1 | python: can't open file '/code/manage.py': [Errno 2] No such file or di rectory ch1-hello_web_1 exited with code 2 I'm using a Windows with windows 7 professional, therefore I have the Docker Toolbox working fine with other dockerized apps. I accessed the docker image and confirmed the file is in the container. So I would like to know if it could be Linux permissions when Docker tries to access the file. The folder /code inside the docker image: -rwxr-xr-x 1 root root 361 Apr 23 02:11 Dockerfile -rwxr-xr-x 1 root root 157 Apr 11 21:31 Pipfile -rwxr-xr-x 1 root root 1624 Apr 11 21:31 Pipfile.lock -rwxr-xr-x 1 root root 131072 Apr 11 21:31 db.sqlite3 -rwxr-xr-x 1 root root 103 Apr 23 02:11 docker-compose.yml drwxr-xr-x 2 root root 4096 Apr 23 00:38 hello_project -rwxr-xr-x 1 root root 633 Apr 11 21:31 manage.py drwxr-xr-x 3 root root 4096 Apr 23 00:38 pages [1]: https://i.stack.imgur.com/u3KEn.png Screenshot of the … -
Not able to connect to Amazon RDS from EC2 Django Instance
I was deploying my Django Project on AWS (this is my first time doing this) after a lot of first time learning i got stuck at an error : django.db.utils.OperationalError: (2005, "Unknown MySQL server host '****.*****.us-east-2.rds.amazonaws.com' (0)") When i tried migrating my Django Project.I tried multiple solutions but none worked. I tried command mysql -u username -p password -h ****.********.us-east-2.rds.amazonaws.com but this also returned and error. ERROR 2005 (HY000): Unknown MySQL server host '*****.*********.us-east-2.rds.amazonaws.com' (2) If you require any log or information please feel free to ask in the comments. Thanks -
Python Django web application hosted on Apache 2.4.41 , doesn't navigate to other pages
I followed the steps of hosting the Python Django application in Apache 2.4.14. from the below link https://www.codementor.io/@aswinmurugesh/deploying-a-django-application-in-windows-with-apache-and-mod_wsgi-uhl2xq09e Everything went well, apache is running and my application opened at . But when I have to navigate to another page by clicking a button the URL changes to the localhost/secondpage but the secondpage.html is not displayed but displays "This site can't be reached. Should there be mapping for the URLs for the secondpage to show? -
Django Apache configuration stati files
I've a little issue about the configuration of Django and Apache on AWS Lightsail. I followed this guide: https://aws.amazon.com/it/getting-started/hands-on/deploy-python-application/ point 5) Host the application using Apache I configured all the files just like this guide (obviously using the name of my prj instead of "template") It's working everything, except the static files: I mean, I just see my website without any css/img/js.. Have I add something in urls.py? in settings.py? I tried everything... How can I configure correctly Apache? For me it's the first time dealing with Django and Apache, and I cannot find a guide that works for my situation. This is my tree of the prj: tree-prj-img Thank you, Manuel -
User matching query does not exist :Django
i am making a custom user login authentication system. i am getting error User matching query does not exist . i think that's come from ORM while fetching the query but i am not pretty sure why query does not exit while user matching. it would be great if anybody could me out what i am trying to solve. thank you so much in advance. here below is my working code; class LoginAPIView(APIView): def post(self, request, format=None): #gather the username and password provided by user data = request.data email = data['email'] user_password = data['password'] user_entered_password = user_password salt = "5gz" db_password = user_entered_password + salt hash_password = hashlib.md5(db_password.encode()) print(hash_password.hexdigest()) user_queryset = User.objects.all().get(Q(email__exact=email) & Q(password__exact=hash_password.hexdigest())).first() # user_ser = UserLoginSerializers(user_queryset,many=True) # user_data = user_ser.user_queryset user_id = [] for u in user_queryset: _id = u.get('id') user_id.append(_id) if len(user_queryset) > 0: print(user_id) payload ={'user_id':user_id[0], 'exp':datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS)} jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) return Response({'token':jwt_token, "data":user_queryset}, status=status.HTTP_200_OK) else: return Response({"msg":"Invalid User"}, status=status.HTTP_400_BAD_REQUEST) -
Why is my Query not working? 'Exception Value: Cannot use QuerySet for "Conversation": Use a QuerySet for "Profile" '
I am attempting to query Conversation, which has a many to many field called members. I am doing this so that I can then pass Conversation to my InstantMessage object because that object has a foreign key called conversation that attaches to Conversation. I need to check if members are apart of Conversation first, and then if so, get, or if not, create, and then pass that into my InstantMessage object. But for some reason, I am not able to query it and I don't understand why. error Exception Value: Cannot use QuerySet for "Conversation": Use a QuerySet for "Profile". views.py/message def message (request, profile_id): other_user = get_object_or_404(Profile,id=profile_id) members = Conversation.objects.filter(members= request.user).filter(members= other_user) conversation, created = Conversation.objects.get_or_create( members = members) if request.method == 'POST': form = MessageForm(request.POST, instance= request.user, sender=request.user, conversation = conversation, message=message, date=date) if form.is_valid(): form.save() return redirect ('dating_app:messages.html') else: conversation, created = Conversation.objects.get_or_create( members= [request.user, other_user]) form = MessageForm(instance= request.user, sender=request.user, conversation= conversation, message=message, date=date) context = {'form' : form } return render(request, 'dating_app:messages.html', context) models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must … -
Python framework for CLI development
Need to write python CLI scripts - basic functionalities include - expose REST APIs, consume REST APIs, connect to Oracle/sql-server etc.Hooking onto a front end is not an immediate requirement - but its a possibility. Checked here, here etc. - came to realize that there is no file structure which is universally accepted. Checked various frameworks like click, cement, django, flask etc. - kind of decided on django(as may need to hook a front-end later in time).Here are my concerns: Is it an overkill to use django for CLI development Do we get all features of django(like ORM etc.) if we choose to run from CLI(without web server) If I start with click(for example), how difficult will it be to hook front end in future Please advice. -
Checking if user exists in django table once when looping through values
I have a table where I query all the objects into 'test' in views def book_module(request): test = books.objects.all() and in html, I'm trying to check whether user exists once inside of it. The issue I'm running into is that it is instead printing out every time it finds it inside the table.. table example user col1 col2 col3 test 1 1 1 test 1 1 1 test_2 1 1 Here is my html code. If the current user = 'test' {% for item in test %} {% if item.user == user %} //if user exists in table once, value= "True" <p>Checking if user exists in table.<input type="text" id="exists" value= "True" readonly></p> {% elif item.user !== user %} //if user does not exist in table once, value= "False" <p>Checking if user exists in table.<input type="text" id="exists" value= "False" readonly></p> {% endif %} {% endfor %} If the current user = 'test', I would get 3 outputs, but I'd only like one. Checking if user exists in table. Checking if user exists in table. Checking if user exists in table. I also attempted to use if in, but nothing returned. {% if user in test.user %} <p>Checking if user exists in … -
Set default value to reference own relationship in django migrations
I am updating a Picture model to add additional information and need to set some default values. When the migration runs, I want to populate the DB with some reasonable default values which can be obtained from the user within it. These are my models: class User(models.Model): ... company = ForeignKey(Company, on_delete=models.CASCADE) ... class Picture(models.Model): ... user = ForeignKey(User, on_delete=models.CASCADE) company = ForeignKey(Company, on_delete=models.CASCADE) # New field being added ... The Picture would belong to a company even if the user changes companies. When making migrations, Django wants to know a default value for the company field on Pictures. Is there a way to tell it to look at the Pictures user and use the company that user has? -
Nginx caching of uwsgi served static files
The django project is deployed using uwsgi as application server, it also serves static files from a specified directory(as shown in the below command) and nginx is used as reverse proxy server. This is deployed using docker. The uwsgi command to run the server is as follows: uwsgi -b 65535 --socket :4000 --workers 100 --cpu-affinity 1 --module wui.wsgi --py-autoreload 1 --static-map /static=/project/static; The application is working fine at this point. I would like to cache the static files into nginx server. So i have referred blog https://www.nginx.com/blog/maximizing-python-performance-with-nginx-parti-web-serving-and-caching and i have included following configuration in my nginx.conf : location ~* .(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg |jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid |midi|wav|bmp|rtf)$ { expires max; log_not_found off; access_log off; } After adding this into my Nginx conf, the Nginx server container exits with the following error: [emerg] 1#1: invalid number of arguments in "location" directive in /etc/nginx/nginx.conf:43 Is this how uwsgi served static files can be cached into nginx? If yes please suggest me what is gone wrong here. My complete nginx.conf is as follows: events { worker_connections 1024; ## Default: 1024 } http { include conf/mime.types; # the upstream component nginx needs to connect to upstream uwsgi { server backend:4000; # for a web port socket (we'll use this … -
Creating <select> element and populating it with variable options
I am using django and I have a template where I have a list of variables. If I wanted to create a select box with HTML I'd easily do it it like this: <select id="maid{{room.id}}" name="maid"> {% for maid in maids %} <option value="{{maid.id}}"> {{maid.first_name}} {{maid.last_name}}</option> {% endfor %} </select> But if I create select element with jquery: var select=$('<select>').appendTo('#....'); What is the best way to populate it with variable options? Thank you. -
Django rendering html tags
Struggling a bit here with the html tags confused on where I am going wrong. So I have create a model cart so I trying to view it and I am not getting any errors but the view is just not rendered here is the model.py of the cart class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CartManager() def __str__(self): return str(self.id) below is now then the view.py def cart_home(request): cart_obj = Cart.objects.new_or_get(request) cart = {"cart": cart_obj} return render(request, 'carts/home.html', cart) Now below is the html page for the cart that I am trying to render out {% extends "base.html" %} {% block content %} <h1> Cart </h1> {% if cart.products.exits %} <table class="table table-dark"> <thead> <tr> <th scope="col">#</th> <th scope="col">Product Name</th> <th scope="col">Product Price</th> </tr> </thead> <tbody> {% for products in cart.products.all %} <tr> <th scope='row'>{{ forloop.counter }}</th> <td>{{ product.name }}</td> <td>{{ product.title}}</td> </tr> {% endfor %} <tr> <td colspan='2'>2</td> <td><b>Total</b></td> </tr> </tbody> </table> {% else %} <p class='lead'>Cart is empty</p> {% endif %} {% endblock %} when I go to the url where I have that html tag I get cart … -
Pyscopg2 Module Not Found
I hope someone can help me to resolve this issue. I have a webapp developed in Django with postgresql, the app is working properly in my local pc, the issue started when i migrate the code into a server. I have a Windows Server 2019 core, and after configure the IIS to serve this app, appear the following issue: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Python\Python38\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' I have installed the connector "psycopg2" and also i already tried all that i found in "google" but i couldnt fix that issue. SO i dont know if i forgot configure something in the IIS or what is happening here because if i open the python console or django shell and import the PSYCOPG2 the connector is imported successfully. Thanks and Regards. -
No moudle named roocket
hello guys i have a problem with a tutorial which im seeing since qurantine has started and i really need a big help into solving it. story is i lost some of my files or accidently deleted them , so i used the files for the project which they have into zipfiles but for this projects i keep getting this error while im trying to run local server this is the error after using py manage.py makemigrations (( its a big error so i just copied end of it )) File "c:\users\navid\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'roocket'``` i think it must be something with bootstrap so i started to see if bootstrap is installed or not and the results for the project directory are: `asgiref==3.2.7 astroid==2.3.3 beautifulsoup4==4.9.0 colorama==0.4.3 Django==3.0.5 django-bootstrap4==1.1.1 django-jalali==3.3.0 django-jalali-date==0.3.1 isort==4.3.21 jdatetime==3.6.2 lazy-object-proxy==1.4.3 mccabe==0.6.1 psycopg2==2.8.5 pylint==2.4.4 pytz==2019.3 six==1.14.0 soupsieve==2.0 sqlparse==0.3.1 wrapt==1.11.2` -
Django validate_unique method all ready exists message
Thinking How to get the instance pk that exists during validate_unique? it is not a good practice to overwrite the method validate_unique and I don't know if it would be correct to validate unique fields in the clean() method. but imagine the following situation: you want to show admin users which is the instance that already exists so they can edit it if they want, I think it would be more intuitive when working with thousands of data. the following code is just an example - think about it as a pseudocode although I tried it and it works, I know it could be better def clean(self): lockup ={} unique_togethers = self._meta.unique_together[0]#these could throw an error for field in unique_togethers: f = self._meta.get_field(field) value = getattr(self, f.attname) if value is None: continue if f.primary_key and not self._state.adding: continue lockup[str(field)] = value qs = snippet.objects.filter(**lockup) if qs.exists and self._state.adding: raise ValidationError( format_html('''this object all ready exist plese edit it on <a href="{}">Edit</a>''', reverse('admin:testing_snippet_change', args=(qs[0].pk,)))) Is this approach correct, how to apply it to the validation_unique method to works in all unique validations? Result -
Get the dropdown data and update the data in Django
dear all of django developer , i having facing this below issue . i try to update this db table data where has one field and one drop down field data , i getting basic field data . but not get the drop down list data . i request expert for help me the issue . Advanced Thanks For All views.py def update_brands(request, id): brand = Brand.objects.get(id=id) form = AddBrandForms(request.POST, instance=brand) if form.is_valid(): form.save() return redirect('/parts/brands') return render(request, 'parts/edit_brands.html', {'brand': brand }) edit_brands.html {% extends 'parts/base.html' %} {% block content %} <form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form"> {% csrf_token %} <div class="form-group row"> <label class="col-sm-2 col-form-label">Country Name:</label> <div class="col-sm-4"> <input type="text" name="country" value="{{ brand.brand_name }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Country Name:</label> <div class="col-sm-4"> <select id="cars" name="cars"> {% for db in dbf.all %} <option value="{{ db.db}}">{{ db.db}}</option> {% endfor %} </select> </div> </div> <button type="submit" class="btn btn-success">Submit</button> </form> {% endblock %} -
Why form.is_valid() does not returns false immediately when the first clean_<field_name> raises ValidationError?
I have defined a form with two CharField. I have defined clean method for both fields. In my view i am calling is_valid() method of the form I defined. I am giving an invalid input for field1 so that clean_field1 method raises ValidationError. In clean_field2 i am accessing cleaned_data[field1]. When calling the url, it is giving 500 error. And in stack trace it says KeyError: 'field1'. On debugging I found ValidationError was raised in clean_field1 method. I expected that form.is_valid() will return false when clean_field1 raised ValidationError. But django went on to execute clean_field2. Why django is executing clean_field2, when clean_field1 raised ValidationError. form.is_valid() should have returned false when clean_field1 raised ValidationError. Am I correct? Does Form.is_valid() method return only after executing all clean_<'field_name'> methods(even if ValidationError was raised)? If yes, then this poor design I think. If first clean_<'field_name'> method raises ValidationError then what is the point in executing other clean_<'field_name'> method? I think Form.is_valid() should return false when it encounters first ValidationError. Or am I missing something? It will be really helpful if anyone can explain what is going on? Thank you. The code that I was executing: class MyForm(Form): field1 = forms.CharField() field2 = forms.CharField() def clean_field1(self): … -
Django queryset get empty values in query
So I'm trying to get all the values to be able to display in my templates. However I have encountered myself with this problem: I have these models: class Project(models.Model): projectId = models.AutoField(primary_key=True, db_column="Id", db_index=True, verbose_name='Project ID') description = models.CharField(max_length=900) class PM(models.Model): PMid = models.AutoField(primary_key=True, db_column="Id", db_index=True) PMNumber = models.CharField(max_length=50, unique=True, db_column="PMNumber") description = models.CharField(max_length=600) projectId = models.ForeignKey(Project, on_delete=models.CASCADE, db_column="ProjectID", related_name='+') And I'm trying to get all the projects with their respective PMNumber. For which I'm trying something like this: fpm = PM.objects.all() projects = [] for i in fpm: projects.append('ProjectName': i.projectId.description, 'PMNumber': i.PMNumber}) After that the result is like this [{'ProjectName': 'pr1', 'PMNumber': '119508-01'}, {'ProjectName': 'pr1', 'PMNumber': '119490-01'}] However, I'm still missing some projects that don't have a PM related to them, I want all the projects in the queryset to be able to show them in a template, not just the ones that have a PM. It should look something like this: [{'ProjectName': 'pr2', 'PMNumber':'None'}, {'ProjectName':'pr3' , 'PMNumber':'None'}, {'ProjectName': 'pr1', 'PMNumber': '119508-01'}, {'ProjectName': 'pr1', 'PMNumber': '119490-01'}] Is there a way to do this? or is there another way to do this in the views? Note: I know that setting an ID for each class in Django is not … -
Unsupported config option for services.volumes: 'postgres_data'
My docker-compose.yml is below, version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: but while running the command docker-compose up -d --build I got the following error message,someone please help me, ERROR: The Compose file './docker-compose.yml' is invalid because: Unsupported config option for services.volumes: 'postgres_data' -
Save table loop data in database in django
html file <table style="border-spacing: 10px;"> <thead> <th>Test</th> <th>Rate</th> </thead> <tbody> {% for booktest in var1 %} <tr> <td width="100%">{{ booktest }}</td> <td>{{ booktest.rate }}</td> </tr> {% endfor %} <br> <th scope="row">Total</th> <td><strong> {{ total_rate }} </strong></td> </ul> </tbody> </table> I want to save the {{ booktest }} and {{ booktest.rate }} value in database , as both has multiple values has it is in for loop