Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to return DB Array object in Django to a View
I have something sort of working. I am very new to Django and Python. I have the following view in my api folder from re import S from django.shortcuts import render from rest_framework import generics, status from .serializers import CourseSerializer, CreateCourseSerializer from .models import Course from rest_framework.views import APIView from rest_framework.response import Response import logging from django.core import serializers logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Create your views here. class CourseView(generics.ListAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer SomeModel_json = serializers.serialize("json", Course.objects.all()) logger.debug(SomeModel_json) def get(self, request, format=None): return Response(self.SomeModel_json, status=status.HTTP_201_CREATED) class CreateCourseView(APIView): serializer_class = CreateCourseSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): course_title = serializer.data.get('course_title') course_topic = serializer.data.get('course_topic') course_topic_about = serializer.data.get('course_topic_about') course_question = serializer.data.get('course_question') course_answer = serializer.data.get('course_answer') course = Course(course_title=course_title, course_topic=course_topic, course_topic_about=course_topic_about, course_question=course_question, course_answer=course_answer) course.save() return Response(CourseSerializer(course).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and have the following serializers.py in my api folder from rest_framework import serializers from .models import Course class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ( 'id', 'course_title', 'course_topic', 'course_topic_about', 'course_question', 'course_answer', 'created_at', 'updated_at') class CreateCourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ( 'course_title', 'course_topic', 'course_topic_about', 'course_question', 'course_answer') Have the follow models.py in api folder from django.db import models # Create your … -
Does transaction.atomic roll back increments to a pk sequence
I'm using Django 2.2 and my question is does transaction atomic roll back increments to a pk sequence? Below is the background bug I wrote up that led me to this issue I'm facing a really weird issue that I can't figure out and I'm hoping someone has faced a similar issue. An insert using the django ORM .create() function is returning django.db.utils.IntegrityError: duplicate key value violates unique constraint "my_table_pkey" DETAIL: Key (id)=(5795) already exists. Fine. But then I look at the table and no record with id=5795 exists! SELECT * from my_table where id=5795; shows (0 rows) A look at the sequence my_table_id_seq shows that it has nonetheless incremented to show last_value = 5795 as if the above record was inserted. Moreover the issue does not always occur. A successful insert with different data is inserted at id=5796. (I tried reset the pk sequence but that didn't do anything, since it doesnt seem to be the problem anyway) I'm quite stumped by this and it has caused us a lot of issues on one specific table. Finally I realize the call is wrapped in transaction.atomic and that a particular scenario may be causing a double insert with the same … -
error mutation grapiql django many-to-many set is prohibited. Use films.set() instead
Tengo los siguientes modelos: ###################################################### class People(TimeStampedModel, SimpleNameModel): """ Personajes del universo de Star Wars """ MALE = 'male' FEMALE = 'female' HERMAPHRODITE = 'hermaphrodite' NA = 'n/a' GENDER = ( (MALE, 'Male'), (FEMALE, 'Female'), (HERMAPHRODITE, 'Hermaphrodite'), (NA, 'N/A'), ) HAIR_COLOR_CHOICES = ( ('BLACK', 'black'), ('BROWN', 'brown'), ('BLONDE', 'blonde'), ('RED', 'red'), ('WHITE', 'white'), ('BALD', 'bald'), ) EYE_COLOR_CHOICES = ( ('BLACK', 'black'), ('BROWN', 'brown'), ('YELLOW', 'yellow'), ('RED', 'red'), ('GREEN', 'green'), ('PURPLE', 'purple'), ('UNKNOWN', 'unknown'), ) height = models.CharField(max_length=16, blank=True) mass = models.CharField(max_length=16, blank=True) # hair_color = models.CharField(max_length=32, blank=True) hair_color = models.CharField(max_length=32, choices=HAIR_COLOR_CHOICES, blank=True) skin_color = models.CharField(max_length=32, blank=True) # eye_color = models.CharField(max_length=32, blank=True) eye_color = models.CharField(max_length=32, choices=EYE_COLOR_CHOICES, blank=True) birth_year = models.CharField(max_length=16, blank=True) gender = models.CharField(max_length=64, choices=GENDER) home_world = models.ForeignKey(Planet, on_delete=models.CASCADE, related_name='inhabitants') class Meta: db_table = 'people' verbose_name_plural = 'people' ###################################################### class Film(TimeStampedModel): title = models.CharField(max_length=100) episode_id = models.PositiveSmallIntegerField() # TODO: Agregar choices opening_crawl = models.TextField(max_length=1000) release_date = models.DateField() director = models.ForeignKey(Director, on_delete=models.CASCADE, related_name='films') producer = models.ManyToManyField(Producer, related_name='films') characters = models.ManyToManyField(People, related_name='films', blank=True) planets = models.ManyToManyField(Planet, related_name='films', blank=True) class Meta: db_table = 'film' def __str__(self): return self.title ###################### class People_film(People): films = models.ManyToManyField(Film, related_name='film', blank=True) Estoy haciendo una mutacion en graphiql de creación que al agregar people tambien pueda agregar films en las … -
Django is crashing again and again
My django server is crashing sometimes on the production, it was also crashing in the test environment but it was not an issue, crash on prod is making business loss. The crash I am getting is quite difficult to trace and difficult to understand(atleast for me) I am attaching few screenshots for your reference. What could be the issue? -
Django search returning all objects not the specified ones
I'm currently trying to achieve a search that shows only the ads that contain the text in title, description or tags. It seems like everything should work properly, but the search returns all of the objects.(site has the /?search=foo ending after the button click) my List View class AdListView(ListView): model = Ad def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) favorites = list() if self.request.user.is_authenticated: # rows = [{'id': 2}, {'id': 4} ... ] (A list of rows) rows = self.request.user.favorite_ads.values('id') # favorites = [2, 4, ...] using list comprehension favorites = [ row['id'] for row in rows ] context['favorites'] = favorites strval = self.request.GET.get("search", False) if strval: # Simple title-only search # __icontains for case-insensitive search query = Q(title__icontains=strval) query.add(Q(text__icontains=strval), Q.OR) query.add(Q(tags__name__in=[strval]), Q.OR) objects = Ad.objects.filter(query).select_related().distinct().order_by('-updated_at')[:10] else : objects = Ad.objects.all().order_by('-updated_at')[:10] # Augment the post_list for obj in objects: obj.natural_updated = naturaltime(obj.updated_at) context['search'] = strval return context part of my template: <div style="float:right"> <!-- https://www.w3schools.com/howto/howto_css_search_button.asp --> <form> <input type="text" placeholder="Search.." name="search" {% if search %} value="{{ search }}" {% endif %} > <button type="submit"><i class="fa fa-search"></i></button> <a href="{% url 'ads:all' %}"><i class="fa fa-undo"></i></a> </form> </div> {% if ad_list %} <ul> {% for ad in ad_list %} <li> <a href="{% url 'ads:ad_detail' … -
Could not import 'djangorestframework_camel_case.render.CamelCaseJSONRenderer' for API setting 'DEFAULT_RENDERER_CLASSES'
I am working on django (DRF) application. And i am using djangorestframework-camel-case==1.2.0 # https://pypi.org/project/djangorestframework-camel-case/ I have the following error: ImportError: Could not import 'djangorestframework_camel_case.render.CamelCaseJSONRenderer' for API setting 'DEFAULT_RENDERER_CLASSES'. ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py). Full error text https://pastebin.com/DKDSv8Q2 Also all my libs version: https://pastebin.com/ucGte32B How can I fix this error? settings.py -- full code (https://pastebin.com/2VbKqPwM) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'djangorestframework_camel_case.render.CamelCaseJSONRenderer', 'djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer', # Any other renders ), 'DEFAULT_PARSER_CLASSES': ( # If you use MultiPartFormParser or FormParser, we also have a camel case version 'djangorestframework_camel_case.parser.CamelCaseFormParser', 'djangorestframework_camel_case.parser.CamelCaseMultiPartParser', 'djangorestframework_camel_case.parser.CamelCaseJSONParser', # Any other parsers ), } -
how to install postgres extension with docker on django project
I want to add full text search to my django project and I used postgresql and docker,so want to add extension pg_trgm to postgresql for trigram similarity search. how shuld I install this extension with dockerfile? In shared my repository link. FROM python:3.8.10-alpine WORKDIR /Blog/ ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' ./entrypoint.sh RUN chmod +x ./entrypoint.sh COPY . . ENTRYPOINT ["./entrypoint.sh"] docker-compose services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/Blog ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=helo - POSTGRES_PASSWORD=helo - POSTGRES_DB=helo volumes:`enter code here` postgres_data: -
WSGI application Error caused by SocialAuthExceptionMiddleware
I was trying python-social-auth and when I added the middleware MIDDLEWARE = [ 'social_django.middleware.SocialAuthExceptionMiddleware' ... ] I get this error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'djangoauthtest.wsgi.application' could not be loaded; Error importing module. and I was looking over at other question to look for an answer and so far I've tried to install whitenoise and add whitenoise middleware reinstall python-social-app use python-social-app 4.0.0 change WSGI_APPLICATION = 'myapp.wsgi.application' to WSGI_APPLICATION = 'wsgi.application' and nothing worked so far. I'll be thankfull for any kind of advice regarding this! -
Unable to run Django with Postgress in Docker
I wanted to set up a Django app with PostgresDb inside docker containers so that's why I wanted to setup docker-compose but when I execute my code docker, django and db all are working fine and I also developed some API's and they were also working fine as expected but unfortunately, suddenly I'm blocked with these errors: pgdb_1 | pgdb_1 | 2021-12-11 15:05:38.674 UTC [1] LOG: starting PostgreSQL 14.1 (Debian 14.1-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit pgdb_1 | 2021-12-11 15:05:38.674 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 pgdb_1 | 2021-12-11 15:05:38.674 UTC [1] LOG: listening on IPv6 address "::", port 5432 pgdb_1 | 2021-12-11 15:05:38.697 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" pgdb_1 | 2021-12-11 15:05:38.729 UTC [27] LOG: database system was shut down at 2021-12-11 15:03:09 UTC pgdb_1 | 2021-12-11 15:05:38.761 UTC [1] LOG: database system is ready to accept connections django_1 | Watching for file changes with StatReloader django_1 | Performing system checks... django_1 | django_1 | System check identified no issues (0 silenced). pgdb_1 | 2021-12-11 15:05:41.390 UTC [34] FATAL: password authentication failed for user "postgres" pgdb_1 | 2021-12-11 15:05:41.390 UTC [34] DETAIL: Role "postgres" does not exist. … -
How can use slug for all urls in django without anything before or after?
I want all djaango urls use slug field without any parameter before or after, by default just one url can use this metod ex: path('<slug:slug>', Article.as_View(), name="articledetail"), path('<slug:slug>', Category.as_View(), name="category"), path('<slug:slug>', Product.as_View(), name="productdetail"), mysite .com/articleslug mysite .com/categoryslug mysite .com/productslug How can I do it? Thank you -
connection error while using requests module in my django project
I was trying to create a django project. Everything was fine until I did a get request using requests.get() in python in my views.py Following is what my views.py have from django.shortcuts import render import re, requests def codify_data(data_raw): data = data_raw.json()['data'] if language == 'web': html_cd = data['sourceCode'] css_cd = data['cssCode'] js_cd = data['jsCode'] def home_page(request): return render(request,'home/index.html') def code(request): link = request.GET.get('link', 'https://code.sololearn.com/c5I5H9T7viyb/?ref=app') result = re.search(r'https://code.sololearn.com/(.*)/?ref=app',link).group(1)[0:-2] data_raw = requests.get('https://api2.sololearn.com/v2/codeplayground/usercodes/'+result) codify_data(data_raw)``` [Error shown in image][1] [1]: https://i.stack.imgur.com/2Uao9.jpg -
get False Booleans one by one from the list
I am building a blog app in which, I have created about 10+ Booleans and I am trying to track Booleans according to the list. I mean, Suppose, there are 5 Booleans and all are in the sequence, like `[boolean_1, boolean_2, boolean_3, boolean_4, boolean_5] and they are all false. then I am trying to get first Boolean on a page until (turning True a Boolean can take days) it is True and then boolean_2 will be seen on page boolean_1 will be removed after True. then I am trying to get the Booleans which are False one by one But I have no idea how can I filter Booleans which are False one by one. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) boolean_1 = models.BooleanField(default=False) boolean_2 = models.BooleanField(default=False) boolean_3 = models.BooleanField(default=False) boolean_4 = models.BooleanField(default=False) boolean_5 = models.BooleanField(default=False) boolean_6 = models.BooleanField(default=False) views.py def page(request): listOfBooleans = [request.user.profile.boolean_1, request.user.profile.boolean_2, request.user.profile.boolean_3] get_first_boolean = listOfBooleans(0) context = {'listOfBooleans':listOfBooleans} return render(request, 'page.html', context) I have tried by using compress :- from itertools import compress list_num = [1, 2, 3, 4] profile_booleans = [request.user.profile.boolean_1, request.user.profile.boolean_2, request.user.profile.boolean_3] list(compress(list_num, profile_booleans)) But this :- It is returning True instead of False I cannot access first from it, if I … -
Accessing query parameter in serializer in Django
I just wanted to access a query parameter in serializer like class MySerializer(serializers.ModelSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): return self.context['request'].query_params['page'] But its showing Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'request' Thanks in advance. -
Getting value from View to Serializer in Django
I am not sure what I am doing wrong, I tried to follow a few solution. class MyViewSet(viewsets.ModelViewSet): filterset_class = IngredientFilter def get_serializer_context(self): context = super().get_serializer_context() context['test'] = "something" return context In my Serializer, class MySerializer(BaseSerializer): isHighlight = serializers.SerializerMethodField() def get_isHighlight(self, obj): return self.context['test'] I am getting this error, Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'test' Any suggestions? -
Probkem in Django with runserver command
I started a project in django and everything was okay, but i closed my project and fews days later i tried to reopen, but this error appeared when i put the command "django-admin runserver" : Traceback (most recent call last): File "c:\users\moren\appdata\local\programs\python\python37-32\lib\runpy.py", line 193, in run_module_as_main "main", mod_spec) File "c:\users\moren\appdata\local\programs\python\python37-32\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Users\moren\Envs\myapp\Scripts\django-admin.exe_main.py", line 7, in File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management_init.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management_init_.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\moren\Envs\myapp\lib\site-packages\django\conf_init_.py", line 82, in getattr self.setup(name) File "C:\Users\moren\Envs\myapp\lib\site-packages\django\conf_init.py", line 67, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. And when i put "python manage.py runserver" this appear : c:\users\moren\appdata\local\programs\python\python37-32\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory if anyone can help me I would be very grateful -
Hello, I encountered this problem. I tried to solve it through searching. I found solutions even here in stack overflow, but I did not understand how
My problem is a ValueError: Field 'id' expected a number but got 'passwprd'. I tried to delete the password field and then re-create it, but to no avail. I also tried to change the default for it too, to no avail. This problem appears when I give it a migrate command. Please help. Any other information I am ready to provide, thank you. PS C:\Users\user\Desktop\test1\prj> python manage.py migrate ←[36;1mOperations to perform:←[0m ←[1m Apply all migrations: ←[0madmin, auth, contenttypes, products, sessions, shop ←[36;1mRunning migrations:←[0m Applying products.0007_user_purshase...Traceback (most recent call last): File "C:\python\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'passwprd' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\python\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\python\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\python\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\python\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\python\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\python\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\python\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) … -
Setting some fields to be automatically filled in using CreateVeiw in Django
I'm using Django's CreateView in order to fill a form and I want some of the fields to be automatically filled in, looking for ides how I could that -
trying to update DjangoREST API using calls from a Golang Job runnier. For some reason i keep receiving None Value in request.POST in django
Below is the function i run to update a Django REST API. The Map is correctly constructed as check by the println but Django server shows the value received as None. The similar API is called successfully using Python requests module. What might be the error here ? func upd_prices() { for i:=0; i<501; i++ { co_id:=strconv.Itoa(i) // co_obj:=Company{co_id} co_obj:=map[string]string{"id":co_id} jsonStr,err:=json.Marshal(co_obj) if err!=nil { log.Println(err) } // var jsonStr = []byte(`{"co_id":`+co_id+`}`) // responseBody:=bytes.NewBuffer(postBody) fmt.Println(string(jsonStr)) resp,err:=http.Post("http://127.0.0.1:8000/insert_prices/","application/json", bytes.NewBuffer(jsonStr)) if err!=nil { log.Print(err) } defer resp.Body.Close() _, err2 := ioutil.ReadAll(resp.Body) if err2 != nil { log.Fatalln(err) } // sb := string(body) // log.Print(sb) // // file,_:=os.Create("log.txt") // file.WriteString(sb) // defer file.Close() time.Sleep(time.Second*5) } }``` -
Display image and filter team members according to id in django
I want to display and team members of selected photographer id. But I am not getting image as well as team. Nothing is showing. models.py class Photographer(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) location = models.CharField(max_length=100) studio_name = models.CharField(max_length=100) mobile = models.CharField(max_length=100) address = models.CharField(max_length=200) category = models.ManyToManyField(Category) class Gallery(models.Model): photographer = models.ForeignKey(User,on_delete=models.CASCADE) photo = models.ImageField(upload_to='gallery') cover_photo = models.ImageField(upload_to='cover_photos/',null=True,blank=True) class Team(models.Model): photographer = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=100) speciality = models.CharField(max_length=100) I am using foreignkey in Gallery table and in Team table. views.py def visit_photography_site(request,id): photographer = Photographer.objects.get(id=id) gallery = Gallery.objects.filter(photographer=photographer.user.id) team = Team.objects.filter(photographer=photographer.user.id) context = { 'photographer':photographer, 'gallery':gallery, 'team':team, } return render(request,'app/home.html',context) I want to display/filter gallery and team of the photographer according to particular photographer id. home.html <img class="sp-image" src="{{ gallery.cover_photo.url }}" alt="Slider 1"/> <h1 class="sp-layer slider-text-big" data-position="bottom" data-vertical="25%" data-show-transition="top" data-hide-transition="top" data-show-delay="1500" data-hide-delay="200"> <span class="highlight-texts">{{ photographer.studio_name }}</span> Here I want to display cover photo which is field in Gallery table and there is Foreign Key from Photographer table. If I click on photographer whose id is 1 then I should get cover photo of that photographer whose id is 1. -
Why Heroku can't find my Django templates?
I deployed my project on Heroku. But it can't find my templates(Source doesn't exist): My project architecture: settings.py: from pathlib import Path import sys import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { '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', ], }, }, ] -
Unable to install mysqlclient with pip on ubuntu
I'm trying to install mysqlclient on Ubuntu 20.04LTS, the main error is: mysql_config not found. Whole Error: $ pip3 install mysqlclient==2.0.3 Defaulting to user installation because normal site-packages is not writeable Collecting mysqlclient==2.0.3 Using cached mysqlclient-2.0.3.tar.gz (88 kB) Preparing metadata (setup.py) ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup.py'"'"'; _file__='"'"'/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file_) if os.path.exists(_file_) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, _file_, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-ehrlbbbl cwd: /tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/ Complete output (15 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-qr1hc7jz/mysqlclient_1ff152ec2d5d4f14a4e282285faeb229/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/3c/df/59cd2fa5e48d0804d213bdcb1acb4d08c403b61c7ff7ed4dd4a6a2deb3f7/mysqlclient-2.0.3.tar.gz#sha256=f6ebea7c008f155baeefe16c56cd3ee6239f7a5a9ae42396c2f1860f08a7c432 (from https://pypi.org/simple/mysqlclient/) (requires-python:>=3.5). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ERROR: Could not find a version that satisfies the requirement mysqlclient==2.0.3 (from versions: 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, … -
Dockerizing django, postgres, gunicorn, ngnix - only admin static works, other 404
As in topic. I have tried to apply solutions I found in internet, but no success :( I am pretty new to programming and as making an app is one thing, deploying it just overwhelmed me. I have managed to put it on server, run it on docker with SSL, but main problem is that only admin static files load, other give 404 error. Weird thing is that static subdirectories structure is kept, but there are no files inside. Please help me, I am really stuck :( If you require any other data, please write Note that neither STATIC_ROOT or STATIC_DIRS work (in some cases changing it helped, not here). Thank you very much in advance Directory structure: ├── app │ ├── Dockerfile.prod │ ├── entrypoint.prod.sh │ ├── manage.py │ ├── requirements.txt │ ├── sancor │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── settings.py │ │ ├── urls.py │ │ ├── views.py │ │ └── wsgi.py │ ├── static │ │ ├── css │ │ ├── favicon.ico │ │ ├── fonts │ │ ├── js │ │ ├── less │ │ ├── sancor │ │ │ ├── css │ │ │ └── js … -
im not able to send data to view due json serializable
i am getting error set object is not JSON serializable i also used json.dumps but still getting this error ? actually i am trying to save form data to django database with help of ajax but where i am doing mistake def update_ajax(request): if request.method == "GET" and request.is_ajax(): nam1 = request.GET.get('nam1') nam2 = request.GET.get('nam2') nam3 = request.GET.get('nam3') n1 = json.loads(nam1) n2 = json.loads(nam2) n3 = json.loads(nam3) print(n1, n2, n3) return JsonResponse({'success'}, safe=False) script function myfun(){ let nam1=document.getElementById('name').value; let nam2=document.getElementById('email').value; let nam3=document.getElementById('phone').value; obj ={ 'nam1': JSON.stringify(nam1), 'nam2':JSON.stringify(nam2), 'nam3':JSON.stringify(nam2), } $.ajax({ type:"GET", url: "{% url 'update_ajax' %}", dataType: "json", data: obj, success:function(){ alert('success') } }); } -
A question about django:TypeError: 'builtin_function_or_method' object is not subscriptable
models.py class User_db(models.Model): username = models.CharField(max_length=32) password = models.CharField(max_length=64) here is shell code >>>python manage.py shell >>>from appName.models import User_db *i dont konw why it is wrong,maybe about QuerySet?* >>>User_db.objects.all().values() **TypeError: 'builtin_function_or_method' object is not subscriptable** >>> User_db.objects.get(id=1) <User_db: User_db object (1)> the problem also occurs with "filter()". this error makes me confuse,help me,plz!!! -
How to display Data of relative foreign key in Django html page?
I saw may answer but i don't know why in my page its not working can anyone help me to find the mistake. model class SchoollModel(models.Model): title = models.CharField(max_length=60 ) image = models.FileField(upload_to = 'static/img' ,help_text='cover img') desc = models.TextField(null=True, blank=False) def __str__(self): return self.title class SchoolImage(models.Model): post = models.ForeignKey(SchoollModel, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to = 'static/img') def __str__(self): return self.post.title views.py after importing all def school_view(request , id): school_model =SchoollModel.objects.all().filter(id=id)[0] school_image = SchoolImage.objects.all() return render(request,'school.html' ,{'school_model':school_model,'school_image':school_image}) school.html i wanna display multiple image of school. i have inlined in admin. how we can get all the images that foreign-key to SchoolModel {% for sch in SchoollModel.SchoolImage_set.all %} <img style = 'max-height:14rem ;max-width:14rem;' src="{{sch.images.url}}" alt="image"> {% endfor %}