Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fixing a NoReverseMatch Error for a Django Project
I am trying to fix a No Reverse Match error for my django project but I am unable to figure out the reason and the sequence of thinking to fix it. My objective is to click on a button and change the status of a boolean from False to True and if the status is False to appear and if it is true disappear. Here is the model: class Workout(models.Model): active = models.BooleanField(default=False) Here is the view: def change_status(request, pk): url = request.META.get('HTTP_REFERER') # get last url startsession = Workout.objects.get(id=pk) startsession.active = True startsession.save() return HttpResponseRedirect(url) Here is the template: {% if startsession.active %} <button disabled="disabled" type="button">Start the workout</button> {% else %} <a href="{% url 'my_gym:bla' startsession.pk %}"> <--------Error here <button type="button">Start the workout</button> </a> {% endif %} here is the url: path('workout/bla/<int:pk>/', change_status, name='bla'), and finally here is the error Traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File … -
Is it possible to include djoser urls and custom model urls in one querystring?
urlpatterns = [ path('users/', include('users.urls')), path('users/', include('djoser.urls')), path('users/', include('djoser.urls.jwt')), ] it gives me error when I try to include djoser.urls and users.urls in one path. Are there any options to do this? -
Can't set user.is_active and user.is_superuser to True
I need to use email for authentication instead of user but when ever I create super user it doesn't set the is_active and is_superuser to True which are False by default! models.py class CustomUserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('User must have an email') if not password: raise ValueError("User must have a password") user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user(email, username, password) user.is_active = True user.is_staff = True user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField(max_length=200,unique=True) username = models.CharField(max_length=200, unique=True) last_login = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email objects = CustomUserManager setting AUTH_USER_MODEL = "account.User" SQL table for users id ... is_active is_staff is_admin is_superuser 1 ... 0 1 0 1 2 ... 0 1 0 1 3 ... 0 1 0 1 4 ... 0 1 0 1 -
Zero Values Not Shown in Integer Field of Django Form
In a Django project, I have a very simple form with three integer fields: class SpecItemForm(forms.Form): n1 = forms.IntegerField() n2 = forms.IntegerField() n3 = forms.IntegerField() def __init__(self, *args, **kwargs): super(SpecItemForm, self).__init__(*args, **kwargs) I instantiate the form from views.py with code like this: initial_values = {} initial_values['n1'] = 1 initial_values['n2'] = 0 initial_values['n3'] = 3 form = SpecItemForm(initial=initial_values) I expect the form to be rendered with the specified initial values for the three integer fields but this only works for non-zero initial values. For instance, in the example above, I see the initial values for fields n1 and n3 (initial values are, respectively, '1' and '3') but not for n2. Why is an initial value of zero not rendered? -
How to convert an array of objects to object of objects in python
How do I convert this array of objects to object of objects in python [ { "id": 7, "name": "science" }, { "id": 8, "name": "Sports" }, { "id": 9, "name": "culture" }, { "id": 10, "name": "Communication" } ] I will like it to be like this { { "id": 7, "name": "science" }, { "id": 8, "name": "sports" }, { "id": 9, "name": "culture" }, { "id": 10, "name": "Communication" } } -
Django dynamic filter from user input with json date
I need to have a dynamic filter for the user(Admin). There the Admin inputs a date and based on that date Admin sees results to that corresponding date. My problem right now is, I convert it to json bc I dont think that django can do that. the model would be like that class employeemodel(etc): name = etc something = etc from date 1 = date 1 status 1 = status 1 to date 1 = to date 1 from date 2 = date 2 status 2 = status 2 to date 2 = to date 2 I cant lookup every entry in that model, so I have a _set in my tempalte bc the user(admin) searches for entries from user(staff) {% for i in something.employeemoddel_set.all %} {{i.from date 1}} {{i.status 1}} {{i.to date 1}} {{i.from date 2}} {{i.status 2}} {{i.to date 2}} etc Now the admin user sees all entries from one staff user. Admin now needs to have an input field where he can enter a date. Based on that date the entry from staff user in the employeemodel now should show either status 1 or 2 or nothing bc of the date input from Admin. How should … -
Django form post doesn't save to DB
The form I made on Django doesn't save any data, I think it's a validation issue but I can't find where the problem is - whenever I click on the "submit" button the page is refreshed but no new entries are created - when I do that from Django Admin it works fine. I'm a complete beginner and this is my very first Django project. models.py class Utente(models.Model): id_utente = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) gen_utente = models.CharField(max_length=7, choices=GEN_CHOICES) age_utente = models.CharField(max_length=2) con_utente = CountryField() per_utente = models.CharField(max_length=18, choices=PER_CHOICES) pres_utente = models.CharField(max_length=11, choices=PRES_CHOICES) doc_utente = models.CharField(max_length=29, choices=DOC_CHOICES) vis_utente = models.CharField(max_length=10, choices=VIS_CHOICES) san_utente = models.CharField(max_length=17, choices=SAN_CHOICES) nnb_utente = models.CharField(max_length=5, choices=NNB_CHOICES) unnb_utente = models.CharField(max_length=8, choices=UNNB_CHOICES) va_utente = models.CharField(max_length=12, choices=VA_CHOICES) tem_utente = models.DateField() res_utente = models.CharField(max_length=5000) def __str__(self): return f'Utente n: {self.id_utente} del {self.tem_utente}' forms.py (I've removed the labels) class UtenteForm(forms.ModelForm): class Meta: model = Utente fields = ['id_utente', 'gen_utente', 'age_utente', 'con_utente', 'per_utente', 'pres_utente', 'doc_utente', 'vis_utente', 'san_utente', 'nnb_utente', 'unnb_utente', 'vac_utente', 'tem_utente', 'res_utente'] labels = { 'id_utente': '.......', 'gen_utente': '.......', 'age_utente': '.......', 'con_utente': '.......', 'per_utente': '.......', 'pres_utente': '.......', 'doc_utente': '.......', 'vis_utente': '.......', 'san_utente': '.......', 'nnb_utente': '.......', 'unnb_utente': '.......', 'vac_utente': '.......', 'tem_utente': '.......', 'res_utente': '.......' } widgets = { 'id_utente': forms.TextInput(attrs={'class': 'form-control', 'disabled': True}), 'gen_utente': forms.Select(choices=SESSO_CHOICES, attrs={'class': … -
Unable to retrieve static files into a django project from S3 bucket, but able to upload. Any suggestions?
Following is the settings.py file. I've tried varying combinations of enabling and disabling STATIC_ROOT, status quo remains disabled. Have added CORS and Bucket policy as per templates available on AWS. Alas ! Still no CSS rendered. Django settings for baatcheet project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path import sec # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ with open(os.path.join(BASE_DIR, 'secret_key.txt')) as f: SECRET_KEY=f.read().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['https://test-astratechztestapp.pagekite.me', 'localhost', '127.0.0.1', '*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', 'rest_framework', 'corsheaders', ] AUTH_USER_MODEL = 'base.User' MIDDLEWARE = [ 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'baatcheet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 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', ], }, }, ] WSGI_APPLICATION = 'baatcheet.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { … -
i need to put javascript validation in django
I have a javascript validation but it doesn't work for me, I think it may be sweet alert I think that sweetalert is validating before the validation that I have in javascript javascript validation: const $email_validation = document.getElementById('email_validation'); const $contrasena_validation = document.getElementById('contrasena_validation'); const $formularioempleado = document.getElementById('formularioempleado'); var $expresion_email, $expresion_password; $expresion_email = /^([\da-z_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; $expresion_password = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/; (function() { $formularioempleado.addEventListener('submit', function(e) { let email=String($email_validation.value).trim(); let contrasena=String($contrasena_validation.value).trim(); if(email.length === 0 || contrasena.length === 0){ alert("Todos los campos son obligatorios"); e.preventDefault(); } else if(email.length>100){ alert("El correo es muy largo"); e.preventDefault(); } else if(!$expresion_email.test(email)){ alert("El correo no es valido"); e.preventDefault(); } else if(contrasena.length>255){ alert("La Contraseña es muy larga"); e.preventDefault(); } else if(!$expresion_password.test(contrasena)){ alert("Contraseña: Debe contener al menos un numero y una letra mayúscula y minúscula, y al menos 8 caracteres o más"); e.preventDefault(); } e.preventDefault(); }); })(); createuser.html: {% extends 'app/base.html' %} {% block contenido %} {% load crispy_forms_tags%} <div class="container"> <div class="row"> <div class="col-md-3"> </div> <div class="col-12 col-md-6 content m-0 mt-2 mb-2 pt-2 pb-2" > <form class="p-0" method="POST" id="formularioempleado"> {% csrf_token %} <h2 class="text-center">Crear Empleado</h2> <hr> {{empleado | crispy}} <input class="btn btn-primary mb-2" type="submit" value="Crear Usuario"> <hr> </form> </div> <div class=" col-md-3"> </div> </div> </div> views.py(here i have the message of the sweetalert) def … -
Why does django admin inline save fails when inline contains readonly primary key?
Why isn't it possible to have a readonly inline related object in the django admin? In the example below, as soon as I add id in the readonly_fields, it breaks when trying to save the OtherFoo model. I found this ticket in the django project that was closed years ago and the alternate ticket does not help. class FooInline(admin.TabularInline): model = Foo fields = ( "id", "link", "content", ) readonly_fields = ( "id", # <=============== "link", "content", ) class OtherFooAdmin(admin.ModelAdmin): inlines = [ FooInline, ] -
Adding a Direct Messaging page to react native social media app with Django backend
I am trying to develop a react native social media app with Django backend. I need my app to have a Direct Messaging page. I already have made the Django backend and the React Native frontend without the messaging functions. How can I add the Direct Messaging to my existing backend and frontend? -
Why do i need to use a virtual envirotment with django?
I'm new to django and i want to know why i need to use a virtual enviroment for django. (you have not to read the next it's for stack overflow) i just get started with web developpement blablablablabalabalablablabalablablabalaablablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalanablabalabblablabalabalan -
How to filter by all in queryset
I've got a queryset within a function. In some cases, I want to filter by a specific model. cars = Car.objects.filter(model='Toyota') In other cases, I don't want to filter by this field at all. Eg. (Syntax is wrong, but it demonstrates what I'm after) cars = Car.objects.filter(model=all) How do I include a field within a queryset as shown above, but prevent it from limiting the results? Thanks! -
How to serve a css file in production using django 4.1?
I have been stuck on this for two days now, I've searched high and low but can't find the solution. I'm trying to use a base.css file in production to render my CSS but it's not working. When I run python manage.py runserver I get this error "GET /static/css/base.css HTTP/1.1" 404 1896 When I run python manage.py findstatic base.css It can find the base.css file file Found 'base.css' here: C:\Users\static\base.css. I think my setup is correct but I must be missing something If someone could help me I would really appreciate it. I'm using Django 4.1 in VS code. settings.py import os BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'home', ] STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('home.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) base.html CSS link {% load static %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"> home app index.html {% extends "base.html" %} {% load static %} -
AttributeError at /appointment/create-appointment/ '__proxy__' object has no attribute 'get'
I had created a appointment creation form and appointment book form whenever I login as doctor or user and try to create or book appointment respectively it is showing me error after I click copy/paste view to find out error I am not getting can you please help me out. below is error and code. Request Method: GET Request URL: http://127.0.0.1:8000/appointment/create-appointment/ Django Version: 3.2.7 Python Version: 3.9.6 Installed Applications: ['m1.apps.M1Config', 'authenticate_me.apps.LoginModuleConfig', 'appointment.apps.AppointmentConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', '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 "C:\Users\Ashraf\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Ashraf\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\deprecation.py", line 119, in __call__ response = self.process_response(request, response) File "C:\Users\Ashraf\AppData\Local\Programs\Python\Python39\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /appointment/create-appointment/ Exception Value: '__proxy__' object has no attribute 'get' code: class AppointmentCreateView(CreateView): template_name = 'appointment/create-appointment.html' form_class = CreateAppointmentForm extra_context = { 'title': 'Post New Appointment' } success_url = reverse_lazy('appointment:home1') @method_decorator(login_required(login_url=reverse_lazy('authenticate_me:login'))) def dispatch(self, request, *args, **kwargs): if not self.request.user.is_authenticated: return reverse_lazy('authenticate_me:login') if self.request.user.is_authenticated and self.request.user.is_doctor: return reverse_lazy('authenticate_me:login') return super().dispatch(self.request, *args, **kwargs) def form_valid(self, form): form.instance.user = self.request.user return super(AppointmentCreateView, self).form_valid(form) def post(self, request, *args, **kwargs): self.object = None form = self.get_form() if form.is_valid(): return self.form_valid(form) … -
How to pass keys and values in ModelForm ModelChoiceField in django
I have three tables user, doctor, and patient. User table contains Username , password, status , etc. User table is auth table of Django. doctor table contains id, user_id(foreign key),and other information. patient table contain doctor_assignid(foreign key), name ,etc. so, trying to get the username from user table and id form doctor table. And pass those data in ModelForm ModelChoiceField. class PatientForm(forms.ModelForm): assigned_doctor=forms.ModelChoiceField(queryset=None,empty_label="Name of the Doctors",to_field_name='username') class Meta: model= patient fields=['patient_first_name','patient_last_name','address','mobile','age','symptoms'] def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(PatientForm, self).__init__(*args, **kwargs) if self.request: users = self.request.user.id adminId = hospitalAdmin.objects.all().filter(user_id=users).values('pk') doctors=doctor.objects.filter(assigned_hospitalAdmin=adminId[0]['pk']) userTableDoctor = User.objects.filter(id__in=[i.user_id for i in doctors],status=True) userTableDoctor = userTableDoctor.values('username','doctor__id') assignedDoctorId = self.fields['assigned_doctor'] assignedDoctorId.queryset = userTableDoctor but, I'm getting dictionary like querset like this which is not an acceptable parament to pass. So, I want to display the username and If the user selects the username the backend receives the doctor id. So, is there any way to pass as an object or any other way to solve it -
In javascript when adding an image, the src can't find the image because it redirects firstly to the html file and then searches for the image
How do i add an image without it going thrue the html file first? test is the html file. It shows "not found" cause it goes thrue the html file first which is test GET http://127.0.0.1:8000/test/images/a11.png 404 (Not Found) Javascript file var imgQuestion1 = document.createElement("img"); imgQuestion1.src = "images/a11.png"; var block = document.getElementById("question"); block.appendChild(imgQuestion1); -
django/drf: many-to-many, serializer, duplicates
I have M2M relationship between models Combo and ComboLinks. User should be able to provide ComboLinks that are gathered by the backend into a one Combo. This is done with through DRF serializer and it works but with an issue: if a user provides a list of ComboLinks that has one or more ComboLinks already present in the database - duplicate is created. How can I avoid creating those duplicates and use already present ComboLinks to point to new Combo object? django model structure: class Combo(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='searches') updated = models.DateTimeField(auto_now = True) class ComboLink(models.Model): combo = models.ManyToManyField('Combo', blank=True, related_name='links') title = models.CharField(max_length = 64, null=True, blank=True) django view: @api_view(['GET', 'POST', 'PUT', 'DELETE']) def getCombo(request, pk=None): user = request.user # for all paths besides create new search if (pk != 'new') and (pk != None): combo = Combo.objects.get(id=int(pk)) if user != combo.user: return Response('Not valid user for a search', status=status.HTTP_401_UNAUTHORIZED) # handle different request methods if request.method == 'GET': serializer = ComboSerializer(combo, many=False) return Response(serializer.data, status=status.HTTP_200_OK) if request.method == 'POST': data = request.data data['user'] = user.id combo = Combo.objects.create(user= User.objects.get(id=user.id)) serializer = ComboSerializer(instance = combo, data = data) if serializer.is_valid(): print('updateSearch: combo serializer IS valid') serializer.save() combo.save() … -
Django forbidden 403 Origin checking failed csrf failed
I'm running django on a docker machine. Everything works just fine, but when I want to login into the admin site I get 403 forbidden Origin checking failed - https://example.com does not match any trusted origins. I've tried to add some other settings like: ALLOWED_HOSTS = [ "example.com", "127.0.0.1", "localhost", ] CSRF_TRUSTED_ORIGIN = ["https://example.com"] if PRODUCTION: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True as it is mentioned here and here but it doesn't work either. This is my nginx setup: server { server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/example/data/static/; } location /media/ { alias /home/example/data/media/; } location / { proxy_pass http://127.0.0.1:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } how do I fix this error? -
How to configure Django Dynamic Menu with the URLs.py
My app is generating a list that would be the side menu, like this: Views.py: def generate_menu(request): array = [] deviceList = [] f1 = open('dictionary.txt', 'r') array = f1.read() array = literal_eval(array) for i in sorted(array): deviceList.append(i) f1.close() context.update({'deviceList': deviceList}) return render(request, "device_list.html", context) Now in my Template, I am doing this to create the menu based on dic file: device_list.html: <nav id="sidebar"> <ul class="list-unstyled components"> <li class="active"> <a href="device_list">Device List</a> </li> {% block devices %} {% for each in deviceList %} <li> <form action="/{{each}}" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" value={{each}} name='DEVICES'>{{each}}</button> </form> </li> {% endfor %} {% endblock %} </ul> </nav> URLs.py: url(r'^$', app.views.index), url(r'^(?P<string>.+)$', app.views.generate_menu, name='DEVICES'), and it doesn't work here. So how can I change the URL in a way to accept all kind of request like http://127.0.0.1/Device* because all device list names, are different and they need their own url. So I need to have a url path that is dynamic. -
CKEditor breaks when debug = False
I'm nearing the end of my project, a blog. I have set DEBUG = False for security. This breaks my CKEDITOR, making it just not appear at all when the page is loaded. When DEBUG = True it works fine. template: <form class="text-center m-3" action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <button class="btn btn-signup right" id="button">Post &raquo;</button> forms.py: class PostForm (forms.ModelForm): class Meta: model = Post fields = ('title', 'excerpt', 'featured_image', 'content', 'author') widgets = { 'title': forms.TextInput(attrs={'placeholder': 'Give it a catchy title'}), 'excerpt': forms.TextInput(attrs={'placeholder': 'E.g. My first ever post'}), 'content': forms.Textarea( attrs={'placeholder': '<p>Wrap your content in these P tags to create a paragraph</p> \ \n\n<b>Wrap your words in these B tags \ to make them bold</b>'}), 'author': forms.TextInput( attrs={'class': 'form-control', 'value': '', 'id': 'user', 'type': 'hidden'}), } -
How to post data in nested serializer using id field
I'm trying to post data in nested serializer using only id field, but it does not work. This project is for making orders in restaurants What i want to see Here is how i push data: { "is_done": false, "dishes": [ {"dish":1} ] } The GET request looks like this: { "id": 14, "is_done": false, "dishes": [ { "dish": 1, "quantity": 1 } ] } But I want to see it like this { "id": 14, "is_done": false, "dishes": [ { "dish": { "id": 1, "name": "Simple dish 1", "price": "200.00" }, "quantity": 1 } ] } Here is my python code OrderItemSerializer OrderSerializer class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ( 'dish', 'quantity', ) class OrderSerializer(serializers.ModelSerializer): dishes = OrderItemSerializer(many=True, read_only=False) class Meta: model = Order fields = ( 'id', 'is_done', 'dishes', # 'created_at', # 'updated_at', ) def create(self, validated_data): order_items = validated_data.pop('dishes') order = Order.objects.create(**validated_data) for dish in order_items: OrderItem.objects.create(order=order, **dish) return order def update(self, instance, validated_data): order_items = validated_data.pop('dishes') instance.is_done = validated_data.get('is_done', instance.is_done) instance.save() for dish in order_items: order_item = OrderItem.objects.get(order=instance) order_item.dish = dish['dish'] order_item.quantity = dish['quantity'] order_item.save() return instance Models class Order(models.Model): is_done = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = … -
Django MultiPartParserError
I am trying to send image to the django server. Here is my code: @csrf_exempt def classify_image(request): if request.method == 'POST' and request.FILES: try: image = request.FILES['file'] if image: img_b64 = b64encode(image.read()) res = main.classify_image(img_b64) return JsonResponse({ "status": "ok", "result": { "class": res[0], "confidence": res[1], } }) except Exception as e: return JsonResponse({ "status": "error", "error": str(e) }) return JsonResponse({ "status": "error", "error": "Image file is required" }) But I keep on getting I am sending requesting using postman, here's the sample The weird thing is the code was working perfectly fine some hours ago. Later I didn't change a single thing but it was throwing error. -
Integrity error while adding foreignkey in a migrated table
I tried to add a foreign that is already migrated but it seems error like django.db.utils.IntegrityError: insert or update on table "adminpanel_product" violates foreign key constraint "adminpanel_product_categories_id_id_cd41514d_fk_adminpane" DETAIL: Key (categories_id_id)=(1) is not present in table "adminpanel_categories". -
How to create or update a model with Django REST Framework?
I would like to create or update a model Account by specifying the fields id and params with the REST Framework. To begin with, I try to create the model but I'm constantly getting 400 or 500 error code. What am'I missing? client data = dict(id=18, params=dict(foo='bar')) res = requests.post('http://container-django-1:8002/api/account/', data=data, headers={'Authorization': 'Bearer {0}'.format(instance.bookkeeper.jwt_token)} ) server models.py class Account(TimestampedModel): active = models.BooleanField(null=True, blank=True, default=False) params = models.JSONField(default=dict, blank=True) views.py class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer queryset = Account.objects.all() http_method_names = ['post'] serializer.py class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('id', 'params',) def create(self, validated_data): return Account.objects.create(id=validated_data['id'], params=validated_data['params']) urls.py router = routers.DefaultRouter() router.register("account", AccountViewSet, basename="accounts-list") urlpatterns = [ path('', include(router.urls)), ] Output container-django-1 | 2022-09-03T18:14:22.785593661Z Starting development server at http://0.0.0.0:8002/ container-django-1 | 2022-09-03T18:14:22.785604944Z Quit the server with CONTROL-C. container-django-1 | 2022-09-03T18:17:09.252092179Z Bad Request: /api/account/ container-django-1 | 2022-09-03T18:17:09.253001155Z Bad Request: /api/account/ container-django-1 | 2022-09-03T18:17:09.261351802Z [03/Sep/2022 18:17:09] "POST /api/account/ HTTP/1.1" 400 40