Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show all the lesson urls present in a lesson list?
I would like to retrieve lesson urls present in lesson model. class Course(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() price = models.FloatField() class Lesson(models.Model): title = models.CharField( max_length=200) course = models.ForeignKey(Course, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) class LessonURL(models.Model): category = models.ForeignKey(Lesson, on_delete=models.CASCADE) title = models.CharField(max_length=200) video_url = models.URLField() Below is my views.py def courseDetail(request, category_slug, course_slug): try: course_detail = Course.objects.get(category__slug=category_slug, slug=course_slug) all_lessons = Lesson.objects.filter(course=course_detail).order_by('created_date') all_lesson_urls = LessonURL.objects.filter(category__id=all_lessons) except Exception as e: raise e context = { 'course_detail': course_detail, 'all_lessons': all_lessons, 'all_lesson_urls': all_lesson_urls, } return render(request, 'course-detail.html', context) Here is my urls.py urlpatterns = [ path('<slug:category_slug>/<slug:course_slug>/', views.courseDetail, name='course-detail'), ] I am trying to explain my issue with the bellow example Ex: Course: "How to Learn Django" In that course i have 3 Lessons i.e Lesson 1, Lesson 2, Lesson 3 And each lesson contains multiple lesson urls. i.e Lesson 1: URL1, URL2, URL3 - Lesson 2 Contains URL4, URL5, URL6, and so on.. So i am facing the issue while extracting the lesson Urls. Now when i run the above code then its showing. Lesson 1 - (URL1, URL2, URL3, URL4, URL5, URL6) Lesson 2 - (URL1, URL2, URL3, URL4, URL5, URL6) But i wanted to show like … -
How do I filter a django model into ChartJS
Im new to Django and Im working on this project where I need to plot the number of employees based on a given hour. Model class Employe(models.Model): name = models.CharField(max_length=20) monday = models.CharField(max_length=20) tuesday = models.CharField(max_length=20) wednesday = models.CharField(max_length=20) thursday = models.CharField(max_length=20) friday = models.CharField(max_length=20) saturday = models.CharField(max_length=20) sunday = models.CharField(max_length=20) def __str__(self): return self.name Every row contains the name of the employee as well as the hour their shift starts at for each day of the week. I want the user to be able to select a certain day (for instance Monday) so that the graph shows how many employees work throughout the day (00:00 -> 23:59) Chart <canvas id="myChart" width="400" height="350"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for emp in employe %} '{{emp.monday}}', {% endfor %}], datasets: [{ label: '# Des employes', data: [], fill: true,}] options: { scales: { y: { beginAtZero: true } } } }); </script> -
What is the best way to transition from imp to importlib for CloudLinux Passenger WSGI files?
I am looking for the best way to transition from imp to importlib with my passenger_wsgi.py file using importlib as recommended by pylint. My passenger file looks like this: import imp import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'core/wsgi.py') application = wsgi.application I have seen some examples using importlib.utils.find_spec(path) and some using importlib.machinery.SourceFileLoader('name','script') Does anyone have an example for their passenger_wsgi.py file that uses the newer method with importlib that would be the new standard they could share? -
import cv2 error on django ImportError: libGL.so.1
i'm working on a django project and i need to use the webcam. i've tried to install opencv-python with pip but python give me back the error ImportError: libGL.so.1: cannot open shared object file: No such file or directory. i've tried to install libGL.so.1 inside Dockerfile: RUN apt-get update RUN apt-get install libgl1 -y but I haven't solved my problem. -
httpd (apache) server django website hosting
I want to host my website on a VPS with Centos 7 I setup httpd (apache) server and set all the configuration in "/etc/httpd/conf/httpd.conf" file but it doesn't work. when i try to access my website in the browser, it will take a lot of time and finally it returns an error 500 & says that there is a problem in your configuration file. can you please check my file, whats wrong with this. # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot … -
Performing group by and aggregrate Django
How can I do the following in Django? SELECT AVG(calories) AS AVG_DAILY_CALORIES FROM ( SELECT date, SUM(calories) FROM products_eaten GROUP BY date ) daily_calories I already have the subquery itself with values and annotate. Adding aggregate after this fails. Thanks in advance! -
DoesNotExist at /settings Profile matching query does not exist. django error
this is the profile model class Profile(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) id_user=models.IntegerField() bio=models.TextField(blank=True) profileimg=models.ImageField(upload_to='profile_images',default='defualtdp.png') location=models.CharField(max_length=100,blank=True) def _str_(self): return self.user.username and in the views.py i tried to get the object like this def settings(request): user_profile=Profile.objects.get(user=request.user) return render(request,'setting.html',{'user_profile':user_profile}) and passed into settings.html <img src="{{user_profile.profileimg.url}}"> <textarea id="about" name="bio" rows="3" class="shadow-none bg-gray-100">{{user_profile.bio}}</textarea> <input type="text" name="location" value="{{user_profile.location}}" class="shadow-none bg-gray-100"> and its showing the error DoesNotExist at /settings Profile matching query does not exist. I am really dont know what to do... -
Use m2m_changed signal on model with related manager
I can set up a m2m_changed signal on one side of the relationship but not both. for example: This works: class Topping(models.Model): # ... pass class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) from django.db.models.signals import m2m_changed def toppings_changed(sender, **kwargs): # Do something pass m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through) But the following gives me the error AttributeError: type object 'Topping' has no attribute 'pizza_set' even though Topping.pizza_set.all() or Topping.pizza_set.through is successful in the shell: class Topping(models.Model): # ... pass class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) from django.db.models.signals import m2m_changed def toppings_changed(sender, **kwargs): # Do something pass m2m_changed.connect(toppings_changed, sender=Topping.pizza_set.through) -
KeyError: 'product_pk' [closed]
Internal Server Error: /store/products/1/images/ Traceback (most recent call last): File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) File "C:\Users\moaz\Desktop\pythoon\The Ultimate Django Series Part 2[TutsNode.com] - The Ultimate Django Series Part 2\Resources\Code\1- Getting Started\Start\storefront2\store\views.py", line 154, in get_queryset return ProductImage.objects.filter(product_id=self.kwargs['product_pk']) KeyError: 'product_pk' Internal Server Error: /store/products/1/images/ Traceback (most recent call last): File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\moaz.virtualenvs\storefront2-IED86ZYE\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File … -
How to get a QuerySet with type of a ForeignKey attribute in Django
I have a simple database model in Django that looks like: class Employee(Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class PrizeDraw(Model): winner = models.ForeignKey( Employee, null=True, on_delete=models.SET_NULL, ) What I want now is a QuerySet of type Employee that contains all the winners of all PrizeDraws. I would have thought that to be fairly straightforward by something something like: def get_queryset(self): return PrizeDraw.objects.exclude(winner__isnull=True).values('winner') However, that doesn't actually return me what I want, instead it returns: <QuerySet [{'winner': (Employee1) }, {'winner': (Employee2) }, etc...]> Which makes sense according to the values() documentation it returns a Dictionary of values. But this doesn't work for me in the rest of the code I need, so I want to select only the second (i.e. value) part of the key-value pair and return that as a QuerySet that just looks like <QuerySet[Employee1, Employee2, etc...]>. How can I select the right value as to get that desired QuerySet? -
Django ContentType and generic relationship
I need a proper and detailed explanation and understanding of how Django content type model works and the use and purposes of generic relationships. I am trying to create an anonymous chatting app where users can come and register and other people can send them messages whether registered or not through a link the user created and they would not know who sent it. -
Send data to another django template/view after specific process using ajax
I have a page where I load 2 files. After a click to the load button, this page reload to display a major part of the data, allowing the user to modified it. After a click to lunch button, I want to launch the process and I want to send to another page the path of results files to allow the user to download it. My problem is after clicking on lunch button and send data to the other page. I have 2 versions : The first one, send data to the result page, but I do not find a way to take back in the view the data modified by the user, the ajax seems to be ignored because of the type "summit" for the button launch : <body> <section class="bg-light py-5 border-bottom"> <div class="container px-5 my-5 px-5"> <div> <h1 class="display-5 fw-bolder mb-2"> Convert to Dose </h1> <br> </div> <form id="formCTD" action="{% url 'json:convertToDose' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} ##here some fields to modified one of them following <div class="row gx-5 justify-content-center"> <div class="col-lg-4 col-xl-4"> {% if factors %} <input name="img_path" readonly class="form-control" {{ pathAnalyseForm.img_path }}> {% else %} <input id="btn-submit-form-jsonfile" class="btn btn-lg" {{ formImgFile.imgFile }}> {% endif … -
Django - How to access parent object for passing as URL primary key inside templates?
I have two Django models: class AP(models.Model): room = models.ForeignKey(Room, on_delete=models.SET_NULL, null=True) and class Room(models.Model): name = models.CharField(max_length=20, unique=True) I have passed an object of AP class as ap to the template. In the template, I am trying to create a hyperlink with ID of the room. I am creating hyperlink through the following line: <a href="{% url 'edit_ap' ap.room.id %}">{{ap.room.name}}</a> This is throwing the following error: Reverse for 'edit_ap' with arguments '('',)' not found. 1 pattern(s) tried: ['edit\\-ap/(?P<pk>[^/]+)/$'] The urls.py has the following matching pattern: path('edit-ap/<str:pk>/', views.edit_ap, name='edit_ap'), The hyperlink is working if the primary key is changed from ap.room.id to ap.room, which passes room.name as the primary key to the URL. However, I need to provide ap.room.id as the primary key. I believe it has to do with using two dots in the primary key. Can you please suggest how can I pass ap.room.id as primary key to my URL? Thank you. -
django clean method is not being called when validating form
I tried the simplest way of form validation I could find using the clean method (I need to validate multiple fields). However, it is not working and it is not throwing any errors. forms.py class DOEForm1(ModelForm): class Meta: model = Doe labels = { 'column_parameter': ('Parameter to vary'), 'column_min': ('Minimum value'), 'column_max': ('Maximum value'), 'column_step': ('Step value'), } exclude = ('substrate','row_parameter','row_min','row_max','row_step',) def clean(self): cleaned_data = super().clean() print('test') min = cleaned_data.get('column_min') max = cleaned_data.get('column_max') step = cleaned_data.get('column_step') if min and max and step: if not (int(step) > 10): raise ValidationError( '(!) the parameters you inputted dont go well with the substrate size' ) return cleaned_data template {% extends 'accounts/main.html' %} {% load static %} {% block content %} <br> <div class="row" style = "padding-left: 15px; width: 500px; margin: auto;"> <div class="col" style = "margin: auto; "> <div class="card card-body"> <form style = "margin: auto; width: 400px; padding: 20px; border: 1px solid #270644;" action="" method="POST"> {% csrf_token %} <table> {{ St_form.as_table }} {{ DOE_form.as_table }} </table> {% for error in form.non_field_errors %} <p class = "help is-danger">{{ error }}</p> {% endfor %} <input type="submit" name="Submit" > </form> </div> </div> </div> {% endblock %} views.py def ST_parameters(request): st_form = STForm() doe_form = DOEForm1() … -
working with SQLSERVER database that doesn't have keys using DJANGO
I'm currently doing an internship at a company, they asked me to build an invoice management web app, the process is a little complicated. First I created the login page, home page and the core elements of every web app. I used PostgreSQL for this, but when I wanted to build the main functionalities of the app, I switched to a copy of their database, they are using SQL Server 2012 and the data is coming from an ERP. The problem is when I have connected to database and use inspect DB to get the tables, I discovered that all the tables in the database don't have a Primary Key or Foreign Key. I asked the IT responsible about this and he told me that the ERP is stocking the data without any keys, it uses another method. I would really appreciate it if someone could help me out of this issue. -
Django - making form which contains two related models
I wonder if it is possible to make a django model based form which will allow to create two models which one will be passed as a foreign key to second one. let we have these models: class Book(models.Model): title = models.CharField(max_length=200) published = models.DateField() def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(max_length=200) number = models.IntegerField() book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return self.name I'd like to make a view which will contain BookForm and many ChapterForms somehing like: Book.title = [input] Book.published = [input] and below that (still in the same view) Chapter.name = [input] Chapter.number = [input] Chapter.name = [input] Chapter.number = [input] add more chapters After submitting form, Book and related chapters should be created How can I achive it ? Till now I was just making two views: one for making a Book and second one for chapter which gets created book's id as a parameter in url, but I'd like to make it in one view -
Different methods of Django User model
I have been using Django for 4 5 months now and i have been implimenting users by importing the user class like this example 1: from django.db import models from django.contrib.auth.models import User class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_name = models.CharField(max_length=150) desription = models.CharField(max_length=200) image = models.ImageField(upload_to="images/uploads") def __str__(self): return self.desription and i have seen some people use the user model like this : example 2: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=220) description = models.TextField(blank=True, null=True) directions = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) and also like this : example 3: author = models.ForeignKey(get_user_model()) now I have used both example 1 and example 2 for my projects and to mess around in my free time and both seem to work fine , I am wondering what would be the use cases for these different methods and also is there any pros or cons to these methods of using the User Model? -
Add health check to Kafka consumer k8s pods
How to add health check(liveness/readiness) in Kafka consumer pods in my Django application. New to this infra-structure related things. Please help in implementing a periodic health check for Kafka consumer pods in my application so that it does not allow pods to rotate if their health is not perfect if there is any issue. -
Configuration Heroku, daphne, redis - CHANNELS
I'm trying to get django channels to work with daphne, apparently daphne (PROCFILE) works and redis (part of CHANNEL_LAYERS) too, but I can't connect, whenever I run the app, and open a "room" it automatically disconnects, it is worth mentioning that my site is running with HTTPS and has a valid certificate 2022-08-19T13:20:57.879758+00:00 app[worker.1]: conn = await self.create_conn(loop) 2022-08-19T13:20:57.879769+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/channels_redis/core.py", line 79, in create_conn 2022-08-19T13:20:57.879862+00:00 app[worker.1]: return await aioredis.create_redis_pool(**kwargs) 2022-08-19T13:20:57.879863+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/commands/__init__.py", line 188, in create_redis_pool 2022-08-19T13:20:57.879967+00:00 app[worker.1]: pool = await create_pool(address, db=db, 2022-08-19T13:20:57.879978+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/pool.py", line 58, in create_pool 2022-08-19T13:20:57.880062+00:00 app[worker.1]: await pool._fill_free(override_min=False) 2022-08-19T13:20:57.880073+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/pool.py", line 383, in _fill_free 2022-08-19T13:20:57.880224+00:00 app[worker.1]: conn = await self._create_new_connection(self._address) 2022-08-19T13:20:57.880233+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/connection.py", line 133, in create_connection 2022-08-19T13:20:57.880336+00:00 app[worker.1]: await conn.auth(password) 2022-08-19T13:20:57.880345+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/util.py", line 52, in wait_ok 2022-08-19T13:20:57.880426+00:00 app[worker.1]: res = await fut 2022-08-19T13:20:57.880437+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/connection.py", line 186, in _read_data 2022-08-19T13:20:57.880564+00:00 app[worker.1]: obj = await self._reader.readobj() 2022-08-19T13:20:57.880576+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/stream.py", line 102, in readobj 2022-08-19T13:20:57.880669+00:00 app[worker.1]: await self._wait_for_data('readobj') 2022-08-19T13:20:57.880680+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/asyncio/streams.py", line 502, in _wait_for_data 2022-08-19T13:20:57.880853+00:00 app[worker.1]: await self._waiter 2022-08-19T13:20:57.880863+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/asyncio/selector_events.py", line 854, in _read_ready__data_received 2022-08-19T13:20:57.881081+00:00 app[worker.1]: data = self._sock.recv(self.max_size) 2022-08-19T13:20:57.881108+00:00 app[worker.1]: ConnectionResetError: [Errno 104] Connection reset by peer 2022-08-19T13:20:58.216868+00:00 heroku[worker.1]: … -
'list' object has no attribute '_committed'
this is my problem 'list' object has no attribute '_committed' how to solve pls help me. enter image description here def add_trainer(request): if request.user.is_authenticated: if request.method == 'POST': print(request.POST) trainer_name = request.POST.get('trainer_name') adderes = request.POST.get('adderes') phone_no = request.POST.get('phone_no') phone_no_optional = request.POST.get('phone_no_optional') email = request.POST.get('email') email_optional = request.POST.get('email_optional') gender = request.POST.getlist('gender') trainer_international = request.POST.getlist('trainer_international') trainer_pricing = request.POST.get('trainer_pricing') trainer_course_specialization = request.POST.get('trainer_course_specialization') trainer_skill_set = request.POST.get('trainer_skill_set') trainer_enrolled_with = request.POST.get('trainer_enrolled_with') trainer_tier = request.POST.get('trainer_tier') trainer_attachment = request.POST.getlist('trainer_attachment') obj = Trainer(trainer_name=trainer_name, adderes=adderes, phone_no=phone_no, phone_no_optional=phone_no_optional, email=email, email_optional=email_optional, gender=gender, trainer_international=trainer_international,trainer_pricing=trainer_pricing, trainer_course_specialization=trainer_course_specialization, trainer_skill_set=trainer_skill_set, trainer_enrolled_with=trainer_enrolled_with, trainer_tier=trainer_tier, trainer_attachment=trainer_attachment) obj.save() learning_path = Learning_Path.objects.all() df= {'learning_path': learning_path} return render(request, 'add_trainer.html', df) else: print('hello') return render(request, 'add_trainer.html') else: html = '<!DOCTYPE html><html><head></head><body><h1> Unauthorized Access </h1></body></html>' return HttpResponse(html) please help me to solve this as soon as possible -
Problem in posting Django API it shows "name": [ "This field is required." ]
this is my serializers.py from rest_framework import serializers from api.models import Movie class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name=serializers.CharField() description= serializers.CharField() viewed = serializers.BooleanField() def create(self,validated_data): return Movie.objects.create(**validated_data) this is my models.py class Movie(models.Model): name = models.CharField(max_length=20) description = models.CharField(max_length=100) viewed=models.BooleanField(default=True) def __str__(self): return self.name this is views.py @api_view(['GET','POST']) def home(request): if request.method == 'GET': movies=Movie.objects.all() serializer=MovieSerializer(movies,many=True) return Response(serializer.data) if request.method == 'POST': serializer=MovieSerializer(data=request.POST) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) this is what my output looks like { "name": [ "This field is required." ], "description": [ "This field is required." ] } -
How to create multiple orderitems according to number of dictionaries in list?
This is the data I am sending through postman raw(json) section. And data = json.loads(request.body) and following data are same data = [{'quantity': 2, 'service_id': 1, 'price': 2}, {'quantity': 2, 'service_id': 1, 'price': 2}, {'quantity': 2, 'service_id': 1, 'price': 2}] @api_view(['GET', 'POST']) @csrf_exempt def create_order(request, *args, **kwargs): if request.method == 'POST': now = datetime.date.today() order = Order.objects.create(date=now) order.save() orderid = order.id order_id = orderid data = json.loads(request.body) print('data = '+ str(data)) price = request.session.get('price') print('Price = ' + str(price)) quantity = request.session.get('quantity') print('quantity ' + str(quantity)) service_id = request.session.get('service_id') print("Service id = "+ str(service_id)) orderitemslist = [int(v) for lst in data for k,v in lst.items()] quantity = orderitemslist[1] service_id = orderitemslist[2] price = orderitemslist[3] for item in orderitemslist: orderitemcreate= OrderItem.objects.create(order_id_id=order_id, quantity=quantity, service_id_id=service_id, price=price) orderitemcreate.save() return Response({"data created"}) else: order_qs = models.Order.objects.all().values_list() OrderItem_qs = models.OrderItem.objects.all().values_list() return Response({"Order":str(order_qs),"OrderItem":str(OrderItem_qs)}) I want to store data in db like if there are three [{'quantity': 2, 'service_id': 1, 'price': 2}, {'quantity': 2, 'service_id': 1, 'price': 2}, {'quantity': 2, 'service_id': 1, 'price': 2}] dictionaries in list. The loop should create 3 Orderitem and store each value in table. But it creates 9 orderitems because there are 9 colums(1 dict has 3 col) 3 dicts = 9 cols … -
I can't understand why the form in django is invalid
models.py class User(AbstractUser): is_employer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) phone = models.CharField(max_length=9, blank=True, null=True) avatar = models.ImageField(upload_to='avatar/', blank=True, null=True) class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='employer', related_query_name='employer') company_name = models.CharField(max_length=255) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='employee', related_query_name='employee') cv = models.FileField(upload_to='cv/') views.py class EmployeeCreateView(CreateView): model = User form_class = EmployeeForm template_name = 'common/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'employee' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('common:index') forms.py class EmployeeForm(UserCreationForm): cv = forms.FileField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_employee = True user.save() employee = Employee.objects.create(user=user, cv=self.cleaned_data.get('cv')) return user and i read article on the internet about Multiple Users. https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html -
cannot use django ckeditor rich text field content in vue
I hope you are fine. I have a rich text field in my django model and I want to show the content in a vue js template but unfortunately the content is completely in html tags and when I want to show this in the template it shows an html code. I will thank anyone to give me a piece of guidance about this matter. -
Django, despite of setting request.method to POST it's GET in view
I'm making Django app and I have an issue, I've never had problem with before. As always in form view, I'm checking if request.method == 'POST' but somehow it returns False, My code looks like that: def recipe_create_view(request): context = {} form = RecipeForm() IngredientFormset = formset_factory(IngredientForm) formset = IngredientFormset() print(request.method) # prints GET if request.method == 'POST': form = RecipeForm(request.POST) formset = IngredientFormset(request.POST) if form.is_valid(): if formset.is_valid(): form.save() print("made a recipe") for form in formset: child = form.save(commit=False) child.recipe = parent child.save() print("made an Ingredient") return redirect('index') else: print("formset is not valid") else: print("form is not valid") else: print("request method is not correct") # I can see it every time in console context['form'] = form context['formset'] = formset return render(request, 'recipes/create_recipe.html', context) create_recipe.html <form method="POST"> {% csrf_token %} <label>recipe</label> <p>{{form}}</p> <label>ingredients</label> {% for form in formset %} <ul> <label>name</label> <li>{{ form.name }}</li> <label>quantity</label> <li>{{ form.quantity }}</li> </ul> {% endfor %} <div> <input type="submit" value="submit" class="button-33" role="button"> </div> </form> Where is the issue, it so annoyoing. I have already checked plenty of articles and nothing helps