Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Streaming zip in Django for large non-local files possible?
I've got a proxy written in Django which receives requests for certain files. After deciding whether the user is allowed to see the file the proxy gets the file from a remote service and serves it to the user. There's a bit more to it but this is the gist. This setup works great for single files, but there is a new requirement that the users want to download multiple files together as a zip. The files are sometimes small, but can also become really large (100MB plus) and it can be anywhere from 2 up to 1000 files simultaneously. This can become really large, and a burden to first get all those files, zip them and then serve them in the same request. I read about the possibility to create "streaming zips"; a way to open a zip and then start sending the files in that zip until you close it. I found a couple php examples and in Python the django-zip-stream extension. They all assume locally stored files and the django extension also assumes the usages of nginx. There are a couple things I wonder about in my situation: I don't have the files locally stored. I can … -
How to find the highest value of a ForeignKey field for a specific user in Django
I am building an app that allows users to record their workouts. First they will create an exercise, (e.g Bench Press), and then they will complete a form to show how much weight they were able to lift for that specific exercise. Their results will display below the form. There will be many workout forms, relating to many different workouts. The workouts and exercises will also be specific to each user. Here is my models.py: from django.contrib.auth.models import User class Exercise(models.Model): name = models.CharField(max_length=100) class Workout(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) weight = models.DecimalField(default=0.0, max_digits=5, decimal_places=1) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) What I now want to do is be able to show the user what their max lift was for each different workout, but can't figure out how to retrieve this information. I have searched for the answer online and it seems that using aggregate or annotate might be the way to go, but I have tried a bunch of different queries and can't get it to show what I need. Hope somebody can help. -
Static files not loaded into templates
I am new to Django and so far all I know about static files is that they are CSS, JS, and images and they should be in a directory called static within the app directory but when I use one of these files in my template like that: first I load the static files {% load static %} <!-- in the 1st line of the template --> then I link the CSS file like that <link href="{% static 'auctions/styles.css' %}" rel="stylesheet"> They don't load and the styles don't seem to appear so I just want to know what I am missing here -
Django container fails to connect MySQL container with error "Can't connect to MySQL server on 'db' (115)" in the first migration
I am trying set up a Django development environment using Docker. But, the Django container fails to connect to MySQL container with following error: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") Please give me some advises to solve this problem. Below is the structure of the directory: . ├── python │ ├── Dockerfile │ └── requirements.txt ├── docker-compose.dev.yml ├── mysql │ ├── conf.d │ │ └── default_authentication.cnf │ ├── Dockerfile │ └── init.d │ └── init.sql ├── nginx Below is the Docker configuration: ("octave" is the name of the web application). version: '3.7' services: python: build: context: ./python dockerfile: Dockerfile command: uwsgi --socket :8001 --module octave.wsgi --py-autoreload 1 --logto /tmp/uwsgi.log restart: unless-stopped container_name: Django networks: - django_net volumes: - ./src:/code - ./static:/static expose: - "8001" depends_on: - db db: image: mysql:latest restart: unless-stopped container_name: MySQL networks: - django_net ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: ${OCTAVE_DB_PASSWORD:-default} TZ: "Asia/Tokyo" volumes: - octave.db.volume:/var/lib/mysql - ./mysql/init.d:/docker-entrypont-initdb.d - ./mysql/conf.d:/etc/mysql/conf.d (... the configuration of nginx is omitted.) networks: django_net: driver: bridge volumes: octave.db.volume: name: octave.db.volume Below is requirements.txt: Django==3.1.4 uwsgi==2.0.18 mysqlclient==2.0.1 Below is mysql/init.d/init.sql: CREATE DATABASE IF NOT EXISTS octave_db CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; CREATE USER IF NOT EXISTS 'octave_user'@'%' IDENTIFIED BY ${OCTAVE_DB_PASSWORD} … -
OperationalError at /admin in Django
I am following this article from simpleisbetterthancomplex to build a multiple usertype in django. but when i visit the admin page this is the error i get. "no such column: catalog_merchant.user_id" models.py class User(AbstractUser): is_customer=models.BooleanField(default=False) is_merchant=models.BooleanField(default=False) class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) shop_name=models.CharField(max_length=100) shop_address=models.CharField(max_length=100) phone_number=models.IntegerField() email_address=models.EmailField() country=models.CharField(max_length=100) city=models.CharField(max_length=100) state=models.CharField(max_length=100) zip_code=models.IntegerField() thanks beforehand. -
Customize the JSON output in django-rest api
I'm working on the creation of a django REST api where I can visualize some numerical data of different variables. This values are allocated on a database (using sqlite) each one as a column of the same table. The problem is that the results appear as an array of objects like this: (each object is a row in the table) But I would like to have it in the form of a object of arrays: "results": { "dir_racha": [125.0,137.0,131.0], "hum_rel": [87.0,87.0,86.0], // } I found out that I can use posgres' models.ArrayField object, but I don't want to change my database engine. Also, I think I can get what I want by using JsonResponse and doing it by hand, but I want to use django REST framework if possible. This is the model I use: class Data(models.Model): dir_racha = models.FloatField() hum_rel = models.FloatField() presion = models.FloatField() racha = models.FloatField() tem = models.FloatField() v_vent = models.FloatField() datetime = models.CharField(max_length=20, primary_key=True) def __str__(self): return 'Data.' The serializer class: class DataSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Data fields = ('dir_racha', 'hum_rel',\ 'presion', 'racha', 'tem', 'v_vent', 'datetime') And finally the viewset: class DataViewSet(viewsets.ModelViewSet): queryset = Data.objects.all().order_by('datetime') serializer_class = DataSerializer -
Many кусщкві in the foreign key field (ModelForm Django)
I have tables: # model.py class ctNovaPoshta(models.Model): SiteKey = models.CharField(max_length=50, verbose_name="Код відділення", primary_key=True) ShortAddress = models.CharField(max_length=200, verbose_name="Адреса відділення") Number = models.CharField(max_length=50, verbose_name="Номер відділення") def __str__(self): return f'{self.ShortAddress} [{self.Number}]' class docOrder(models.Model): ... nova_poshta = models.ForeignKey(ctNovaPoshta, null=True, blank = True, on_delete = models.DO_NOTHING, verbose_name="Нова пошта") # form.py OrderFormSet = inlineformset_factory(docOrder, docOrderProduct, form=OrderProductForm, extra=1, ) # view.py class OrderProductCreate(CreateView): template_name = 'order/order_create.html' model = docOrder fields = ['description', 'client', 'type_price', 'status', 'date_ship', 'nova_poshta'] success_url = reverse_lazy('order-list') def get_context_data(self, **kwargs): data = super(OrderProductCreate, self).get_context_data(**kwargs) if self.request.POST: data['product'] = OrderFormSet(self.request.POST) else: data['product'] = OrderFormSet() return data def form_valid(self, form): ... In the table ctNovaPoshta I have 10,000 records. So when I generate an html page: ... <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab"> {{ form.nova_poshta|as_crispy_field }} </div> ... I have a very buggy browser. How to properly generate an html page in such crap? What are the approaches to solving this problem? is it possible to completely change the display logic? -
How to edit data from database in Django?
I'm a beginner in Django . I got all data associated with User and displayed it in a table. And one field in the table is a dropdown which can be used to change the value in each row and there is an update button at the end to update changes(if any) in the dropdown.How can i do the updation ? I know it is simple. What should i do ? Just guide me .ThankYou //views.py @method_decorator(login_required, name='dispatch') class AllUsersView(TemplateView): template_name = 'users/all_users.html' def get_context_data(self, **kwargs): context = super(AllUsersView, self).get_context_data(**kwargs) context['users'] = User.objects.all() return context // all-users.html <table class="addrss-list"> <tr> <th>Name</th> <th>Email</th> <th>Country</th> <th>Plan</th> <th>Role</th> <th>Action</th> </tr> {% for user in users %} <tr> <td>{{user.username}}</td> <td>{{user.email}}</td> <td>{{user.country}}</td> <td>{{user.subscription.active_plan.title}}</td> <td> {% if user.role == "student" %} <select> <option selected>Student</option> <option>Tutor</option> </select> {% elif user.role == "tutor" %} <select> <option selected>Tutor</option> <option>Student</option> </select> {% endif %} </td> <td><a href="/update-user/{{user.id}}" class = "text-decoration-none">Update</a></td> </tr> {% endfor %} </table> -
Work with templates as frontend developer
I have accepted a job, in which I have to work on some html and css in frontend. However, the files I was given to work with seem to be interpreted by some kind of interpreter (I think Django or Jinja2). All I have however are frontend files and I cannot figure out, how to debug my code without any interpreter. F:. ├───static │ ├───css │ └───images │ └───navigation └───templates ├───admin ├───cart ├───home ├───order ├───partials ├───payment ├───product ├───ticket └───user above I have listed the folders I have to work with. Each folder only contains html files, that look like this for example: <input id="navi-open" type="checkbox" name="" class="ct" /> <div id="navigation" class="column"> <label for="navi-open" class="navi-button"> <img src="{{ url_for('static', filename='images/cancel.png') }}" alt="" /> </label> <div id="navigation-items" class="column h-sb"> <div class="category"> <a href="{{ url_for('home.home') }}" style="opacity:1" class="navigation-item light {{ 'active' if current_page == 'homepage' else '' }}"> <div style="opacity:1" class="icon"> <img src="{{ url_for('static', filename='images/karma_blackwhite.png') }}" alt="" style="filter: invert(0);" /> </div> <div class="label">Homepage</div> <div class="tooltip">Homepage</div> <div class="indicator"></div> </a> <a href="{{ url_for('home.news') }}" class="navigation-item {{ 'active' if current_page == 'news' else '' }}"> <div class="icon"> <img src="{{ url_for('static', filename='images/navigation/newspaper.png') }}" alt="" /> </div> <div class="label">News</div> <div class="tooltip">News</div> <div class="indicator"></div> </a> <a href="{{ url_for('home.about') }}" class="navigation-item … -
How to avoid typing "python" at the begining of new command [closed]
I have two notebooks Windows 10. Both with same installed PyCharm version. If I want to perform a command: At the first one I should type: manage.py runserver At another one I must type: python manage.py runserver (without word "python" the command would not perform). How to fix at the 2nd notebook to avoid typing "python" every time ? P.S. I added all routes to python39.exe to the PATH - no result. -
module has no Attribute in Django
i check everything but i still can't figure out the problem. this is the error that i get "AttributeError: module 'users.views' has no attribute 'CustomerSignUp' " urls.py path('customer/register/', views.CustomerSignUp.as_view(), name='customer_homepage'), path('merchant/signup/',views.MerchantSignUpView.as_view(), name='merchant_signup'), views.py class CustomerSignUpView(CreateView): model = User form_class = CustomerSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'customer' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('catalog:index') thanks beforehand. -
Using Proxy as Static IP [PythonAnywhere] [closed]
recently I deployed a python web on Pythonanywhere and I also integrate some third-parties in it, then turned out I need a Static IP for third-parties to add to whitelist. Unlucky for me, PythonAnyWhere doesn't support it. As I intend to use a Proxy server for this purpose, will it work or do you have any advices for it. Many thanks in advance, -
Which Language or Framework Should I Use to Create an ETL
I am trying to build an ETL app which can schedule automated ingestion of weather and agriculture data from websites like agromonitoring.com and openweathermap.org. The app should, on schedule, pull data from an API, split the contents of the JSON response into individual JSON files and save it in AWS S3. The same app should also POST this same JSON to another API endpoint. I am unsure which language/framework or technology to study and use for this project. I tried with Apache Nifi but I am unable to figure out how to dynamically change the date parameter on the API's URL. What is the easiest and fastest way to do this? Thank you in advance for the assistance! -
Multiple forms in django template always submitting same form
I have a template with 3 forms, and submitting any of the last 2 always only results in the first form being submitted. I've searched on this issue, and tried adding prefixes and conditional logic like is suggested in answers to this question, but neither solution is working for me. A single form works absolutely fine, it is just attempting to get 3 working, or even 2, where I am running into issues. Is there another solution other than using conditional logic and prefixes? My current attempt is: if request.method == "POST": approveform = ApproveOrDenyForm(request.POST, instance=contestant, prefix='approved') if approveform.is_valid(): contestant = approveform.save() else: approveform = ApproveOrDenyForm(instance=contestant, prefix='approved') if request.method == "POST" and not approveform.is_valid(): statusform = ChangeStatusForm(request.POST, instance=contestant, prefix='status') if statusform.is_valid(): contestant = statusform.save() else: statusform = ChangeStatusForm(instance=contestant, prefix='status') if request.method == "POST" and not approveform.is_valid() and not statusform.is_valid(): assignteamform = AssignTeamForm(request.POST, instance=contestant, prefix='assignteam') if assignteamform.is_valid(): contestant = assignteamform.save() else: assignteamform = AssignTeamForm(instance=contestant, prefix='assignteam') I tried adding conditional logic to every form also, e.g. making sure approveform was not statusform or assignteamform, but it made no difference. What is the correct approach here? -
Django heroku : Unable to deploy application (ModuleNotFoundError)
When I am deploying my Django application on Heroku, the application crash and Heroku's logs notify me about this error : 2020-12-07T12:55:55.982458+00:00 app[web.1]: ModuleNotFoundError: No module named 'WebSite' The thing is, WebSite is not a python module, but a folder in my Django application (Achievement Comparer behing my main application name). Repository picture Of course, if I start my application locally, everything works just fine. -
Loading "/Media/" files with Django Webpack Loader
After I setup a frontend with a django webpack loader, the media files are not rendering. settings.py STATIC_URL = '/static/' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) WEBPACK_LOADER = { "DEFAULT": { "BUNDLE_DIR_NAME": "dist/", "STATS_FILE": os.path.join(BASE_DIR, "frontend", "webpack-stats.json"), } } And urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include("companies.routes.urls")), path('api/v2/', include("projects.routes.urls")), path('accounts/register/', RegistrationView.as_view( form_class=CompanyUserForm, success_url="/", ), name="django_registration_register"), path('accounts/', include("django_registration.backends.one_step.urls")), path('accounts/', include("django.contrib.auth.urls")), path('api-auth/', include("rest_framework.urls")), path('api/rest_auth/', include("rest_auth.urls")), path('api/rest_auth/django_registration/', include("rest_auth.registration.urls")), re_path(r'^.*$', IndexTemplateView.as_view(), name="entry-point") ] # adding the media root path. urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But when I browse the media file url, image isn't rendering. I think the problem lies in the webpack loader, but I am not sure how to fix the issue here. -
How to restrict anonymous users to vote only once in django poll app?
I want to limit that each user can only vote once for a question in my poll application. In case of authenticated users my code works very well, however when an anonymous user (not registered) try to vote I got the next error: TypeError: 'AnonymousUser' object is not iterable How can I restrict that anonymous users could vote only once? You can see my related code here: models.py: class Question(models.Model): question_text = models.TextField("Question", max_length=300) category = models.CharField(max_length=100) pupblish_date = models.DateTimeField(default=now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField("Choice",max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Vote(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) voter = models.ForeignKey(User, on_delete=models.CASCADE) views.py: def vote_view(request, poll_id): poll = get_object_or_404(Question, pk=poll_id) if Vote.objects.filter(question=poll, voter=request.user).exists(): messages.error(request,"Already Voted on this choice") return redirect("poll_app:home") else: if request.method == "POST": try: selected_choice = poll.choice_set.get(pk=request.POST["clap"]) except(KeyError): return render(request, "poll_app/vote.html", { "poll": poll, "error_message": "You haven't voted yet!" }) else: selected_choice.votes += 1 selected_choice.save() Vote.objects.create(voter = request.user, question=poll) return redirect(reverse("poll_app:result", args=(poll.id,))) else: context = {"poll": poll} return render(request, "poll_app/vote.html", context) Thanks! -
django, constraint without effect?
I had something like the following model in my Django Application: class custom_user(models.Model): # ... number = models.IntegerField() # ... location = models.ForeignKey( Locations, on_delete=models.PROTECT ) I then relaized that number and location needs to be unique together, therefore I added the following to custom user class Meta: verbose_name_plural = "Patienten" constraints = [ models.UniqueConstraint( fields=['nummer', 'praxis'], name='unique_patientennummer_praxis' ) ] I ran makemigrations and migrate afterwards, and the console told me that the contraint was added successfully. Unfortunately it is still possible to add new users with the same number and location! Am I missing something? -
Can't paass count result using annotate with Django querysete to template
I'm using annotate with my Django queryset to count a number of records. I am using it with filter and understand the order makes a difference. My query is: numcontestants = Contestant.objects.filter(assigned_team__id=urlid).annotate(num_contestants=Count('id')) When I pass numcontestants to my template and display it with {{ numcontestants }}, I see a queryset containing each of the records I want to view. When I try {{ numcontestants.num_contestants }} I get nothing. I don't want to have to iterate over numcontestants to get a count, my understanding was that num_contestants should be a single integer number. What is the right way to access the number generated by annotate here? -
Image Upload Issue with TinyMCE
I'm trying to upload the images from tinymce's textarea to the server side media folder. I try to do it with file_picker_callback instance from tinymce and images_upload_url with postAcceptor.php. Here's the details; Tinymce customize script: tinyMCE.init({ selector: 'textarea', plugins: 'quickbars wordcount preview codesample image imagetools hr link lists media fullscreen autosave powerpaste nonbreaking', image_title: true, automatic_uploads: true, images_upload_url: "/static/js/postAcceptor.php", images_upload_base_path: "/media/images", file_picker_types: 'image file media', /* and here's the custom image picker */ file_picker_callback: function (cb, value, meta) { var input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'image/*'); input.onchange = function () { var file = this.files[0]; var reader = new FileReader(); reader.onload = function () { var id = 'blobid' + (new Date()).getTime(); var blobCache = tinymce.activeEditor.editorUpload.blobCache; var base64 = reader.result.split(',')[1]; var blobInfo = blobCache.create(id, file, base64); blobCache.add(blobInfo); cb(blobInfo.blobUri(), { title: file.name }); }; reader.readAsDataURL(file); }; input.click(); } }); *And the postAcceptor.php I get from static folder: <?php $accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com", "http://127.0.0.1", "127.0.0.1"); $imageFolder = "/media/images"; if (isset($_SERVER['HTTP_ORIGIN'])) { if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } else { header("HTTP/1.1 403 Origin Denied"); return; } } if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { header("Access-Control-Allow-Methods: POST, OPTIONS"); return; } reset ($_FILES); $temp = current($_FILES); if (is_uploaded_file($temp['tmp_name'])){ if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) { … -
How to delete whole directory with files in it using Django default_storage
My Storage Structure: my-bucket/ - dir_1/ - file_1 - dir_A - dir_2/ What I tried: default_storage.exists('dir_2/') o/p: True default_storage.delete('dir_2/') dir_2 got deleted successfully. But when I try the same for dir_1: default_storage.exists('dir_1/') o/p: False default_storage.delete('dir_1/') This doesn't work. dir_1 still exists How to delete dir_1 completely using the default_storage? -
Cannot link an authenticated user to their new Account upon creation
I'd like each User to be able to create an Account (max of one account each). The user in session won't be able to see the option to create an account unless they are logged in/authenticated. When I log in and click submit on the Create Account form, this error is raised: 'ValueError at /accounts/create/ Cannot assign "<SimpleLazyObject: <User: Jimmy>>": "Account.user" must be a "User" instance.' My models.py: from django.db import models from django.contrib import auth from django.utils.text import slugify from django.urls import reverse from django import template register = template.Library() class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return self.username class Account(models.Model): user = models.OneToOneField(User,related_name='customer_account',on_delete=models.CASCADE) first_name = models.CharField(max_length=30,blank=True) surname = models.CharField(max_length=30,blank=True) billing_address = models.TextField(blank=True) delivery_address = models.TextField(blank=True) def __str__(self): return f"Account: {self.user.username}" def get_absolute_url(self): return reverse('about',kwargs={'username':self.user.username, 'pk':self.pk}) Views.py: from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from braces.views import SelectRelatedMixin from django.views.generic import (CreateView, UpdateView, ListView, DetailView, TemplateView,) from . import forms from . import models from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import redirect from django.contrib.auth import get_user_model # User = get_user_model() class SignUp(CreateView): form_class = forms.CreateCustomerForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html' class CreateAccount(LoginRequiredMixin,CreateView): model = models.Account fields = ['first_name','surname','billing_address','delivery_address'] template_name = 'accounts/create_account.html' def form_valid(self,form): self.object = form.save(commit=False) … -
Django template tags through TinyMCE editor
I have a custom template tag which returns the URL of an image @register.simple_tag def mediaURL(slug): """Gets the URL of the media with the inputted slug""" print("Here") return str(utilities.getMediaURL(slug)) Referencing this template tag directly from the HTML file like shown below returns the URL of the image. {% load custom_tags %} {% mediaURL 'logo-300-by-300' %} When I try to create an image though the TinyMCE editor and set the image source as the template tag, the template tag isn't being rendered, {% block content %} {{ page.body | safe }} {% endblock %} This is the source code from the browser: <img style="display: block; margin-left: auto; margin-right: auto;" src="{% mediaURL 'logo-300-by-300' %}" alt="" /> How do I allow template tags through the TinyMCE editor? -
How to seperate messages based on both sender and receiver of the message in blog app using Django
Guys I have the following code for my message app in my instagram-like project in Django. I can get all the messages in my app. In the dialogues page I want to just classify the messages into categories based on the dialogues that the user has between him/herself and the other users of the app. How can I classify these messages. Is there any good solution for that. Just know that I dont want any online chat or anything related to web socket programming. Model of the Message: class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') dispatcher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='dispatcher') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') content = models.TextField(max_length=500, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) content = models.TextField() def get_dialogues(user): sent_messages = Message.objects.filter(dispatcher=user) received_messgaes = Message.objects.filter(receiver=user) all_messages = sent_messages | received_messgaes return all_messages And this is the view @login_required def dialogues(request): messages = Message.get_dialogues(request.user) return render(request, 'message/dialogues.html', {'messages':messages}) I think this much of code suffices for the question to be answered. -
Is there a way to merge 2 querysets in Django and order them by a their repecting field?
I'm trying to create a twitter clone and this is my user and tweet Model(some irrelevant fields have been removed). class TwitterUser(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE,primary_key=True) Bio = models.CharField(max_length=200, blank=True) Location = models.CharField(max_length=200, blank=True) Website = models.URLField(blank=True) ProfilePicture = models.ImageField(upload_to="Twitter", default="../static/twitter/images/default_profile.png") CreateDate = models.DateField(default=timezone.now) class Tweet(models.Model): TweetBody = models.CharField(max_length=140, blank=False) TweetDate = models.DateTimeField(default=timezone.now) Owner= models.ForeignKey(to=TwitterUser,on_delete=models.CASCADE,related_name="Owner") RetweetedBy= models.ManyToManyField(to=TwitterUser,related_name="Retweeted",blank=True,through="RetweetIntermediate") and this the table that my many to many relationship for retweet is using. class RetweetIntermediate(models.Model): twitteruser=models.ForeignKey(TwitterUser,on_delete=models.CASCADE) tweet=models.ForeignKey(Tweet,on_delete=models.CASCADE) retweetDate=models.DateTimeField(default=timezone.now) In profile view all the tweets and retweets should be shown ordered by date what I'm doing right now (and it is working fine) is this: def keymaker(a): return a.TweetDate def ProfileView(request): tweets= list(Tweet.objects.filter(Owner=user.user_id,IsReplyToTweet__isnull=True).order_by("-TweetDate")) retweets = list(user.Retweeted.all().order_by("-id")) retweetInter=RetweetIntermediate.objects.all().order_by("-tweet_id") for i , j in zip(retweets,retweetInter): i.TweetDate=j.retweetDate tweets=(tweets+retweets) tweets.sort(key=keymaker,reverse=True) I retrieve all the tweets ordered by date. then I retrieve all of retweets and make a list out of them and change the data of tweet to the date saved in intermediate table and merge both lists and sort them by date. I want to know is there a better way or more standard way to do this? Thanks in advance.