Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I setup celery beat in docker?
in settings.py CELERY_TIMEZONE = 'Europe/Minsk' CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') CELERY_RESULT_BACKEND = os.environ.get('CELERY_BROKER_URL') CELERY_BROKER_URL = redis://redis:6379 config/celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'pulling-games-to-database': { 'task': 'gamehub.tasks.pull_games', 'schedule': 604800.0, } } docker-compose.yml version: '3' services: db: build: context: ./docker/postgres dockerfile: Dockerfile env_file: - ./.env.db volumes: - ./docker/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql restart: always ports: - '5432:5432' redis: image: redis ports: - '6379:6379' celery: build: . command: celery -A config worker -l info volumes: - .:/code depends_on: - db - redis celery-beat: build: . command: celery -A config beat -l info volumes: - .:/code depends_on: - db - redis app: build: context: ./ dockerfile: Dockerfile env_file: - ./.env volumes: - ./:/usr/src/app depends_on: - db - redis ports: - '8000:8000' restart: always nginx: build: context: ./docker/nginx dockerfile: Dockerfile depends_on: - app - db ports: - '80:80' When I run this by sudo docker-compose build --no-cache sudo docker-compose up I do not see any errors. As well as I do not see celery output. My task puts data to the database periodically. This data must be shown at main page. But it does not. I'm pretty sure that database is … -
Django allauth OSError: [Errno 99] Address not available
I'm trying to implement django-allauth and faced this problem. For this project I'm using Docker as well. When I click "Sign up using VK" it redirects me to http://127.0.0.1:8000/accounts/vk/login/callback/?code=...random code... with this error. After going to sign up page again and clicking the same button it successfully redirects me to profile page which means the user was created. I couldn't find any solutions using Google so hope you can help. I don't think that was because of bad configuration because I've tested similar configuration on empty django project which was not containerized and everything worked properly. Maybe it's because inside docker container there's venv installed. Traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/vk/login/callback/?code=5d6083ab180253fa42&state=JDhRkbbzqV2m Django Version: 3.2.8 Python Version: 3.9.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'coreapp', 'crispy_forms', 'rest_framework', 'corsheaders', 'easy_thumbnails', 'django_cleanup', 'storages', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.vk'] Installed Middleware: ['whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/py/lib/python3.9/site-packages/allauth/socialaccount/providers/oauth2/views.py", line 77, in view return self.dispatch(request, *args, **kwargs) File "/py/lib/python3.9/site-packages/allauth/socialaccount/providers/oauth2/views.py", line 147, in dispatch return complete_social_login(request, login) File "/py/lib/python3.9/site-packages/allauth/socialaccount/helpers.py", line 151, in complete_social_login … -
'utf-8' codec can't decode byte 0xff in position 0: invalid start byte UnicodeDecodeError
i am working with djangorestFramework and in the serializers i have an image which when i fetch it tells me that 'utf-8' error: from rest_framework import serializers from backend.models.productos import Productos from backend.models.categoria import Categoria from backend.serializers.CategoriaSerializers import Categoriaserializers class ProductosSerializers(serializers.ModelSerializer): #Categorias = Categoriaserializers() class Meta: model = Productos fields = "__all__" this on localhost:8000/products returns this: [ { "id_productos": 8, "codigo": 12, "producto": "Carro", "imagen": "http://localhost:8000/media/productos/bulgakov-mijail-el-maestro-y-margarita.jpg", "stock": 0, "precio_compra": 0.0, "precio_venta": 0.0, "venta": 0, "fecha": "2021-10-12T16:02:06.167755Z", "id_categoria": 2 } ] but in addition to that, I need to bring in the product category and I do it this way: from rest_framework import serializers from backend.models.productos import Productos from backend.models.categoria import Categoria from backend.serializers.CategoriaSerializers import Categoriaserializers class ProductosSerializers(serializers.ModelSerializer): Categorias = Categoriaserializers() class Meta: model = Productos fields = "__all__" #fields = ["id_productos","codigo","producto","imagen","stock","precio_compra","precio_venta","venta","fecha","Categorias"] def to_representation(self, obj): productos = Productos.objects.get(id_productos=obj.id_productos) categorias = Categoria.objects.get(productos=obj.id_productos) return{ 'id_producto': productos.id_productos, "codigo": productos.codigo, "producto" : productos.producto , "imagen": str(productos.imagen), "stock": productos.stock, "precio_compra" : productos.precio_compra, "precio_venta": productos.precio_venta, "venta": productos.venta, "fecha": productos.fecha, "Categorias":{ "id_categoria": categorias.id_categoria, "categoria": categorias.categoria, "fecha": categorias.fecha } } and I get this back [ { "id_producto": 8, "codigo": 12, "producto": "Carro", "imagen": "productos/bulgakov-mijail-el-maestro-y-margarita.jpg", "stock": 0, "precio_compra": 0.0, "precio_venta": 0.0, "venta": 0, "fecha": "2021-10-12T16:02:06.167755Z", "Categorias": { "id_categoria": … -
django update user form
here the problem with form, all fields are applied except for the avatar field. i can't see the reason why. forms class UserEditForm(forms.ModelForm): class Meta: model = User fields = ['username', 'name', 'email', 'bio', 'avatar'] exclude = () widgets = { 'avatar': forms.FileInput(), 'bio': forms.Textarea(), } views @login_required(login_url='login') def edit_profile(request): user = request.user form = UserEditForm(instance=user) if request.method == 'POST': form = UserEditForm(request.POST, request.FILES, instance=user) if form.is_valid(): form.save() return redirect('get_author', pk=user.id) return render(request, 'account/edit_profile.html', {'form': form}) template <form class="form-horizontal" role="form" method="POST" action=""> {% csrf_token %} <div class="col-md-3"> <div class="text-center"> <img src="{{ request.user.avatar.url }}" class="avatar img-circle" alt="avatar" style="width: 100px; height: 100px;"> <h6>Upload a different photo...</h6> {{ form.avatar }} </div> </div> ... other fields thanks for ur help -
How to use multiprocessing in Python with Django to create thousands of model instances from xml file?
I have a script that parses data from an xml file into Django models. It works ok but recently we've been encountering files with dozen of thousands of models to create which is incredibly slowing down the process (up to 40 min to upload a single 20MB file). I would like to try and use multiprocessing to speed it up as much as I can but I am new to this package. This is the current setup: create_profiles_from_xml: is a function that loops through the data extracted from the xml, called xml_members, popping one element at a time (it has to be like that due to a relationship that can be created with the next element or not). create_profile: is a just a function that handles the data to match with the model fields and then call the .create() method, that's why I omitted the details of this function here. def create_profiles_from_xml(xml_members, device): profiles = [] while len(xml_members) > 0: parent_member = members.pop(0) profile = create_profile(parent_member, parent=None) if profile: profiles.append(profile) return profiles And here is what I tried to do with the multipocessing from multiprocessing import Pool def create_profiles_from_xml(xml_members, device): profiles = [] pool = Pool(processes=cpu_count()) profiles = pool.imap_unordered(create_profile, xml_members) … -
How to access values from a form powered by typeform in python
I'm trying to use Typeform in my Python/Django website, and I wanted to know if there is a way to access the data from the form and do something with it. -
TypeError at /pet/3/ petAPI() got an unexpected keyword argument 'pk' Django
I am a newbie to Django and its REST Framework, I am trying to design an API that allows me to perform the basic operations of the CRUD, both the GET, POSt and PUT methods work correctly, however when I try to implement the DELETE method I get a very particular error: This is my main urls.py file: from django.conf.urls import url from django.urls import path from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView) from pethomeApp import views urlpatterns = [ path('login/', TokenObtainPairView.as_view()), path('refresh/', TokenRefreshView.as_view()), path('user/', views.UserCreateView.as_view()), path('pet/', views.petView.petAPI), path('pet/<int:pk>/', views.petView.petAPI), ] This is my petViwe.py file: from rest_framework import status, views from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from pethomeApp.models import Pet from pethomeApp.serializers import PetSerializer # Create your views here. @csrf_exempt def petAPI(request, id=0): if request.method == 'GET': if id == 0: pets = Pet.objects.all() serializer = PetSerializer(pets, many=True) return JsonResponse(serializer.data, safe=False) else: pet = Pet.objects.get(id=id) serializer = PetSerializer(pet) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = PetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse("Added successfuly", safe=False) return JsonResponse("Failed to add", safe=False) elif request.method == 'PUT': data = JSONParser().parse(request) pet = Pet.objects.get(id_pet=data['id_pet']) serializer = PetSerializer(pet, data=data) if serializer.is_valid(): serializer.save() … -
How to send a reset password email in Django on User creation?
I want to be able to let an admin create user accounts and then, instead of setting up a password for the user, the user would automatically receive a reset password email. The view for the user creation, which also includes a Member model, is the following: def newmember(request): if request.method == 'POST': nu_form = NewUser(request.POST) nm_form = NewMember(request.POST) if nu_form.is_valid() and nm_form.is_valid(): nusave = nu_form.save() nmsave = nm_form.save(commit = False) nmsave.user = nusave nmsave.save() return redirect(members) else: print(nu_form.errors) print(nm_form.errors) else: nu_form = NewUser() nm_form = NewMember() context = { 'nu_form': nu_form, 'nm_form': nm_form} return render(request, 'web/newmember.html', context) How can I make so that upon creation of a new user, Django automatically sends an email to that new user requestion a password reset? -
overriding Django change_list_results
I am customizing my admin panel a little and want to add an additional column to it, so as per the docs I have to override the change_form_results.html file but how do I do it? all I see is this code in it <tbody> {% for result in results %} {% if result.form and result.form.non_field_errors %} <tr><td colspan="{{ result|length }}">{{ result.form.non_field_errors }}</td> </tr> {% endif %} <tr>{% for item in result %} {{ item }} {% endfor %}</tr> {% endfor %} </tbody> what change am i suppose to make to above code -
Django postgres raise notice
Let's say that I have a postgres function that raise multiple notices. Example: function testnotice ... raise notice 'test' raise notice 'test-2' When I execute this function from django, cursor.execute("select testnotice()") Is there any posibility to retrive the notifications ? I tried the answer from: Python2 print postgresql stored procedure raise notice But I get AttributeError: 'DatabaseWrapper' object has no attribute 'notices' on Python 2.7 Any helpful ideas ? Thank you. -
Set unique primary key based on foreignkey
I have a model defined as - class sales_order(models.Model): customer=models.ForeignKey() item=models.ForeignKey() branch=models.ForeignKey() --- ---other fields Now for each branch, I want to start the primary key from 1 ("id" for eg.), but the default functionality of Django will increment the id irrespective of any other data. I'm ok even if id keeps on incrementing as it does, and then I set my own field making it unique per branch and this field should auto increment without the user passing the data by checking the previous value from the database such as - class order_serializer(serializers.ModelSerializer): class Meta: validators = [ UniqueTogetherValidator( queryset=sales_order.objects.all(), fields=['myOwnDefinedField', 'branch'] ) ] I'm in a state of no idea how to achieve this. Using Django 3.1.5. Any help? -
How to change ImageField into FileField in Django?
I have a ImageField in one of the models, is there any way to change that field into FileFiled? If converted how can one identify image during upload? What is the difference between ImageField and FileField in django? -
Django : passing parameter or context with the function redirect and id encoded by hashids
I am a newbie and I need your help ! But maybe it's a complicated question even for experts, who knows! The following code works perfectly to generate a table (using a datepicker form to select the table's day) from the homepage, and with the ID page encoded with hashids in the URL, it redirects to the table URL generated for the day selected. For example, when a specific table is created for a particular day selected by the user, the page is redirected to http://127.0.0.1:8000/O3GWpmbk5ezJn4KR where "O3GWpmbk5ezJn4KR" is one table id encoded with hashids, this works fine. However, I would like to pass a variable with redirect(), the day selected in the datepicker used to create the table, in order to display the date on the html page rendered with the table generated. I tried the reverse function to pass the day variable with redirect, but if failed due to the hashid encoded URL not being recognized by the reverse function (example of error message obtained in the Shell : django.urls.exceptions.NoReverseMatch: Reverse for '/VvJ4openRe7Az1XP' not found. '/VvJ4openRe7Az1XP' is not a valid view function or pattern name.) Have you any idea to help ? Would appreciate any hint ! Best … -
Why getting "This site can’t be reached" when trying to deploy django appplication on heroku?
I am learning how to deploy django application to heroku and to do so,i have completed the following steps:- 1 cloned a git repo which i want to host 2 Install Heroku CLI 3 Run command --> heroku login 4 heroku create <my_app_name> 5 Add to remote --> heroku git:remote -a <my_app_name> Now to push to heroku we need to test it locally,so i installed waitress 6 waitress installed 7 Run waitress using following command waitress-serve -port=8000 <path_to_wsgi.py file>:application Upto this point i have't get any error,waitress starts running:- PS C:\Users\akcai\OneDrive\Desktop\heruko\polling_application> waitress-serve --port=8000 EVCFinder.wsgi:application INFO:waitress:Serving on http://0.0.0.0:8000 urls.py in django application:- urlpatterns = [ path('/admin/', admin.site.urls), path('signup/', user_registration, name="sign_up"), path('login/', user_login, name='login'), path('logout/', user_logout, name='logout'), also in setting.py i have added allowed host as follow:- ALLOWED_HOSTS = ["*"] when i tried to access urls http://0.0.0.0:8000 OR http://0.0.0.0:8000/admin/ got following error:- This site can’t be reached The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID Thanks in advance, Any help will be highly appreciated Hope to here from you soon. -
Django: Making python script run on button click and display output on html page
I have been working on making a python script that will run by clicking a button and then displaying the output in the Django html page. so far I have managed to make a button that will run the script but I am not able to display any results below is the code I have used, it runs the python script in shell but goes no further. In my Views.py def Yellow(request): inp = request.POST.get('param') out = run(['python', '/yellow_page_updated.py', inp], stderr=subprocess.DEVNULL) print(out.stderr) print("Finished!!") return render('Yellow_Page.html', {'data1': out}) In my Urls.py url(r'^Yellow', views.Yellow, name="Yellow") if anybody can help or point me in the right direction i would be very grateful. Thanks for taking a look -
RestAPI unable to download a file sent from Django API to sveltekit client - Fatal error reading a PNG image file
I have a Django Get APIView which returns a FileResponse with a png image data. When it is downloaded on the sveltekit client side then its not being read. It complains that it is not a png file. Not sure what is wrong. Here is the server code: from django.http import FileResponse, HttpResponse import mimetypes # from django.core.files import File mime_type, _ = mimetypes.guess_type('qrcode.png') response = HttpResponse(open('qrcode.png', 'rb'), content_type=mime_type) # response = FileResponse(open('qrcode.png', 'rb'), content_type=mime_type) # response = HttpResponse(open('qrcode.png', 'rb')) # response = HttpResponse(open('qrcode.png', 'rb'), content_type='application/png') # response = HttpResponse(FileWrapper(img), content_type='application/png') response['Content-Disposition'] = 'attachment; filename=qrcode.png' return response I have commented all the possibilities that I tried. Now here is the client side code: if (res.status == 200){ qrimage = await res.data; console.log(typeof(qrimage)); // const blob = new Blob(qrimage); // let url = window.URL.createObjectURL(blob); // let url = window.URL.createObjectURL(qrimage); let a = document.createElement("a"); // console.log(url); a.href = 'data:image/png;'+qrimage; a.target = '_blank'; a.download = 'qrcode.png'; a.click(); // }); } Thank you for help and comments. -
Django - Endpoint JSON empty
When I test my Endpoint i get the right amount of json packages but they are all empty. in the database the entries are correct. When i enter somethin like : /flush/?devid=2&startdate=11/10/21&enddate=29/10/21&resolution=1 i get a json with two elements but both are empty. where did I fail? i created a model: from django.db import models class Flush(models.Model): id = models.AutoField(db_column = 'ID', primary_key = True) devid = models.IntegerField(db_column = 'DEVICE ID',default = 0) time = models.DateTimeField() temp = models.IntegerField() status = models.IntegerField() class Meta: db_table = 'SpuKas' created a view: class FlushView( APIView, ): def get(self,request): devId = int(request.GET.get('devid', '1')) startDate = datetime.strptime(request.GET.get('startdate', '01/01/00'), '%d/%m/%y') endDate = datetime.strptime(request.GET.get('enddate', '01/01/00'), '%d/%m/%y') resolution = int(request.GET.get('resolution', '1')) queryset = Flush.objects.filter(devid=devId, time__range=(startDate, endDate + timedelta(days=1)))[0:1844674407> readSerializer = FlushSerializer(queryset, many = True) return Response(readSerializer.data) and serialized it in the serializers.py: from .models import Flush class FlushSerializer(serializers.Serializer): class Meta: model = Flush fields = '__all__' -
TypeError: decode() got an unexpected keyword argument 'verify' djangorestframework simple jwt
I'm using djoser for authentication and I'm getting TypeError: decode() got an unexpected keyword argument 'verify'. The /jwt/create/ endpoint is working and returning the access and refresh tokens but I can't verify or get the user's details (/auth/users/me/). The same code works in my previous project. Any idea what could be causing the error? {Traceback (most recent call last): File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 414, in initial self.perform_authentication(request) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\views.py", line 324, in perform_authentication request.user File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\request.py", line 227, in user self._authenticate() File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework\request.py", line 380, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\authentication.py", line 40, in authenticate validated_token = self.get_validated_token(raw_token) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\authentication.py", line 94, in get_validated_token return AuthToken(raw_token) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\tokens.py", line 43, in init self.payload = token_backend.decode(token, verify=verify) File "C:\Users\User\dev\ergorite\src\services\backend\venv\lib\site-packages\rest_framework_simplejwt\backends.py", line 90, in decode return jwt.decode( TypeError: decode() got an … -
Creating months based on start date and end date value in django
I have been working on an application where user is required to create monthly tasks, so I made a model named AcademicYear and Months, now I want to take only the start_month and end_month input from user, and based upon the values of these fields, I want to create months automatically once the year object is create. class AcademicYear(SingleActiveModel, models.Model): title = models.CharField(max_length=10) start_month = models.DateField() end_month = models.DateField() def __str__(self): return str(self.title) class Months(models.Model): year = models.ForeignKey(AcademicYear, on_delete = models.PROTECT, related_name='year') months = models.CharField(max_length = 20) ??? what could be the logic or a solution which can be applied here? -
Please explain the proper configuration of jinja2 templating with django(3+). I am not getting clear view about this
I have configured the Django project with default DTL. But I want to use jinja2 templating with the Django project. I am not getting a clear point to configure it properly with Django. As I am new to development. Can someone please help me to understand this, and explain how to configure jinja2 with Django properly? -
select filter once added in the db
I need a filter for that select as you can see in the background there are green blocks with the names written in select, those blocks are associated with a board and then saved in the db. This box is a modal that I need to add a group within my tab, I would like them to disappear every time I add a new one in the db. example I create a box and in the select I put group 5. on click it refreshes the page with the added group 5 and if I had to reopen the modal in the select there must no longer be group5. form class EserciziForm(forms.ModelForm): class Meta: model = models.DatiEsercizi exclude = ['gruppo_single'] class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] html {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">CREA</h1> <a href="{% url 'lista-gruppi' %}" class="btn btn-outline-primary">LISTA</a> </div> <hr> <div class="scheda mb-4"> <div class="d-flex justify-content-between align-items-center"> <h4 style="margin-bottom: 0;">Nome: {{ scheda.nome_scheda }}</h4> <div> <p style="margin-bottom: 0;"> <span><strong>Inizio: {{ scheda.data_inizio }}</strong></span> | <span><strong>Fine: {{ scheda.data_fine }}</strong></span> </p> </div> </div> </div> <div class="box"> {% for gruppo in scheda.gruppi_scheda.all %} <div … -
Send a list in POST requisition - Django Rest Framework
i trying send a list in a POST requisition in Django Rest Framework. My objective like this: Nested Relationship, but i want a list. What i need: { "id": 3435, "titulo": "Livro x", "editora": "Editora x", "foto": "https://i.imgur.com/imagem.jpg", "autores": ["Autor 1"] } What i am getting: { "autores": [ { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } ] } My serializers.py file: from rest_framework.serializers import ModelSerializer from .models import Autor, Livro class AutorSerializer(ModelSerializer): class Meta: model = Autor fields = ('nome') class LivroSerializer(ModelSerializer): autores = AutorSerializer(many=True) class Meta: model = Livro fields = ('id', 'titulo', 'editora', 'autores') def create_autores(self, autores, livro): for autor in autores: obj = Autor.objects.create(**autor) livro.autores.add(obj) def create(self, validated_data, **kwargs): autores = validated_data.pop('autores') livro = Livro.objects.create(**validated_data) self.create_autores(autores, livro) return livro Where i going wrong? -
Invalid data Expected a dictionary, but got ModelBase
{ "non_field_errors": [ "Invalid data. Expected a dictionary, but got ModelBase." ] } I get this error in postman when I try to upload a CSV File through Postman -
Many to many field reverse lookup with TreeQuerySet
I have made no leg way with my issue, I have tried following multiple tutorials but am getting no where. I have looked in these places (and elsewhere) - Django Model API reverse lookup of many to many relationship through intermediary table https://www.revsys.com/tidbits/tips-using-djangos-manytomanyfield/ https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/ https://readthedocs.org/projects/django-mptt/downloads/pdf/latest/ class CategoryTree(MPTTModel): title = models.CharField(max_length=120, default="no name") slug = models.SlugField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') products = models.ManyToManyField(Product, blank=True) class MPTTMeta: order_insertion_by = ['title'] class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) is_digital = models.BooleanField(default=False) # User Library Lets say in the Product models I have an item with the title Iron Man Toy, I need to find a way of finding the category (or categories) it belongs to in the CategoryTree model. I had one solution which came close to solving my problems but if the item was in two seperate categories, then I got an error message. -
Nginx not finding static files in Dockered Django app in Azure Web App for containers
I managed to run my Django app locally with docker compose( Django container + Nginx container) and it works fine, but when i want to run it in Azure web app for containers nginx can't find the ressources. I don't know if i should change some configuration so it can work in Azure services or i need to enable ports in azure app settings therefore my containers could communicate. This is my nginx configuration (nginx.conf) : upstream myapp { server web:8000; } server { listen 80; server_name myappname.azurewebsites.net; location / { proxy_pass http://myapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/static/; } location /media/ { alias /home/app/web/media/; } } I don't know why it did work locally when i run docker compose but in azure web app nginx can't find static files. Please let me know if I need to clarify or include anything else. Thanks in advance.