Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't display an image in react from backend django
I want to display an image which I got the src from in the database linked to django on localhost 8000, in react (localhost 3000). here is my view: class NextQuestion(APIView): permission_classes = [IsAuthenticated] lookup_url_kwarg = 'old_questions' def post(self, request, format=None): old_questions = request.data.get(self.lookup_url_kwarg) if len(old_questions): old_questions_q = [Q(id=x) for x in old_questions] questions_valides = Question.objects.exclude(reduce(operator.or_, old_questions_q)) if len(questions_valides) == 0 : return Response("Il n'y a plus de questions disponibles!") else: questions_valides = Question.objects.all() index = randint(0, len(questions_valides) -1) new_question = QuestionSerializer(questions_valides[index]).data return Response(new_question) My serializer: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' My urls: from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ###### path('quiz/', include('quiz.urls')), ] urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And in my settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' In my .js: <Fade in={!toggle} {...(!toggle ? { timeout: 2000 } : {})}> <Paper elevation={0} className={classes.paper}> <img className={classes.image} src={image} alt="La réponse." /> </Paper> </Fade > My variable image has this value: /media/images/quiz/animal-2029280_1280.png It should match the path corresponding to the image, yet it doesn't load. … -
How do i use placeholders along with % in the LIKE query django raw sql
I want to perform a query like this: select * from table where column like 'a%' I am doing this using django Raw SQL queries. I want to use a placeholder after the like operator in the query. how do I properly execute this using django raw SQL for example: if %s(the placeholder) is 'a' then this query should be executed: select * from table where column like 'a%' -
How can i pass model object to my form? Django
I have created an order form. I want save customer and order to model. I have 3 models Order, Customer and ShippingAddress Order model: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True) transaction_id = models.CharField(max_length=200, null=True) Customer model: class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=30, null=True) email = models.CharField(max_length=30, null=True) ShippingAddress model: class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=20, null=True) date_added = models.DateTimeField(auto_now_add=True) and i have form: class ShippingAddressForm(forms.ModelForm): class Meta: model = ShippingAddress fields = ['address', 'phone'] widgets = { 'address': forms.TextInput(attrs={'placeholder': 'Address...'}), 'phone': forms.TextInput(attrs={'placeholder': 'Phone...'}), } def __init__(self, *args, **kwargs): super(ShippingAddressForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' My views.py where i am processing form: def checkout(request): if request.user.is_authenticated: if request.method == 'POST': form = ShippingAddressForm(request.POST) if form.is_valid: form.save() else: form = ShippingAddressForm() context = { 'form': form } return render(request, 'store/checkout.html', context) Form has fields address and phone that the user must fill in. How can i pass fields customer and order when the user has filled form? -
Crispy Forms InlineRadios refuses to display correctly
I'm building a database front end and working on the search page. I'd like to show the radio buttons as horizontal, not vertical. I'm using Crispy Forms in Django and am aware of the simple InlineRadios function within the Formhelper Layout. For whatever reason, it refuses to display horizontally. Thinking it maybe related to css somewhere, I even removed all css and it STILL displayed horizontally. I have researched this problem with as many queries as I can imagine, but to no avail. forms.py from django import forms from crispy_forms.bootstrap import InlineRadios, Field, InlineCheckboxes from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Div, Row, Column length_overall_choices = [('Any', 'Any'), ('0-5', '0-5'), ('6-10', '6-10'), ('11-15', '11-15'), ('16-20', '16-20'), ('21-25', '21-25'), ('26-30', '26-30'), ('31-35', '31-35'), ('36-40', '36-40'), ('41-45', '41-45'), ('46-50', '46-50')] price_choices = [('Any', 'Any'), ('1', '$0-$1,000'), ('2', '$1,000 - $5,000'), ('3', '$5,001 - $10,000'), ('4', '$10,001 - $20,000'), ('5', '$20,001 - $30,000'), ('6', '$30,001 - $40,000'), ('7', 'More than $40,000')] condition_choices = [('Any', 'Any'), ('salvage', 'Salvage'), ('fair', 'Fair'), ('good', 'Good'), ('like new', 'Like New'), ('excellent', 'Excellent'), ('new', 'New')] manufacturer_choices = [('0', 'Any'), ('1', 'Jeanneau')] boat_year_choices = [('0', 'Any'), ('1', '1900-1920'), ('2', '1921-1940'), ('3', '1941-1960'), ('4', '1961-1980'), ('5', '1981-2000'), ('6', '2001-2020')] … -
Why can Django request.user.is_authenticated take 8 seconds to execute?
I am utterly confused. A few days ago my Django app started working significantly slower. It turned out that the following Django view takes 8 seconds to execute for an authorized viewer 0 seconds to execute for an anonymous user def speed_test(request): start = time.time() # measuring execution time b = request.user.is_authenticated # THIS somehow creates a problem response = {"test": "test"} # constructing a dummy response end = time.time() logger.warning("speed test: " + str(end - start) + " auth = " + str(b)) # logging return HttpResponse(json.dumps(response)) 17/Apr/2021 17:18:18 WARNING speed test: 8.06065821647644 auth = True 17/Apr/2021 17:23:04 WARNING speed test: 6.508827209472656e-05 auth = False is_authenticated can be replaced by any function from AbstractBaseUser with the same results. If I remove a call to is_authenticated, everything works fast for every user. It is reproduced both withrunserver and gunicorn/uwsgi. But I can't reproduce it on my dev laptop, even connecting with the same remote database. So it doesn't look like a database issue, and it's definitely not a networking issue. Django 3.08, python 3.8, ubuntu. Tried making a brand new venv - to no avail. I would appreciate any hints on how to troubleshoot this. -
Upload image via AJAX not working in Django
I'm making a library application, the books have an image field, and when I try to upload that image via AJAX, it doesn't work. If I upload it from the admin panel, it does work, so the fault I imagine will be in the AJAX function ... Everything works fine except the image. That is, if I change the authors, the title, etc, everything works, except the image, which does not upload ... The form in the template: <form id="form_edicion" action="{% url 'libro:editar_libro' object.id %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-body"> <div id="erroresEdicion"> </div> {{ form.as_p }} </div> <div class="modal-footer"> <button class="btn btn-danger" type="button" onclick="cerrar_modal_edicion();">Cancelar</button> <button id="boton_creacion" class="btn btn-primary" type="button" onclick="editar();">Confirmar</button> </div> </form> The AJAX function: function editar() { activarBoton(); var data = new FormData($('#form_edicion').get(0)); $.ajax({ url: $('#form_edicion').attr('action'), type: $('#form_edicion').attr('method'), data: data, cache: false, processData: false, contentType: false, success: function (response) { notificacionSuccess(response.mensaje); listadoLibros(); cerrar_modal_edicion(); }, error: function (error) { notificacionError(error.responseJSON.mensaje); mostrarErroresEdicion(error); activarBoton(); }, }); } The function in views.py: class ActualizarLibro(LoginYSuperStaffMixin, ValidarPermisosMixin, UpdateView): model = Libro form_class = LibroForm template_name = 'libro/libro/libro.html' permission_required = ('libro.view_libro', 'libro.add_libro', 'libro.delete_libro', 'libro.change_libro') def post(self, request, *args, **kwargs): if request.is_ajax(): form = self.form_class( data=request.POST, files=request.FILES, instance=self.get_object()) if form.is_valid(): form.save() mensaje = f'{self.model.__name__} actualizado … -
Django ORM annotate + data set fields
I can't get additional fields from the data set introduced after using annotate and order by. If I add values this changes the "group by" statement. Details: Connection.objects.filter(Q(task__taskcontexts__key="project_id") & Q(task__taskcontexts__value__in=Subquery(Project.objects.filter(is_active=True).values('pk')))) \ .values('task__taskcontexts__value') \ .annotate(start_date=Max('start_at')) \ .order_by() The SQL select shows the correct "group by" I want to have and the related data returned. SELECT ..... GROUP BY `Core_taskcontext`.`value But I am still missing fields like "pk", "state" etc. When I add them after the "order by" (last code line ).... Connection.objects.filter(Q(task__taskcontexts__key="project_id") & Q(task__taskcontexts__value__in=Subquery(Project.objects.filter(is_active=True).values('pk')))) \ .values('task__taskcontexts__value') \ .annotate(start_date=Max('start_at')) \ .order_by() \ .values('pk', 'state', 'end_at') The SQL statement changes the group by part and returns more lines. :-( SELECT ..... GROUP BY `Core_Connection`.`task_id`, `Core_taskcontext`.`value` How can I add those fields to the results without changing the group by ? Thank you. -
Lock Next course until Previous Course watch Complete
I want to lock a course Section in My website.If user watch complete lectures of Previous course then Unlock next course otherwise lock next course.I am developing this site in django..How can I do this and achieve this functionality any code example plzzz help -
How to display last 25 messages in a chat application in Django
I am building a chat application in Django. But I have a problem with displaying the last 25 messages of my chat. Here is my code.... This is my model for saving the messages: from django.contrib.auth import get_user_model from django.db import models class Message(models.Model): username = models.CharField(max_length = 255) room = models.CharField(max_length = 255) content = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: ordering = ('date_added', ) Here is the function that should filter the messages and render the template in views : @login_required(login_url = 'index') def room(request, room_name): messages = Message.objects.filter(room = room_name)[:25:] return render(request, 'chatroom.html', { 'room_name': room_name, 'messages': messages }) Here is the part that should display the messages in chatroom.html template: <div class="container_chat"> <form> <div class="textarea" id="chat-text" rows="10" readonly> {% for m in messages %} <b> {{ m.username }} </b>: {{ m.content }} <br> {% endfor %} </div> <div class=container_chat_inputs> <input id="input" placeholder="Enter a message" type="text"></br> <input class="chat_message_submit" id="submit" type="button" value="Send"> </div> </form> </div> And here is my function for saving the messages in the model in consumers : @sync_to_async def save_message(self, username, room, message): Message.objects.create(username = username, room = room, content = message) So far I believe that the main problem is in the … -
Email is not sending in digital ocean only working in localhost
When i try to run project in local server it's works smoothly. But when i deploy my project in digital-ocean mail is not sending can anyone please suggest a solution for this problem. is it because of smtp blocking? i go though somany sites but none of them showing a proper solutionthis is my settings -
submit Django froms.py form without refreshing with qty buttons
i am trying to post this form without refreshing and i want to post it using the quantity buttons from bootstrap touchspin i want to remove the apply button is there a way i can do it? if u want just tell me how to post it without refreshing with the apply button html: <form action="{% url "cart:cart_add" product.id %}" method="post" id="form"> {% csrf_token %} {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <input type="submit" value="Apply" class="btn btn-info"> </form> <script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js'></script> <script src='script.js' type="text/javascript"></script> <script async src="//jsfiddle.net/bizamajig/rcbqjLyt/embed/"></script> <script> $(document).ready(function() { $("input[name='quantity']").TouchSpin({ min: 1, max: 10, step: 1, maxboostedstep: 10000000, prefix: '', buttondown_class: "btn btn-primary", buttonup_class: "btn btn-primary", initval: 200, }); }); $('#form').submit(function (e) { e.preventDefault(); $.ajax({ type: 'post', url: 'home.html', data: $('#form').serialize(), success: function () { alert('form was submitted'); } }); return false; }); </script> -
Template tags to work with time in Django
Please tell me how can I use Django to output the time in this format, such as "Last Monday" or "Last Friday" if the difference between the dates is not more than a week. -
Django and mongodb error: E11000 duplicate key error { id: null }
I have a backend in djang rest framework, with mongodb as a database, I use djongo as an orm. to fill the db, I upload a json file to an endpoint which calls mongoimport on the file, the problem is that I get the duplicate key error. The weird thing is that I have the same code on another machine and it works perfectly fine there, I checked the packages versions but they are identical in both so i don't know what's causing this exactly. Model: class Topic(models.Model): main_topic = models.CharField(max_length=120) sub_topics = models.JSONField() score = models.IntegerField() date = models.DateField() def __str__(self): return f""" Main Topic: {self.main_topic} sub_topics: {self.sub_topics} score: {self.score} date: {self.date}. View: class UploadView(APIView): serializer_class = UploadSerializer def post(self,request): """Endpoint for inserting new topics into the database.""" uploaded_file = request.FILES.get('file_uploader') helper.handle_upload(uploaded_file) return Response("ok") The upload handler: def handle_upload(uploaded_file): """ Imports data from a json file to the db""" with open(f"media/{uploaded_file.name}","wb") as destination: for chunk in uploaded_file.chunks(): destination.write(chunk) subprocess.run(['mongoimport','--db','mlops','--collection','topics_topic','--file',f'media/{uploaded_file.name}','--jsonArray']) Any help is appreciated. -
Python throwing variable scope error in Django app
I am currently working on a small Library management Django app, the following is one the view function def issue_book(request): now = datetime.now() if now.month < 10: month = "0" + str(now.month) if now.day < 10: day = "0" + str(now.day) today = str(now.year) + "-" + month + "-" + day context = { 'today': today } return render(request, 'admin_area/issue_book.html', context) But this gives me an error as shown: UnboundLocalError at /admin_area/issue_book local variable 'day' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/admin_area/issue_book Django Version: 3.2 Exception Type: UnboundLocalError Exception Value: local variable 'day' referenced before assignment Can anyone explain the cause of the error! -
Django - How to access the first featured post of my blog?
In my blog's model, I have a boolean flag to determine if a post is "featured" or not. Featured posts will be displayed in a different way. To retrieve the posts I have defined two model managers as below: class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class FeaturedManager(models.Manager): def get_queryset(self): return super(FeaturedManager, self).get_queryset().filter(feature=True).order_by('-publish')[:3] and in the views.py this is how I pass them to the template: class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 10 def get_context_data(self, *args, **kwargs): context = super(PostListView, self).get_context_data(*args, **kwargs) context['featured'] = Post.featured.all() return context Now in my template I have a section for featured posts and another section for normal posts. Normal posts are easy, but I want to display the first featured post — which is going to be the most recent one — in a separate container, and the last two in another one. There always will be the last 3 featured posts displayed. Here's the code for template to display the first featured post: <div class="jumbotron p-4 p-md-5 text-white rounded bg-dark"> <div class="col-md-10 px-0"> <h1 class="display-4 font-italic">The Title of Newest Featured Post</h1> <p class="lead my-3">The Body of the Newest Featured Post</p> </div> </div> My question is, how to access the … -
bind(): Permission denied [core/socket.c line 230]
good day, i am currently trying to deploy my webiste using django, nginx and uwsgi, how do i remove or fix the error " bind(): Permission denied [core/socket.c line 230] " !!! no internal routing support, rebuild with pcre support !!! chdir() to /opt/Spa/beautyparlor your processes number limit is 7029 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with -- thunder-lock) uWSGI http bound on :8000 fd 5 bind(): Permission denied [core/socket.c line 230] -
How to download image from Object Storage (Digital Ocean Spaces) In Django?
I have created an image sharing wesbite in Django where I save my thumbnail files on server and original files on object storage. I was able to upload images(original images on object storage and thumbnail on server). But, The problem is that I cannot download images from object storage. Is there any possible way that you can download images from object storage. Here is my code. My settings.py : # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ AWS_ACCESS_KEY_ID = 'xxx' AWS_SECRET_ACCESS_KEY = 'xxx' AWS_STORAGE_BUCKET_NAME = 'my-bucket-name' AWS_S3_ENDPOINT_URL = 'endpoint-url' AWS_S3_CUSTOM_DOMAIN = 'my-custom-domain-name' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=31536000', } AWS_DEFAULT_ACL = 'public-read' #DEFAULT_FILE_STORAGE = "custom_storages.MediaStorage" (Commented Code) MEDIA_URL = BASE_DIR / 'media' MEDIA_ROOT = 'media/' models.py from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFit from django.urls import reverse import os from django.conf import settings from custom_storages import MediaStorage class Image(models.Model): def get_image_path(instance, filename): return os.path.join('images', str(instance.subcategory.category.category_name), str(instance.subcategory.sub_name), filename) image = models.ImageField(upload_to=get_image_path, storage=MediaStorage(), null=True) #Here I'm saving my image to object storage using custom storage class image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(480,480)], format='JPEG', options={'quality':60}) #generating thumbnail using django-imagekit custom_storages.py - Using this to store my files on object storage import os from storages.backends.s3boto3 import S3Boto3Storage from tempfile import SpooledTemporaryFile class MediaStorage(S3Boto3Storage): bucket_name = 'my-bucket-name' … -
how to automatically oneToOne realation table in django
i created a model in django with one to one relationship with default User model of django i want to automatically create the table for the user when user hit signup and create a new account. i not found any answers in django documentation.kindly help me my model is as follow: class totalleave(models.Model): data = models.OneToOneField(User,on_delete=models.CASCADE) LeaveAvailable = models.IntegerField(default=15) def __str__(self): return self.data.username -
How do I work with nested serializers if I need an html form?
I want the user to be able to select (post so they can make an order) the type of food and the quantity of it so I made a nested serializer. The thing is, when I go to the url I get this error: Lists are not currently supported in HTML input. I read there's no way around it so what can I do? Is there a better way to manage this without a nested serializer? This is the serializer: class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = ('name', 'quantity') name = serializers.CharField(validators=[ UniqueValidator( queryset=models.Food.objects.all(),lookup='iexact' )]) class OrderSerializer(serializers.ModelSerializer): food= FoodSerializer(many=True) class Meta: model = Order fields = ('date','food','phone','email') def validate(self, data): email = data.get('email') phone= data.get('phone') if not email and not phone: raise serializers.ValidationError("Email or phone are required") return data def create(self, validated_data): order= Order.objects.create( email=validated_data['email'], phone=validated_data['number'], date= validated_data['date'], food= validated_data['food'], quantity= validated_data['quantity'], ) order.save() return order -
Handling errors with Vue and Django
I'm performin a call to a Django endpoint from Vuex store with axios.post and it is intended to return a Error: Request failed with status code 500, the thing is how to handle that response from the server in order to display instructions on why is that action being rejected. I've tried a lot of ways to perform an action once the status=500 is resolved, but it seems like once this error is returned from the server, everything breaks before letting any catch block of code gets done. Tried with Promise: return new Promise(async (resolve, reject) => { const response = await axios.post(url, payload) if (response.status == 200) { //commit actions resolve(response); } else if (response.status == 500) { resolve(response); } }); inside a trycatch: return new Promise(async (resolve, reject) => { try { const response = await axios.post(url, payload) if (response.status == 200) { //commit actions } } catch (error) { console.log("error ", error); } }); using catch directly in axios promise: return axios.post(url, payload) .then(response => { if (response.status == 200) { } else { throw response.statusText; } }) .catch(error => { throw 'error' }) However, none of the above performs the catch block of code. I need … -
Import error while customizing django-comments-xtd
acordign to the documentation for django-XtdComments in order to have my custom comment model instead of XtdComment the setting file should be like this: COMMENTS_APP = "django_comments_xtd" COMMENTS_XTD_MODEL = 'commenting.models.BookComment' at this poin I have a commenting app and a BookComment model to use for Comment model but setting file gives me Import Error that Module "commenting.models" does not define a "BookComment" attribute/class can anyone help me what's wrong with this code? -
Deploy a Django project to an AWS EC2 instance through GitHub Actions
In my workflows folder I have a django.yml file that does CI. it currently has 1 job i.e. build that tests the code. I want another deploy job that deploys my django project to an AWS EC2 instance. I am new to AWS and CI/CD any help would be appreciated. -
My Django web page is not showing CSS styling
I have a base template with a CSS file linked within. The web page itself extends the base but is not showing the CSS styling, only the html. In-line styling does work though. This is what is in my settings.py file STATIC_URL = '/static/' this is the base for my web page {% load static %} <!DOCTYPE html> <html lang = "en"> <head> <title>myapp</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static 'myapp/styles.css' %}"> </head> <body> {% block body %} {% endblock %} </body> </html> This is the web page itself {% extends "myapp/layout.html" %} {% block body %} <div class="topnav"> <a class="active" href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> </div> {% endblock %} This is the style sheet linked in the base body { margin: 0; font-family: Arial, Helvetica, sans-serif; } .topnav { overflow: hidden; background-color: #333; } .topnav a { float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .topnav a.active { background-color: #4CAF50; color: white; } This is the web page that I'm seeing This is my file layout And this is the message I'm receiving from Django after the get request [17/Apr/2021 11:06:04] … -
I am getting this error after running "Django manage.py migrate" command
This is all error I am getting: PS E:\funds\Restaurant\restaurant> python manage.py makemigrations Did you rename the menu.Order model to Orders? [y/N] n Migrations for 'menu': menu\migrations\0003_auto_20210417_2034.py - Create model Orders - Delete model Order PS E:\funds\Restaurant\restaurant> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, menu, sessions Running migrations: Applying menu.0003_auto_20210417_2034...Traceback (most recent call last): File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 394, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: table "menu_orders" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\funds\Restaurant\restaurant\manage.py", line 21, in <module> main() File "E:\funds\Restaurant\restaurant\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\tejas\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 124, … -
Django: Where to write querysets in Django Application?
I know this is a type of theoretical question, but I am new to Django and I have been struggling for last 2 weeks, and it would be helpful for beginners of Django. In the django documentation, there is a lot of information about queryset, filters, annotate, aggregate and so on. Everything mentioned there is just in command line. But I am not able to find where do we write these queries? either in views.py, models.py or somewhere else. For example, I am making a django application, where I have two models Client and Installment, and each client can have multiple installments, so they are connected with foreign key. Now, I am able to do most of the tasks like, adding new client, displaying list of clients, adding new installment for each client, displaying the list of installments of each particular client. I am using 'Class based Views' in my views.py, and I have one view called InstallmentListView views.py class InstallmentListView(ListView): model = Installment template_name = 'client_management_system/installment_detail.html' context_object_name = 'installments' # This function is to show the installments of the client, the details of which we are seeing currently, and # pk=self.kwargs['pk'] is to get the client id/pk from URL …