Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrate error for Oracle database table
I have created django project where following versions I have used. Python version 3.8.6 Django version 3.1.2 Oracle 11g I have run makemigrations which works all correct but mugrate commands give me error i.e django.db.migrations.exceptions.MigrationSchenaMissing: Unable to create the django_migrations tabel (ORA-02000: missing ALWAYS keyword) Database setting is following: > DATABASE = { 'default':{ 'ENGINE': 'django.db.backebds.oracle', > 'NAME': '10.1.5.87:1529/cdxlive', 'user': 'cisadm', 'PASSWORD': > 'cistechnology' } } Table I am creating is class Test(models.Model): name = models.CharField() score = models.CharField() -
Call different view function with empty url path , on same app (multiple empty url mapping to different view function)
This is my project urls.py urlpatterns = [ path('', include('index.urls'), name='index'), path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('terms-and-conditions/', include('index.urls', namespace='index'), name='terms'), ) this is my app's urls.py: urlpatterns = [ path('', views.index, name='index'), path('', views.terms, name='terms'), ] my goal is to have the main urls.py generate paths, without having to change the path inside my app's urls.py Example (desired behaviour): website.com/en/terms-and-conditions -> views.terms gets called website.com/ -> views.index gets called The following app's urls.py works: urlpatterns = [ path('', views.index, name='index'), path('terms/', views.terms, name='terms'), ] But now i get www.website.com -> maps to views.index (This is correct) www.website.com/en/terms-and-conditions/ -> maps to index as well. (not correct) and www.website.com/en/terms-and-conditions/terms -> maps to views.terms (NOT THE DESIRED URL) www.website.com/terms -> maps to views.terms (not desired, its redundant and maps to the same page as above) I could solve this by using an app for each page, but this seems very unnecessary as this is a simple website where i'd like to keep everything contained in one app. I started using django 3 or 4 days ago, so i am really at a loss on how to solve problems like these. Any help is very welcome . And i thank you … -
Django - best way to associate user data after log-in
When my users answer a challenge, I want it to be stored against their profile. When they log in, they will see an index of challenges and it will show which ones have been answered. I thought I could solve this problem by having a User_Challenge model in models.py: class User_Challenge(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE, null=True) answered = models.BooleanField(default=False) But because you can't do filtering in a template, I am finding this really cumbersome. Is there a simpler way to associate challenge status against a user profile without introducing another table? -
Django Rest Framework nested serializer creation
I have troubles saving object with foreign key. I have two Django model like (going to simplfy them, for this purpose, but the point remains): class Model1(models.Model): name = models.CharField() class Model2(models.Model): label = models.CharField() rel = models.ForeignKey("Model1", related_name="model2s") and two Serializers like: class model1SER(serializers.ModelSerializer): class Meta: model = Model1 fields = ['pk', 'name'] class model2SER(serializers.ModelSerializer): rel = model1SER() class Meta: model = Model2 fields = "all" def create(self, validated_data): model2 = Model2.objects.create(**validated_data) return model2 I post using axios POST to a modelViewSet, and the POST JSON body looks like: {'label': "xxxx", 'rel': {'pk': 1, 'name': "foo"}} Trying to create an object, returns "rel_id violates not null..." and after inspecting, the validated data only contains: ('rel', OrderedDict([('name', 'foo')])) without pk. I have also tried replacing pk with id, adding id and many more, but can not get to save a object using nested serializer. The Model1 Serializer is used to get the data for all Model1 objects. After selecting a single one, it is appended to a post data for a Model2 Serializer, so the structure of serialized data remains the same. Can I change the create method to somehow get the validated_data['rel']['pk'] ? Thank you -
Django queryset verify if fields exists
I want to implement a custom ordering backend (using rest_framework.filters.OrderingFilter) and I basically want to check if the field exists for my queryset first before filtering it without evaluating the queryset. something like if queryset.is_available_field(my_field): queryset = queryset.order_by(my_field) I cannot try / except because I don't know exactly when my queryset will be evaluated. -
Looping Multi-Dimensional Array in Django HTML Template
My Dictionary looks like below Table: 0: Name1 : ABC Name2 : IJK 1: Name1 : QQQ Name2 : FFF 2: Name1 : WWW Name2 : RRR Currently the below HTML code working with hard coded '0', but nor working with 'row' Here key = 'Table', as mentioned above. {% for key, value in data.items %} {% for row in value %} <br> {{value.0.Name1}} {% endfor %} {% endfor %} for : {{value.0.Name1}} --> Gives output as ABC In the above code, if i replace '0' with 'row' then i get error. Please help. Best Regards, Namratha Patil -
Generic detail view BookDetailView must be called with either an object pk or a slug in the URLconf
i am new in django. i work on a project . it is my bookdetailview:: class BookDetailView(generic.DetailView): model = models.Book template_name = 'catalog/book_detail.html' and this is my renewbooklibririan that define in views:: def renew_book_librarian(request, pk): """ View function for renewing a specific BookInstance by librarian """ book_inst=get_object_or_404(models.BookInstance, pk = pk) # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = RenewBookForm(request.POST) # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required (here we just write it to the model due_back field) book_inst.due_back = form.cleaned_data['renewal_date'] book_inst.save() # redirect to a new URL: return HttpResponseRedirect(reverse('catalog:my-borrowed') ) # If this is a GET (or any other method) create the default form. else: proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,}) return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) and this is my url pattern: urlpatterns = [ path('', views.Index.as_view(), name = "index"), path('books/', views.BookListView.as_view(), name = "books"), path('authors/', views.AuthorListView.as_view(), name = 'authors'), path('book/<int:book_id>/', views.BookDetailView.as_view(), name = "book-detail"), path('mybooks/', views.LoanedBooksByUserListView.as_view(), name = 'my-borrowed'), path('book/<int:book_id>/renew/', views.renew_book_librarian, name='renew-book-librarian' ) ] my code is working until add the renew-book-libririan … -
Django: for loop through parallel process and store values and return after it finishes
I have a for loop in django. It will loop through a list and get the corresponding data from database and then do some calculation based on the database value and then append it another list def getArrayList(request): list_loop = [...set of values to loop through] store_array = [...store values here from for loop] for a in list_loop: val_db = SomeModel.objects.filter(somefield=a).first() result = perform calculation on val_db store_array.append(result) The list if 10,000 entries. If the user want this request he is ready to wait and will be informed that it will take time I have tried joblib with backed=threading its not saving much time than normal loop But when i try with backend=multiprocessing. it says "Apps aren't loaded yet" I read multiprocessing is not possible in module based files. So i am looking at celery now. I am not sure how can this be done in celery. Can any one guide how can we faster the for loop calculation using mutliprocessing techniques available. -
[tag:celery [Connection reset Error either due to "connection to broker" lost or Could not receive ack
I have a back ground task named task_conclude_key_issues_through_selenium, which will perform some click operations on a web page which takes about 3 to 5 mins. I am getting any one of below error once celery back ground task execution is completed. 1.[2020-10-26 16:14:45,233: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... Traceback (most recent call last) 2.Couldn't ack 2, reason:ConnectionResetError(10054, "An existing connection was forcibly closed by the remote host', None, 10054, None) After 2 to 3 minutes,its getting connected to broker with following log message ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host [2020-10-26 16:23:07,677: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// views.py: -------- board_details_task_info = task_conclude_key_issues_through_selenium.apply_async(args=[created_pk]) tasks.py: -------- @shared_task(bind=True) def task_conclude_key_issues_through_selenium(self, created_pk): settings.py: ----------- CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TRACK_STARTED=True My Application uses below Packages: 1.celery - 5.0.1 2.celery_progress 3.Python - 3.6.2 Please let us know how to resolve these errors and proceed further. Regards, N.Dilip kumar. -
CSRF cookie not set in Postman by Django
I am having strange behaviour: Situation 1: I set 'django.middleware.csrf.CsrfViewMiddleware' in my MIDDLEWARE settings. MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I do a POST call with Postman to a REST endpoint: class BlogCreateView(APIView): http_method_names = ['post'] def get_context_data(self, **kwargs): return { 'request': self.request, 'kwargs': kwargs, } def post(self, request, **kwargs): """ POST a new object """ context = self.get_context_data(**kwargs) serializer = self.serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) new_instance = serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) The CSRF cookie is not set. I don't set a csrf value in the header of the request either. But the server accepts it. This should not happen right? -
How to Convert JSON Data Flask Into Djano Object
Flask project Convert flask application to django from flask import Flask, jsonify, request app = Flask(__name__) incomes = [ { 'cpu': "5.2 %" } ] @app.route('/cpu') def get_incomes(): return jsonify(incomes) @app.route('/cpu', methods=['POST']) def add_income(): incomes.append(request.get_json()) return '', 204 I want to convert the above piece of code into corresponding Django. Inside Django project in views.py file def cpu(request) is defined. -
heroku django deployment error when i deploy my project on heroku
[enter image description here][1] this is image when deploy my project [1]: https://i.stack.imgur.com/7Dzkh.png 2020-10-26T10:37:34.171420+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=artz-artz.herokuapp.com request_id=60e18810-1663-4340-bb29-b483ac8c533a fwd="49.205.85.27" dyno= connect= service= status=503 bytes= protocol=https 2020-10-26T10:37:34.672584+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=artz-artz.herokuapp.com request_id=4008c275-487b-4985-8271-609f695f3cef fwd="49.205.85.27" dyno= connect= service= status=503 bytes= protocol=https 2020-10-26T10:39:52.603447+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=artz-artz.herokuapp.com request_id=a80684db-d362-46b3-a077-9bfa241f125f fwd="49.205.85.27" dyno= connect= service= status=503 bytes= protocol=https 2020-10-26T10:39:53.229699+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=artz-artz.herokuapp.com request_id=7c698567-216c-447f-8082-fd79140fa7a7 fwd="49.205.85.27" dyno= connect= service= status=503 bytes= protocol=https 2020-10-26T10:45:13.675510+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=artz-artz.herokuapp.com request_id=e7c3d041-78f3-4526-a642-446fed802fa2 fwd="49.205.85.27" dyno= connect= service= status=503 bytes= protocol=https 2020-10-26T10:45:14.390601+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=artz-artz.herokuapp.com request_id=ea9c96c2-f736-44c6-8ccf-2427fe8151ae fwd="49.205.85.27" dyno= connect= service= status=503 bytes= protocol=https -
Wrong status code when User validation fails - Django One-to-one relationships
I am writing a dajngo user registration REST API and I have extended the Django User model using a one-to-one field in a Profile model. The problem is - when the username validation fails, I get 200 HTTP status code. How can I raise an error code if the Validation of nested User obejct fails? Output : Status Code : 200 { "user": { "username": [ "A user with that username already exists." ] } } The following are the serializers : from rest_framework import serializers from .models import Profile,User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' #fields = ('username', 'first_name', 'last_name', 'email') class registration_serializer(serializers.ModelSerializer): user = UserSerializer(required=True) password_confirm = serializers.CharField(style = {'input_type' : 'password'}, write_only=True) class Meta: model = Profile fields = ['date_of_birth','city','gender','display_picture','password_confirm','user'] extra_kwargs = { 'password' : {'write_only' : True} } def create(self, validated_data): user_data_valid = validated_data.pop('user') password_confirm = validated_data.pop('password_confirm') if user_data_valid['password'] != password_confirm: raise serializers.ValidationError({'password' : 'Passwords do not match'}) else: user = UserSerializer.create(UserSerializer(), validated_data=user_data_valid) profile, created = Profile.objects.create(user=user, date_of_birth=validated_data.pop('date_of_birth'), city=validated_data.pop('city'), gender=validated_data.pop('gender'), display_picture=validated_data.pop('display_picture') ) return profile And this is the Model that I have created : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_of_birth = models.DateField(null=True) city = models.CharField(max_length=40,null=True) gender = models.CharField(max_length=1, choices=(('M','Male'),('F','Female'),('O','Other')), null =True) … -
Field 'id' expected a number but got 'create'
I've been trying to create this model object but i keep getting this error: Field 'id' expected a number but got 'create'. I am using djangi 3.0.3 view.py file:- from django.shortcuts import render from . import models from django.views.generic import (View,TemplateView,ListView,DetailView, CreateView,UpdateView,DetailView) # Create your views here. class IndexView(TemplateView): template_name = 'index.html' class SchoolListView(ListView): context_object_name = 'schools' model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_detail' model = models.School template_name = 'basic_app/school_detail.html' class SchoolCreateView(CreateView): fields = ('name','principal','location') model = models.School model.py from django.db import models from django.urls import reverse # Create your models here. class School(models.Model): name = models.CharField(max_length=265) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse("basic_app:detail", kwargs={'pk':self.pk}) class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School, related_name='student', on_delete=models.CASCADE) def __str__(self): return self.name Any help will be appreciable Thank & Regards Viplav Dube -
Connect different model and form into each post
Please help. Im a newbie in programming. Im currently working on project, simple scientific calculator, but I dont know what path should I take. I want to map MyCalculator Model and Form into each post from 'Post' model. Let say I create model 'Post', and then I create post 'Post1', 'Post2', 'Post3'. I access them through PostListView and PostDetailView and then I create 'Post1Calc', 'Post2Calc', 'Post3Calc' Model and Form. What should I do to do this? How to connect the calculator to each post The goal is, everytime I click the post, I can see the calculator for related post and do some input and result display. What need to be taken as note is I might have many post in the future and so I will keep making new models for calculator. Please give me some direction and explanation. I dont mind some references as well if it is easier. Here is my mind map for. Thank you -
Creating Models To Store Static Webpage Content
I have a webpage which loads the following container: <div class="container"> <div class="row"> <!-- this code is repeated many times --> <div class="example_outer col-md-4 col-xl"> <div class="example_container"> <img class="example" src="{% static 'example/example.png' %}" alt="example"> <div class="inner_container"> <p class="example_text">Example</p> </div> </div> </div> <!-- // --> </div> </div> Only it prints out the middle section many times. As I had a lot of repeated code I decided to remove the repeated code, create a model, create an instance for each object in the repeated code, and iterate through the instances printing them out. Something like: <div class="container"> <div class="row"> {% for example in examples %} <div class="example_outer col-md-4 col-xl"> <div class="example_container"> <img class="example" src={{example.image}} alt={{example.alt}}> <div class="inner_container"> <p class="example_text">{{example.text}}</p> </div> </div> </div> {% endfor %} </div> </div> This data is unlikely to change often, and if so, will only be changed by me (users cannot create these models). I am also thinking in terms of the production server. If I create models and iterate through them to reduce my repeated code then the images in those models will exist in my media folder. I thought the media folder was only for user uploads. Am I missing something? Thank you. -
How do i pass vuejs frontend Vuetify Date picker output to a django DateTime field
My project uses vuejs on the front end and django as backend, django rest framework to serve the api's. i have been stucked on this for hours, without a clue as to why i keep having this error. I have also checked here on stackoverflow, similar questions were not helpful. I have a Project model with a DateTime field for expiry date like so; class Project(models.Model): author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=255, unique=True) details = models.TextField() expiry = models.DateTimeField() ---------------- and a serializer class; class ProjectSerializer(serializers.ModelSerializer): author = UserSerializer(read_only=True) ------- expiry = serializers.DateTimeField(read_only=False) class Meta: model = Project fields = ['id', 'author', 'title', 'details', 'expiry', ...] def create(self, validated_data): title = validated_data.get('title') details = validated_data.get('details') exp = validated_data.get('expiry') expiry = datetime.strptime(str(exp), '%Y-%m-%d') project = Project.objects.create(title=title, details=details, expiry=expiry, author=self.context['request'].user) return project and then my views.py; class CreateProjectViewSet(CreateAPIView): serializer_class = ProjectSerializer queryset = Project.objects.all() permission_classes = [IsAuthenticated,] authentication_classes = [TokenAuthentication,] def create(self, request, *args, **kwargs): context = { 'request': request } serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) response = {'message': 'Project created!', 'result': serializer.data} return Response(response, status=status.HTTP_201_CREATED) def perform_create(self, serializer): serializer.save(created=timezone.now()) In my vuejs frontend, i have a vuetify DatePicker component to input the expiry date field. The method to post the … -
Django not showing a model in admin page
I have created a new model for my app "Consumptions" but it doesn't show up. I know that I have to put it in the admin.py page but still not working. I don't know what could be happening This is my models.py page: from logs.mixins import LogsMixin # Other models class MF(LogsMixin, models.Model): """Definición del modelo de Proveedor.""" name = models.CharField("Nombre", null=False, default="MF", max_length=50) class Meta: verbose_name = 'Módulo formativo' verbose_name_plural = 'Módulos formativos' def __str__(self): return self.name # Other models And this is my admin.py page: from django.contrib import admin from .models import Provider, Consumption, Message, Course, Call, Platform, MF admin.site.register(Provider) admin.site.register(Consumption) admin.site.register(Message) admin.site.register(Course) admin.site.register(Call) admin.site.register(Platform) admin.site.register(MF) as you can see is not my only model, I do the same with all of them but that one is not showing up in the admin page. What am I doing wrong? -
how to access form.cleaned_data values in another view?
urls.py app_name = "spotify" urlpatterns = [ path("home/" , Search.as_view() , name= "home"), path("data/" , View.as_view(), name= "view") ] views.py class Search(View): form = SpotifyForm template_name = "spotify_calls/homepage.html" context = {"form": form} def get(self, request): return render(request , self.template_name, self.context) def post(self, request, *args , **kwargs): form = self.form(request.POST) template_name= "spotify_calls/display.html" if form.is_valid(): cleaned = form.cleaned_data["form"] context = {"data":cleaned} return redirect('spotify:view') else: form() class display(View): template_name = "spotify_calls/display.html" def get(self,request): render(request, self.template_name) I wish to pass context = {"data":cleaned} into my class display(View) so I can use the form data as input to other methods I will define in class display(View) but I do not know how to. -
The view admin panel.views.create category didn't return an HttpResponse object. It returned None instead
I dont know why i am getting this error I am trying build an admin panel.So I am trying to make create category functionality after coding all the functionalities i got stuck in this error Here is my view.py def createcategory(request): if request.method == 'POST': createcat = CategoryForm(request.POST, request.FILES) if createcat.is_valid(): cat_name = createcat.cleaned_data['category_name'] cat_image = createcat.cleaned_data['category_image'] insert_cat = CategoryModel( category_name=cat_name, category_image=cat_image) insert_cat.save() create2 = CategoryForm() else: createcat = CategoryForm() all_categories = CategoryModel.object.all() return render(request, 'createcat.html', {'create2': createcat}) Here is my models.py class CategoryModel(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=100) category_image = models.ImageField(upload_to='images/') -
Django Elasticsearch dsl drf OR query
How to make OR query (using django-elasticsearch-dsl-drf) with multiple contains statements? Query in words: Search for objects where title contains "hello" OR description contains "world" I can't find about it in documentation: https://django-elasticsearch-dsl-drf.readthedocs.io/en/0.3.12/advanced_usage_examples.html#usage-example -
Django 3.1.2 block Content Not Showing
Django block content not working while extends -
Reverse for 'post_detail' with keyword arguments '{'pk': '', 'article_id': ''}' not found
I'm a beginner in developer of django. I want to create a template tag on homepage of my blog and link to article page of my blog. Here is my template tag : {% url 'post_detail' pk=post.pk article_id=photo.article_id %} but cause the error : NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{'pk': '', 'article_id': ''}' not found. 2 pattern(s) tried: ['post/(?P<pk>[^/]+)/$', 'post/(?P<pk>[^/]+)/(?P<article_id>[^/]+)/$'] I try (pk and article_id) = 1,2,3 ... and so on.It can function. Here is my code: home page html: <div class="story"> {% for article in article %} <div> <div> <h3><b>{{ article.title }}</b></h3> <h5>{{ article.created_at }}</h5> </div> <div> <p>{{ article.content }}</p> <div> <div> <p><button type="button" onclick="location.href='{% url 'post_detail' pk=post.pk article_id=photo.article_id %}'"><b>READ MORE »</b></button></p> </div> </div> </div> </div> {% endfor %} </div> view.py: def home(request): article = Article.objects.all() photo = Picture.objects.all() return render(request, 'home.html', {'article':article,'photo':photo} ) def post_detail(request,pk,article_id): post = Article.objects.get(pk=pk) photo = Picture.objects.get(article_id=article_id) return render(request,"post.html",{"post":post , "photo":photo}) url.py: from blog.views import home,post_detail path('', home) path('post/<pk>/<article_id>/', post_detail, name='post_detail') -
How to filter date in diagram (Chart.js) in Python/Django?
I need your help, It's my first project with Python, Django and Chart.js. I have to create monthly Report for Automated tests. What is done: urls.py path('launch/<str:pk>', views.launch_details, name='launch-detail'), path('launch/<str:pk>/<str:feature_id>', views.launch_details, name='launch-detail'), path('launch/<str:pk>/<str:launch_id>', views.launch_details, name='launch-detail'), path('launch/<str:pk>/<str:feature_id>/<int:scenario_id>', views.launch_details, name='launch-detail'), path('monthly_report/', views.monthly_report, name='monthly_report'), path('last_monthly_report/', views.last_monthly_report, name='last_monthly_report') models.py class MonthlyReport(models.Model): start_date = models.CharField(max_length=255, primary_key=True) launch_id = models.IntegerField() status = models.CharField(max_length=255) p1_passed = models.IntegerField() p1_total = models.IntegerField() p2_passed = models.IntegerField() p2_total = models.IntegerField() p3_passed = models.IntegerField() p3_total = models.IntegerField() class Meta: managed = False db_table = 'V_AT_MONTHLY_REPORT' def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('launch-detail', args=[str(self.launch_id)]) def get_failed_p1_features_no(self): return self.p1_total - self.p1_passed def get_failed_p2_features_no(self): return self.p2_total - self.p2_passed def get_failed_p3_features_no(self): return self.p3_total - self.p3_passed views.py def monthly_report(request, pk=-1, launch_id='#'): last_launches = Launch.objects.exclude(launch_id='-1').order_by('-launch_id')[:5] scenario_history_dict = {} for launch in last_launches: for feature in launch.features.all(): for scenario in feature.scenarios.all(): scenario_link = launch.get_absolute_url() + "/" + feature.feature_name + "/" + str(scenario.scenario_id) scenario_hist = ScenarioHist(scenario_link, scenario.status) if scenario.scenario_id in scenario_history_dict: scenario_history_dict[scenario.scenario_id].append(scenario_hist) else: scenario_history_dict.update({scenario.scenario_id: [scenario_hist]}) launch = Launch.objects.get(pk=pk) context = { "launch": launch, "launch_id": launch_id, "dataMonthly_report": MonthlyReport.objects.all() } return render(request, 'monthly_report.html', context=context) class ChartDataMonthlyReport(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None, from_date = '2020-09-18', to_date = '2020-09-30'): historical_launches_bymonth = … -
Django - Many to Many Field Ordering Issue
class Sandeep(models.Model): model_id = models.CharField(max_length=200, unique=True) processors2 = models.ManyToManyField(ConfiguratorProduct,blank=True, related_name="processors2", verbose_name="Processors2") model_sk= models.CharField(max_length=200, unique=True) model_dk = models.CharField(max_length=200, unique=True) model_pk = models.CharField(max_length=200, unique=True) models.DateTimeField(auto_now_add=True).contribute_to_class( Sandeep.processors2.through, 'date_added2') The above is my model and I am using processors2 as a Many to many Field. I want to save many to many field in the same order which i am adding to Sandeep from django Admin but my order get shuffled by the default id of ConfiguratorProduct[Manyto many relation model] I tried using the above statement and successfully added one new field timestamp but not able to get the data into django admin UI as per the time-stamp. I have checked so many solutions but not able to find out the best way to display many to many field in the same order which I am adding to the Model.