Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get One object value from database in Django
The situation is I have a table named Status consists of two fields. one is id which is primary key and based on auto increment and second is status which is integer. Now, the scenario is that I only want to get the value of status not id. Here are the details: views.py: from cvs.models import status_mod field_object = status_mod.objects.get(status) print(field_object) models.py: class status_mod(models.Model): id = models.BigIntegerField status = models.BigIntegerField class Meta: db_table = "status" The issue is that I want to store status value in a variable and want to call him in my template. Any solvable solution please -
legacy-install-failure when installing mysqlclient on mac
In django project I set the database as the rds mysql database and after running the server I got thie error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Naturally I tried to install mysqlclient package with pip3 install mysqlclient and I'm running into this error. I also tried pip3 install mysqlclient --use-pep517 but it results a different error [ -
How do I access static files using Jinja in Django
I am using Jinja templating within Django and I am having trouble getting static files to load. I have tried setting up the back end per this documentation (I've included the code below): https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.jinja2.Jinja2 However, I am getting an "Encountered unknown tag 'static'" if I include a {% load static 'path' %} tag. If I include a {% load static %} tag, I get "Encountered unknown tag 'load'." error. I have setup a "jinja2.py" file in the main folder with the following code: from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env settings.py has the following code: TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "environment": 'valuation.jinja2.environment', } }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Any guidance is very much appreciated. See above code for what I tried. -
Django's CORS_ALLOWED_ORIGINS and CORS_ALLOW_ALL_ORIGINS not working
I have a very strange problem with Django's corsheaders. I have tried all sorts of permutations and combinations by playing with all the possible settings but of no use. My current settings look like this: ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = ['*'] CORS_ALLOW_ALL_ORIGINS = True This is still causing the following error when the frontend sends an API request: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. I am not sure what else needs to be added, please let me know if I am missing anything here. I have already added 'corsheaders' in INSTALLED_APPS and also 'corsheaders.middleware.CorsMiddleware'in the MIDDLEWARE list (on top) I have tried adding domains one by one in the lists and verified by loading the changes, but still nothing worked. Even though I have now allowed for any origin and any host to send cross-origin requests, it is still throwing the CORS error. -
Can I use pretty-errors with gunicorn
I work on a project where in development I run a django webapp in gunicorn on docker. I want to use pretty-errors or any other tool that gives me pretty stacktrace. I have installed it and it works in the docker container because I can use it when I start a python shell. However when I start gunicorn instead of python, the stacktrace doest use pretty-errors. So does gunicorn interfere with pretty-errors? -
How to get the CSS rules that a Django Template would use?
Let's just say I have a basic class-based view like: from django.views.generic import TemplateView class HomePage(TemplateView): template_name = "homepage.html" and in homepage.html of course we load some CSS, apocryphally: {% extends "base.html" %} {% load static %} {% block CSS %} <link rel="stylesheet" type="text/css" href="{% static 'css/default.css' %}" /> <link rel="stylesheet" type="text/css" href="some CDN based CSS file' %}" /> {% endblock %} Now I'd like the view to read/load the CSS that will be sent to the client. If we could just find the source files, we could parse them with cssutils. And of course it's technically possible to find and parse the template file too, but Django already implements that and has a template loader. Is there any way short of rendering the template into a string, and trying to parse the HTML to extract CSS rules? And even if that's the path we need to pursue, is there a package that will given rendered HTML, and return the CSS rules? An interesting problem arises from the need, server-side, to extract some CSS information, notably colours. -
Problem in creating dynamic form fields in Django App using crispy form
I have one Model Given as below:- class FeeItemAmount(models.Model): id = models.AutoField(primary_key=True) fee_item = models.ForeignKey(FeeItem, on_delete=models.CASCADE) class_obj = models.ForeignKey(Classes, on_delete=models.CASCADE) amount = models.IntegerField() For creating new item I wanted to populate the Classes objects from model and based on that we will show the Form fields. One amount field for each class. In code I am doing that by:- name = forms.CharField(label="Name", max_length=100) months_list = forms.MultipleChoiceField(label='Months', widget=forms.CheckboxSelectMultiple,choices=months_name_list) due_date = forms.IntegerField(label="Due Date",required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) classes = Classes.objects.all() for class_obj in classes: field_name = 'class_%s' % (class_obj.id,) self.fields[field_name] = forms.IntegerField(label=class_obj.name,required=False) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.form_tag = False self.helper.label_class = 'col-sm-3' self.helper.field_class = 'col-sm-9' self.helper.layout = Layout( Div( Div('name', css_class='form-group col-sm-6 mb-0 border border-secondary'), Div('due_date', css_class='form-group col-sm-6 mb-0 border border-secondary'), css_class='form-row'), Div( Div(InlineCheckboxes('months_list'), css_class='form-group col-sm-12 mb-0 border border-secondary'), css_class='form-row'), Div( HTML("<p> Provide Amount for following Classes for this Fee Item:</p>"), css_class='form-row'), ) Now the problem is that those dynamically created fields are not showing in the Form. If I remove the Layout part of the code than those fields are showing but than it is not in the format that i want. I am new to Django and crispy form. I searched on google for this. One … -
How to allow CORS from Axios get request in Django backend?
I've been looking for a solution to this problem but nothing seems to work. I've arrived at the django-cors-headers package but can't get it to work. I'm sending an axios request form my vue frontend: axios.get('data/') .then(res => { console.log(res) }) but it throws a 200 network error error: Access to XMLHttpRequest at 'http://localhost:8000/data/' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. GET http://localhost:8000/data/ net::ERR_FAILED 200 AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} code : "ERR_NETWORK" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Network Error" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …} stack : "AxiosError: Network Error\n Django backend I am redirecting the incoming request in myProject/urls.py: from django.urls import path, include urlpatterns = [ path('', include('myApp.urls')), ] to myApp/urls.py: from django.urls import path from . import views urlpatterns = [ path('data/', views.getData) ] which invokes myApp/views.py: from … -
DJANGO - The view location_form.views.Insertrecord didn't return an HttpResponse object. It returned None instead
I am having this error constantly - The view location_form.views.Insertrecord didn't return an HttpResponse object. It returned None instead. I have tried indenting it in all ways possible. And i have a created another view in similar manner and that worked. Can someone tell where am i going wrong? I want to store the data of this form in my database which is phpmyadmin (mysql) views.py from django.shortcuts import render from .models import Location from django.contrib import messages # Create your views here. def Insertrecord(request): if request.method=='POST': if request.POST.get('id') and request.POST.get('parent_id') and request.POST.get('name') and request.POST.get('status') and request.POST.get('added_by') and request.POST.get('updated_by') and request.POST.get('created_on') and request.POST.get('updated_on') : saverecord=Location() saverecord.id=request.POST.get('id') saverecord.parent_id=request.POST.get('parent_id') saverecord.name=request.POST.get('name') saverecord.status=request.POST.get('status') saverecord.added_by=request.POST.get('added_by') saverecord.updated_by=request.POST.get('updated_by') saverecord.created_on=request.POST.get('created_on') saverecord.updated_on=request.POST.get('updated_on') saverecord.save() messages.success(request,"Record Saved Successfully..!") return render(request, 'location.html') else: return render(request,'location.html') location.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Location Registration Form</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <nav class="navbar bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <img src="https://img.freepik.com/premium-vector/customer-service-icon-vector-full-customer-care-service-hand-with-persons-vector-illustration_399089-2810.jpg?w=2000" alt="" width="30" height="24" class="d-inline-block align-text-top"> Location Registration Portal </a> </div> </nav> </head> <body background="https://img.freepik.com/free-vector/hand-painted-watercolor-pastel-sky-background_23-2148902771.jpg?w=2000"> <br> <h1 align="center">Location Registration Portal</h1> <hr> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <div class="container-sm"> <form method = "POST"> {% csrf_token %} <div class="row mb-3"> <label for="inputEmail3" class="col-sm-2 col-form-label">Country</label> <div class="col-sm-10"> <input type="text" name="name" class="form-control" id="inputEmail3"/> … -
How can I send E-Mails through python django frequently with a cronjob?
I try to run a function in django every 5 minutes. For this I user the django-crontab package. The function which should run, checks for some conditions in the database and if they are met, sends an e-mail to the user of the app. I have django 4 running on my linux ubuntu 20.04 server. I added the cronjob via python3 manage.py crontab add (in activated virtual environment). But then I wondered why the cronjob is not running. I tried to execute the job by hand and it worked. I think the problem boils down to this: When I'm in the activated virtual environment and run the crontab with "python3 manage.py crontab run " it works. But when I run it outside of the virtual environment I get the following error: Failed to complete cronjob at ('*/5 * * * *', 'evaluation_tool.scripts.cron.send_mail_if_classeval_ended') Traceback (most recent call last): File "/var/www/amadeus/lib/python3.10/site-packages/django_crontab/crontab.py", line 145, in run_job func(*job_args, **job_kwargs) File "/var/www/amadeus/evaluation_tool/scripts/cron.py", line 12, in send_mail_if_classeval_ended send_mail_time_over_class_evaluation(class_evaluation=class_evaluation.pk, File "/var/www/amadeus/evaluation_tool/scripts/email_handler.py", line 122, in send_mail_time_over_class_evaluation send_falko_mail("AMADEUS Evaluation abgeschlossen", message, to_email_address) File "/var/www/amadeus/evaluation_tool/scripts/email_handler.py", line 34, in send_falko_mail msg.send(fail_silently=False) File "/var/www/amadeus/lib/python3.10/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "/var/www/amadeus/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() File "/var/www/amadeus/lib/python3.10/site-packages/django/core/mail/backends/smtp.py", line … -
ModuleNotFoundError: No module named 'LS.settings'
ModuleNotFoundError: No module named 'LS.settings' LS is my project name File "C:\Users\user\Desktop\LS\venv\Lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'LS.settings' I tried to change my settings.py file and wsgi.py too.. but nothing worked In settings.py import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.Path.dirname(os.Path.dirname(os.Path.dirname(__file__))) -
"id" vs "pk" in django orm query [duplicate]
What is the actual difference between "id" and "pk" in Django, and which one is more preferable to use? Student.objects.get(id=20) Student.objects.get(pk=20) -
setting cookies with react-cookies to be read by DRF API
I want to set/remove a cookie on react web app when client switches between modes. I want the cookie to be sent with every request to the API which is using django rest framework, and use the value of the cookie to determine the kind of response. The web app and API are in different domains. I'm using react-cookie library to set the cookie which works fine on localhost but having issues setting it in other domains and will only let me use current domain for the cookie. setCookie('is_test',true,{domain:document.domain.match(/.[^.]*\.[^.]*$/)?.[0]||document.domain,path:'/'})} Thats the code I'm using to set the cookie, the regex is something I found to remove the subdomain (ex. www.testdomain.com converts to .testdomain.com) if there is any or just set the domain if its something like localhost but when it is deployed to the actual domain the cookie doesn't get set. Also will the backend API read the cookie if the domain is set with the client domain or does it need to be the server domain that is used for the request. It doesn't let me use other domains outside of the current(client) domain -
Passing HTML tag data- to Django with form submit
I am trying to pass data in HTML tag with a form submit to Django I currently have a template like this: {% for item in items %} <div class="product"> {{ item.item_name }} <form method="POST"> {% csrf_token %} <input type="submit" value="add to cart" data-pk="{{item.pk}}" class="add_product"/> <form> </div> {% endfor %} I want to pass data-pk with a Django form. How do I do that? Also I know, I can create a view to handle endpoint to do that, and include pk in the url, is that a better solution? I am new to Django, and I will be grateful for any input on how to do stuff the right way -
I can't Create Second Video in the Django-Rest-Framework
I'm using the Django and React to create YouTube clone. And when the user is creating second video, it giving the bad request error: <QueryDict: {'title': ['Edit Test56'], 'description': ['is It working1643'], 'user': ['3'], 'image': [<TemporaryUploadedFile: slackphot.png (image/png)>], 'video': [<TemporaryUploadedFile: video-for-fatube.mp4 (video/mp4)>]}> Bad Request: /api/admin/create/ When I tried to make post request in postman, it gave me views.py Views of the api. class CreateVideo(APIView): #permissions_classes = [IsAuthenticated] parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) serializer = VideoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py Video Serailzier. class VideoSerializer(serializers.ModelSerializer): user_name = CharField(source="user.user_name", read_only=True) class Meta: model = Video fields = ["id", "title", "image", "video", "description", "date_added", "is_active", "user", "user_name", "likes"] models.py Model of the Video class Video(models.Model): title = models.CharField(max_length=50) image = models.ImageField(_("Image"), upload_to=upload_to, default="videos/default.jpg") video = models.FileField(_("Video"), upload_to=upload_to, default="videos/default.mp4") user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_channel" ) description = models.CharField(max_length=255) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='video_post', null=True, blank=True) date_added = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) If you want to look at the whole project, here is github: https://github.com/PHILLyaHI/diplom-work -
Good way/place to authenticate Keystone/Openstack API from Django
This is my first post on Stackoverflow and I'm new to Django, I hope you'll understand. I want to use Django to provide a portal with authentication, which will have to consume an Keystone/Openstack API, to create/delete Projects, grant/remove rights. Openstack provides a RestFul API, on which I have to authenticate (I provide credentials, and receive back a token). I have 2 possibilities to access this API: Using python client: python-keystoneclient Using directly the restfulAPI Nevermind the option 1 or 2, I'm able to login and interact with the API, I do this in the view. My problem is, each time I change the page/view, I have to authenticate again. I don't know how to use/share the "session or client object" in other views. >>> from keystoneauth1.identity import v3 >>> from keystoneauth1 import session >>> from keystoneclient.v3 import client >>> auth = v3.Password(auth_url='https://my.keystone.com:5000/v3', ... user_id='myuserid', ... password='mypassword', ... project_id='myprojectid') >>> sess = session.Session(auth=auth) >>> keystone = client.Client(session=sess, include_metadata=True) I tried to pass the object as a session variable with request.session and request.session.get, but the object is not serializable. I serialized it, but I can't use it on the other view. Maybe I shouldn't access the API in the view? I'm … -
DJANGO - how to retrieve picture from database(sqlite) to show it on html
I have loaded the pictures to database(sqlite) and now, how to get that photo in html, can you guys tell me the steps to get there, thanks in advance I want to grab the picture from database and show it in the html. -
Django get wrong value from json.loads in POST request
I need to pass a user-input geojson with request to further process the information. The data comes from a textfile and then passed to the views.py in django with a POST request. Before passing to the view I checked the value of the string and that appears to be correct. After passing that to the view, I made a print check and some values inside the JSON are changed in string like: "{"id": "13871", "type":SOH@ "Feature", "properties": {"lanes": 0, "highway": "pedestrian" etc....." or "{"id":"86","type":"FeatureSOHVT","properties":etc......." The bold strings sometimes appear even inside the values of the dictionary. The js file: $.ajax({ type: 'POST', url: $('#confImp').data('url'), dataType: 'json', data: {'streetWeb': JSON.stringify(street_web), 'int_points': JSON.stringify(int_points_loaded), 'csrfmiddlewaretoken': csrftoken,}, success: function(res){blablabla} The django views.py: elif 'streetWeb' in request.POST: print(json.loads(request.POST.get('streetWeb'))) request.session['Working_area_final'] = json.loads(request.POST.get('streetWeb')) print(json.loads(request.POST.get('int_points'))) request.session['int_points'] = json.loads(request.POST.get('int_points')) return JsonResponse({'Risposta': 'Done'}) -
Code works fine without subquery, why to use it?
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') posts = Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1])) And, newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') posts = Post.objects.annotate(newest_commenter_email=newest.values('email')[:1]) Both, works fine then why use a Subquery, what are its advantages? -
Problem with INSTALLED_APPS in django settings.py file
If I try to add blog.apps.BlogConfig string to INSTALLED_APPS (to define the blog app), local server won't start giving me an error. Photos attached below: I am expecting for the separate section to appear on site. Was doing it by tutorial of the Youtuber Corey Schafer: https://www.youtube.com/watch?v=qDwdMDQ8oX4&list=PL-osiE80TeTtoQCKZ03T -
What is the meaning of this wsgi apache error log message (in django)
My django site seems to be working without any problems. But, looking at the apache2 error log, I frequently see this message (but no traceback or anything like it) [Thu Dec 22 16:37:32.948596 2022] [wsgi:error] [pid 763796:tid 140436065670912] [remote xxx.xxx.xxx.xxx:63167] [<JobsListUser: Jillian>] [Thu Dec 22 16:37:32.948671 2022] [wsgi:error] [pid 763796:tid 140436065670912] [remote xxx.xxx.xxx.xxx:63167] ja I have a model called JobsListUser, and these 2 lines appear repeatedly for all users (for example, [<JobsListUser: Kelly>] etc.) I assume the 'ja' is code of some kind for japanese (the site is viewable in english and japanese, but i've never seen an error) Can someone explain this to me? I want to know what the error is and if I need to fix it. I can't see any information in the log telling me which part of the code is generating the error. -
Bad Request when serializing data
I'm creating an API endpoints for a B2B ecommerce application. I have a company model to store the data about companies that are creating an account. I linked the company model to the default User Model in django, so that a user account will be created along with a company object. I linked the company model and the user model (One-to-One relationship). I keep getting this error, "Bad Request: /accounts/create/" when I submit data through the through the browsable API. This is my model. from django.db import models from django.contrib.auth.models import User # Create your models here. class Company(models.Model): class IndustryType(models.TextChoices): MANUFACTURING = "MAN", "Manufacturing" CONSTRUCTION = "CON", "Construction" IT = "IT", "Information Technology" PROFESSIONAL_SERVICES = "PS", "Professional Services" HEALTHCARE = "HC", "Healthcare" FINANCIAL_SERVICES = "FS", "Financial Services" WHOLESALE_AND_DISTRIBUTION = "WD", "Wholesale and Distribution" RETAIL = "RET", "Retail" EDUCATION = "EDU", "Education" user = models.OneToOneField(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=255) industry_type = models.CharField(max_length=255, choices=IndustryType.choices) tax_identification_number = models.CharField(max_length=15) address = models.CharField(max_length=255) phone = models.CharField(max_length=50) email = models.EmailField() def __str__(self): return self.company_name This is my serializer from rest_framework import serializers from django.contrib.auth.models import User from .models import Company class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ( "company_name", "industry_type", "tax_identification_number", "address", "phone", … -
How to configure BaseURL in Django4?
I'm new to django and trying to set a baseURL in django4. I came upon How to set base URL in Django of which the solution is: from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^someuri/', include([ url(r'^admin/', include(admin.site.urls) ), url(r'^other/$', views.other) ])), ] but this import statement: from django.conf.urls import urls shows: Cannot find reference 'urls' in '__init__.py' What am I doing wrong? -
"&" and "|" vs "and" and "or" for "AND" and "OR" operators in Django
I have Blog model below. *I use Django 3.2.16 and PostgreSQL: # "store/models.py" from django.db import models class Blog(models.Model): post = models.TextField() def __str__(self): return self.post Then, store_blog table has 2 rows below: store_blog table: id post 1 Python is popular and simple. 2 Java is popular and complex. Then, when running the filter() code using & or and or using Q() and & or Q() and and in test() view as shown below: # "store/views.py" from .models import Blog from django.db.models import Q def test(request): # With "&" # ↓ Here qs = Blog.objects.filter(post__contains="popular") & \ Blog.objects.filter(post__contains="simple") print(qs) # With "Q()" and "&" # ↓ Here # ↓ Here qs = Blog.objects.filter(Q(post__contains="popular") & Q(post__contains="simple")) print(qs) # ↑ Here # With "and" # ↓ Here qs = Blog.objects.filter(post__contains="popular") and \ Blog.objects.filter(post__contains="simple") print(qs) # With "Q()" and "and" # ↓ Here # ↓ Here qs = Blog.objects.filter(Q(post__contains="popular") and Q(post__contains="simple")) print(qs) # ↑ Here return HttpResponse("Test") I got the same result below: <QuerySet [<Blog: Python is popular and simple.>]> # With "&" <QuerySet [<Blog: Python is popular and simple.>]> # With "Q()" and "&" <QuerySet [<Blog: Python is popular and simple.>]> # With "and" <QuerySet [<Blog: Python is popular and simple.>]> # … -
How to create dockerfile & docker compose for django mysql with .env file?
dockerfile FROM python:3.10 WORKDIR /django_app ENV PYTHONUNBUFFERED 1 ADD . /django_app RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . /django_app docker-compose.yml version: '3.8' services: db: image: mysql:latest hostname: mysql restart: always ports: - '3308:3306' environment: MYSQL_DATABASE: 'test[[enter image description here](https://i.stack.imgur.com/Y6wAp.png)](https://i.stack.imgur.com/1OMAo.png)' MYSQL_USER : 'mysqluser' MYSQL_PASSWORD: 'root123' MYSQL_ROOT_PASSWORD: 'root123' # volumes: # - D:\django_project\db1:/var/run/mysqld # - D:\django_project\db:/var/lib/mysql web: build: . restart: on-failure command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" depends_on: - db [pl check error in photos.](https://i.stack.imgur.com/ni4t7.png) First time create docker build but agine build docker getting errors. Database not connect docker image mysql.