Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF Filter not working with Boolean Value with Postgres
Getting the wrong output when using DRF Filter, It returns data based on user_id only looks like it hasn't consider itemmaster_item_active status for the query. Views.py from django_filters.rest_framework import DjangoFilterBackend class ItemmasterAPIView(mixins.CreateModelMixin, generics.ListAPIView): serializer_class = ItemmasterSerializer queryset = Itemmaster.objects.all() filter_backends = [DjangoFilterBackend] filter_class = ItemMasterItemFilter Filters.py from django_filters import rest_framework as filters from itemmaster.models import Itemmaster, ItemmasterItem class ItemMasterItemFilter(FilterSet): user_id = filters.CharFilter('itemmaster_updated_by_id') item_status = filters.BooleanFilter('itemmaster__itemmaster_item_active') class Meta: model = Itemmaster fields = ('user_id', 'item_status',) Serializers.py class ItemmasterItemSerializer(serializers.ModelSerializer): item_ref_image = serializers.SerializerMethodField(read_only=True) class Meta: model = ItemmasterItem fields = ('item', 'itemmaster_item_active') class ItemmasterSerializer(serializers.ModelSerializer): itemmaster = ItemmasterItemSerializer(many=True, read_only=True) class Meta: model = Itemmaster fields = ( 'itemmaster', 'itemmaster_updated_by') models.py itemmaster_updated_by = models.OneToOneField( User, on_delete=models.CASCADE, related_name='itemmaster_updated_by') class ItemmasterItem(models.Model): itemmaster = models.ForeignKey(Itemmaster, on_delete=models.CASCADE, related_name='itemmaster') itemmaster_item_active = models.BooleanField(default=True) -
Query haystack search with multiple URL params
I have my search working the way I need it to for the most part, but I would like to be able to sort based on the categories a user selects. I have sub-classed searchForm to contain: def no_query_found(self): """ Determines the behavior when no query was found. By default, no results are returned (``EmptySearchQuerySet``). Should you want to show all results, override this method in your own ``SearchForm`` subclass and do ``return self.searchqueryset.all()``. """ return self.searchqueryset.models(Idea) def search(self): sqs = super(IdeaCategories, self).search() if not self.is_valid(): return self.no_query_found() if self.cleaned_data['category']: sqs = sqs.filter(tags__contains=self.cleaned_data['category']) return sqs The following works as expected: /testing/search/?q=test -> All results related to "test" /testing/search/?category=Development&q= -> All results related to "development" /testing/search/?category=Development&q=book -> All results related to "development" and containing "book" The only thing I can't figure out is how to get it to search correctly on the categories of 2 or more: /testing/search/?category=Development&category=Supplemental+Material&q= Is there a way to get a list of categories, query and filter for combined results? Such as: sqs = sqs.filter(tags__contains["Development", "Supplemental Material"]) -
Task Queues for Windows and Django
I am looking for a task queue software to pair with Django(and aMySQL database). I am working in a Windows environment, and I have a couple of requirements: Supports a production environment; From a Django view, I can see the process ID and if the process has executed yet, and kill the process in certain situations. I tried using celery but the newest version of celery does not work within a Windows environment. Any help is appreciated, thank you. -
django table 2: hyper link table rows to redirect to different URLS
I am trying to hyperlink the rows of the class column of to serve as link to other pages. I read the doc about hyperlinks as well as some posts here such as The linkcolumn about django-tables2. but they don't resolve my problem because from my understanding the link is made by referencing the Pks of a UNIQUE TABLE in each row. In my situation, the link is made using a different model for each row so I don't know how to reference a pk. Here is what I have been able to do so far: MAIN PAGE TABLE: class ClassificationTable(tables.Table): Class = tables.Column(gettext_lazy("class"),localize= True) revenue_proportion = tables.Column(gettext_lazy("revenue proportion"),localize= True) Quantity_of_items = tables.Column(gettext_lazy("quantity of items"),localize= True) class Meta: model = Classification fields = ('Class', 'revenue_proportion', 'Quantity_of_items', ) template_name = "django_tables2/bootstrap4.html" here is the html code for the main page: {% load static %} {% load i18n %} {% load django_tables2 %} class="no-padding-bottom"> <div class="container-fluid"> <div class="row"> <div class="col-lg-8"> {% render_table table %} </div> Here are the models used in the other pages: class class_aa1(models.Model): Id = models.CharField(max_length=100, primary_key=True, verbose_name= 'items') revenue_contribution_in_percentage = models.FloatField(default=0, verbose_name= 'value contribution') margin = models.FloatField(default=0, verbose_name= 'value') number_of_orders_placed = models.FloatField(default=0, verbose_name= 'number of orders placed') number_of_sales … -
How to mock django.db.connection.schema_name
I am trying to test a multi-tenant django app. I'm trying to mock a connection to the public tenant: class ViewsTest(ViewTestUtilsMixin, TenantTestCase): def setUp(self): self.factory = RequestFactory() def test_some_public_only_view(self) # generate a request instance so we can call our view directly request = self.factory.get('/') with patch('tenant.views.connection.schema_name', return_value=get_public_schema_name()): response = some_public_only_view(request) self.assertEqual(response.status_code, 200) However, when I debug this to check the value of schema_name in the some_public_only_view method during the test, I get this: <MagicMock name='schema_name' id='140578910478880'>, so at least I know I'm patching the correct location. The problem is that schema_name is not a method, so it doesn't use the return value. So how can I mock the schema_name? The view being testing is using it in this way: if connection.schema_name == get_public_schema_name(): # do stuff I also tried this: with patch.object('tenant.views.connection.schema_name', return_value=get_public_schema_name()): which gives me: AttributeError: tenant.views.connection does not have the attribute 'schema_name' -
Form not validating in Django with a URLFIELD and IMAGEFIELD
I have been trying to set up a simple form so users can register an ad to be shown on the homepage of the website. For some reason, whatever I try to do, my form is not validating. What am I doing wrong? I have tried things like adding the enctype and sifting through numerous stackoverflow questions related to this. I would appreciate if you could help! Below is my code: Models.py: from django.db import models class ad(models.Model): ad_link = models.URLField(max_length=2000) image = models.ImageField(upload_to="ads/") def __str__(self): return self.ad_link forms.py: from django import forms from .models import ad class AdForm(forms.ModelForm): class Meta: model = ad fields = ('ad_link', 'image') Views.py: def ad_registration(request): context= {} if request.method == "POST": form = AdForm(request.POST or None) if form.is_valid(): form.save() else: form.save() return render(request, "ad_registration.html", {}) else: return render(request, "ad_registration.html", {}) HTML file with form: <form enctype="multipart/form-data" class="form-signin" method="post" action="/ad_registration"> {% csrf_token %} <div class="d-flex flex-column pb-3"> <img class="img-fluid mx-auto d-block" src= "/static/logo.png" alt="Logo of our school" width=23% height=23%> </div> <h1 class="h3 mb-3 font-weight-normal">Register your ad</h1> <input type="url" name="ad_link" id="inputurl" class="form-control" placeholder="URL of your ad" required> <label for="inputimage">File of Ad:</label> <input type="file" class="form-control-file" id="inputimage" name="image" accept="image/*" required> <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button> </form> -
Django ORM time delta returns that the firld is not defined
from django.utils import timezone from datetime import timedelta Activity.objects.filter(last_response__lte=timezone.now()-timedelta(days=sla)) On executing it I am getting message that sla is not defined. but my model contains both fields last_response and sla and defined as an integer. What am i doing wrong? -
Django: Easiest way to join all numerical data into one QuerySet when doing alphabetical pagination?
I'm trying to sort query results into alphabetical sections, like so: This works with the following code: def get_context(self, request): # Get published shows, ordered alphabetically context = super().get_context(request) shows = ShowPage.objects.child_of(self).live().order_by("name") context["pages"] = [{"letter" : i, "shows" : shows.filter(name__istartswith=i.upper())} for i in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"] return context The next step is to combine all shows that start with any number into just one group labeled "0-9". The following does what I want, but it's awfully verbose and I'm wondering if there's an easier way I just don't know about: def get_context(self, request): # Get published shows, ordered alphabetically context = super().get_context(request) shows = ShowPage.objects.child_of(self).live().order_by("name") pages = [{"letter" : i, "shows" : shows.filter(name__istartswith=i.upper())} for i in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"] digits = {"letter" : "0 - 9", "shows" : []} for index, alphabet in enumerate(pages): if alphabet["letter"].isdigit(): for show in alphabet["shows"]: digits["shows"] += [show] while pages[0]["letter"].isdigit(): print(pages[0]) pages.pop(0) pages.insert(0, digits) context["pages"] = pages return context Any ideas? -
How to use tokens in frontend for authentication
I am currently developing a React-Django app and using dj-rest-auth package and JWT for authentication on the backend. It works perfectly fine and when a user loggs in, server responses with a HttpOnly cookie which contains access_token. What I don't understand is how can I use the access_token that in the response-cookie for requests in my web app if I can't read the token value from my frontend since it is HttpOnly? I tried js-cookie package for storing JWT in cookies and since it is written in JS, I can't make it HttpOnly. So I am storing access_token in a cookie but doesn't it break the point of HttpOnly cookies since they both store the same token value? -
Django Celery task gives integrityError: CHECK constraint failed when saving instance of model
I am using Celery to set up periodic tasks to automatically change instances of a model I have. Here is my tasks.py code from celery import task from celery import shared_task from django.db import models from tracker.models import Medicine @task(name='decrement number of tablets') def decrement_medicine(): med = Medicine.objects.get(id=2) print("old tablets is " + str(med.Tablets_In_Current_Box)) med.Tablets_In_Current_Box -= med.Dose_Tablets print("new tablets is " + str(med.Tablets_In_Current_Box)) med.save() Here is the Medicine model which the task uses: class Medicine(models.Model): Medicine_Name = models.CharField(max_length=100) User_Associated = models.ForeignKey(User, on_delete=models.CASCADE) Tablets_In_Box = models.PositiveIntegerField() Tablets_In_Current_Box = models.PositiveIntegerField() Dose_Tablets = models.PositiveIntegerField() Number_Of_Boxes = models.PositiveIntegerField() Last_Collected = models.DateField() class Meta: constraints = [ models.UniqueConstraint(fields = ['Medicine_Name', 'User_Associated'], name = 'One of each med per user') ] @property def Days_Left(self): return(floor( (self.Number_Of_Boxes*self.Tablets_In_Box) / self.Dose_Tablets)) def __str__(self): return self.Medicine_Name def get_absolute_url(self): return reverse('tracker-home') I am trying to test my decrement_medicine task in my python shell. But I am having a problem with the med.save() line (because I have no issue calling the function when removing the save line.) I get the following error: The above exception was the direct cause of the following exception: [2020-08-13 17:05:32,635: ERROR/SpawnPoolWorker-1] Task decrement number of tablets[98ceec50-ffbf-48d1-8a78-4426c57a7415] raised unexpected: IntegrityError('CHECK constraint failed: tracker_medicine') Traceback (most recent call last): … -
Django: Queryset filtering based on min max set in another table
Consider the following models: Class ExamResults: ... Marks = models.IntegerField(default=0, null=True, blank=True) Course = models.CharField(max_length=255, null=True) Academic_year = models.CharField(max_length=255, null=True) Class ExamSetting: ... GradeAThreshold = models.IntegerField(default=0, null=True, blank=True) GradeBThreshold = models.IntegerField(default=0, null=True, blank=True) ... Course = models.CharField(max_length=255, null=True) Academic_year = models.CharField(max_length=255, null=True) Now I have an API to search/get results from ExamResults for all students. The API works fine and I use Q filters to filters the results. For e.g. ... year_contains = self.request.GET.get("year_contains", "") if year_contains: q_filt |= Q(Academic_year__icontains=year_contains) queryset = queryset.filter(q_filt) ... Now I have a requirement to filter the queryset for the following condition: List of exam results where the Marks exceed GradeAthreshold List of exam results where the Marks are less than GradeAthreshold and exceed GradeBThreshold and so on What would be the best way of doing this? The ExamResults table and ExamSetting has two common fields which can narrow down the thresholds. For e.g. I use the below code in serializer to check if the result has Grade A or not: setting = ExamSetting.objects.filter(Academic_year=obj.Academic_year, Course=obj.Course, is_active=True).first() if obj.Marks >= setting.GradeAThreshold: # Grade A ... This does work and I do get the results with grades. Now how do I add something like this in the … -
Как настроить шаблоны html в django-allauth? [closed]
Всем привет, обьясните пожалуйста как добавить свои шаблоны авторизации)) В чем заключается суть : Я использую модуль django-allauth для авторизации, и так вот мне нужно стилизовать страницу но я не пойму как.((? Объясните пожалуйста как это сделать... -
Maintain a Requests HTTP Library Session across different requests
I am using Requests Python HTTP library. I am using Django and I am trying to keep the requests session alive across different requests in my application. For example this is what I have in my views.py: import requests s = requests.Session() class Class1(views.APIView): def get(self, request): s.get('https://httpbin.org/cookies/set/sessioncookie/123456789') r = s.get('https://httpbin.org/cookies') class Class2(views.APIView): def get(self, request): s.get('https://httpbin.org/cookies/set/sessioncookie/123456789') r = s.get('https://httpbin.org/cookies') The problem with this is that session is global and will be shared with the classes and is not unique to the incoming request. I want tie a session with a request to ensure that there are no session mixing. I looked at possibly save the cookies the request.session (Database Session, sorry for the too much redundancy naming) as I cannot save the requests.session object in the database session item, but not sure if this is the correct way to go. Have anyone come across this issue? Any recommendations / ideas on where to go? Thank you! PS: I'm sort of new to Django... -
My customized Django's widget isn't read and it was automatically substitude from the default widget
I'm trying to customize a GeoDjango's widget. Inside the Django project folder I've created a folder that contains all of my custom widget: My widget inherit from BaseGeometryWidget and use a part of code from OpenLayersWidget. I've changed the js and the template: from django.contrib.gis.forms.widgets import BaseGeometryWidget from django.contrib.gis.geometry import json_regex class OlPoints(BaseGeometryWidget): template_name = 'widgets/olpoints.html' map_srid = 3857 class Media: js = ( 'js/olpoints.js', ) def serialize(self, value): return value.json if value else '' def deserialize(self, value): geom = super().deserialize(value) # GeoJSON assumes WGS84 (4326). Use the map's SRID instead. if geom and json_regex.match(value) and self.map_srid != 4326: geom.srid = self.map_srid return geom Then I've created a test model, form, view and url: **models.py** class Points(models.Model): geom = models.PointField() **forms.py** from gisdatas.models import Points from olpoints.widgets import OlPoints class AddPointsForm(forms.ModelForm): geom = forms.PointField( widget=OlPoints(), ), class Meta: model = Points fields = '__all__' **views.py** from django.shortcuts import render, redirect from .forms import AddPointsForm map_path = 'openlayers/' form_path = 'openlayers/forms/' def add_points(request): if request.method == "POST": input_form = AddPointsForm( request.POST or None, ) if input_form.is_valid(): new_geopost = input_form.save(commit=False) new_geopost.save() return redirect('points-map') else: input_form = AddPointsForm() template = form_path + 'add_points.html' context = { 'geoform': input_form, } return render(request, template, context) … -
How to implement (tweet or post is deleted) in a clone Twitter website?
I'm building simple Twitter website using django, just for practicing because i'm still junior developer. Inside my website you can add tweet, like, dislike, edit, delete and retweet. That's the model of my tweet: class Tweet(models.Model): content = models.TextField(max_length=250, blank=True, null=True) image = models.ImageField(upload_to="tweets/images/", blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(NewUser, on_delete=models.CASCADE, related_name='tweets') likes = models.ManyToManyField(NewUser, related_name='likes') dislikes = models.ManyToManyField(NewUser, related_name='dislikes') retweeted_tweet = models.ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f"Tweet: {self.content}" The problem is that i want to track retweeted_tweet to know if it is Null (so now we can consider it as normal tweet), having value (so our tweet is actually a retweet), or it has a value of another tweet but the original tweet deleted (and here is the porblem). suppose i retweeted tweet and the owner of that tweet deleted it; so the retweeted_tweet will become Null and the retweet will be considered as normal Tweet. I need to set retweeted_tweet to specific value so i know that it is a retweet and the original tweet was deleted to be able to display something like (The original Tweet was deleted) but i couldn't do this because its type is models.ForeignKey. -
I have a TemplateSyntaxError when I rendered my Django webpage
I was following the tutorial on Django part 2 for my product app, and I am having trouble rendering Bootstrap according to the tutorial. I am doing a products app just for fun. I got this error which said that the template did not render correctly in my products app. Here is my settings.py. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] This error is preventing me from rendering the webpage home.html correctly. Without the line it works, but when I add it in, it crashes. Here is the template error Invalid block tag on line 7: 'static'. Did you forget to register or load this tag? Is there a way for me to fix this error, and to prevent this error in the future. -
Django ajax search not returning result but the url prints in console
I am developing a Django Ajax search that searches through a list of college courses. After I finished implementing, I realized that the search doesn't work. However, my shell prints out the updated URL. Here is what I mean. If I search for BUS, My console would do this, but my HTML file wouldn't change: Note: If it's easier, I can add a GitHub link to my code $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 13, 2020 - 11:37:25 Django version 3.0, using settings 'smore.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [13/Aug/2020 11:37:28] "GET /courses/ HTTP/1.1" 200 19376 Not Found: /artists/ [13/Aug/2020 11:37:35] "GET /artists/?q=BUS HTTP/1.1" 404 2092 I can't seem to understand where the /artists/ is coming from. I changed the endpoints and the URLs respectively. Here are my files urls.py from django.contrib import admin from django.urls import path from search import views as v urlpatterns = [ path('admin/', admin.site.urls), path('courses/', v.course_view, name = "courses") ] settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # … -
Django: Error with inserting dictionary to my_model.objects.raw() method
I'm performing a query in a function inside the views.py as follows: input_dict = {'id': 'id', 'table': 'my_table', 'first_col': 'my_first_col', 'first_name': 'my_first_name'} query = ''' SELECT %(id)s FROM %(table)s WHERE %(first_col)s = %(first_name)s ''' qs = my_model.objects.raw(query, input_dict) print(qs) which prints: qs: <RawQuerySet: SELECT id FROM my_table WHERE my_first_col = my_first_name > However, when I try to run this line: ids = [item.id for item in qs] it gives me an error: psycopg2.errors.SyntaxError: syntax error at or near "'my_table'" LINE 3: FROM 'my_table' and also: django.db.utils.ProgrammingError: syntax error at or near "'my_table'" LINE 3: FROM 'my_table' What should I do? -
Django ajax: in call does not make any changes
So I made this ajax view for my user model def new_notification(request): user = request.user user.profile.notifications += 1 user.save() return JsonResponse(serializers.serialize('json', [user]), safe=False) I extends my user model with an Integerfield of notification, but when I call the ajax it does not give +1 to my notification model, does anybody know what is going on? -
Separate Users accounts
I want to separate the open sessions in my site so a user can't delete/modify objects from another account. If someone could explain me how do I do that, for example here with the delete function. This is my code: models.py class User(AbstractUser): ##abstract user model pass class Auction(models.Model): ##these are the objects user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) name = models.CharField(max_length=64) img = models.ImageField(upload_to='listing_image', null=True, default="/static/default_image.jpg") description = models.TextField(blank=True) starting_bid = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="auctions", null=True) views.py @login_required(login_url="login") def delete(request, id): auction = get_object_or_404(Auction, id=id) if request.method == "POST": auction.delete() return redirect ('index') return render(request, "auctions/delete.html", { "auction": auction }) html: {{auction.user}} <h1>{{ auction.name }}</h1> <img src="{{ auction.img.url }}" width="600"> <h5>Starting price: ${{ auction.starting_bid }}</h5> <form method="POST" enctype="multipart/form-data"> {%csrf_token%} <button type="submit" class="btn btn-primary">Place a New Bid</button> {{form.as_p}} </form> {%for bid in bids%} <h3>${{ bid.new_bid}}</h3> {%empty%} No offers yet. {%endfor%} {{auction.description}} <h2>Comments</h2> <ul> <p><a href="{% url 'new_comment' auction.id %}" class="btn btn-secondary">New Comment</a></p> {%for comment in comments%} <li>{{comment.user}} - {{comment.created_on}} <p><h4>{{comment.body}}</h4></p> </li> {%empty%} <li>No comments yet.</li> {%endfor%} </ul> <p><a href="{% url 'edit' auction.id %}" class="btn btn-secondary">Edit</a> <a href="{% url 'delete' auction.id %}" class="btn btn-secondary">Delete</a></p> -
Django Admin Look strange
It's a new install of Django 3 and I get this admin look for the panel : I have no error in the browser console I have already done python3 manage.py collectstatic One clue : To be able to see this admin panel without apache 500 error, i must comment : django.contrib.staticfiles in settings.py, under MIDDLEWARE if django.contrib.staticfiles is called in MIDDLEWARE, I have this apache error : TypeError: 'module' object is not callable, My css and js looks ok... I can't find how to correct this view -
Heroku/sendgrid can't install this addon
I've created an django project on heroku which can send emails using sendgrid, this app worked as a charm. I created this app to study a bit about how sendgrid, django and heroku works together. Using the same heroku account, I've created another project after this first project, which would be definitive, and in this project I change the sender email many times, but it is my emails with a custom domain. Unfortunately I had my heroku/sendgrid (I don't have a sendgrid account, I only needed heroku to install sendgrid:starter addon in my project) account banned. When I try to install sendgrid addon in a project which I've deployed, this message is returned(in this case, I am using a custom domain to my email: victor.s.silva@unesp.br): › Warning: heroku update available from 7.42.4 to 7.42.6. Creating sendgrid:starter on ⬢ myproject... ! ▸ An error was encountered when contacting the add-on partner to create ▸ sendgrid:starter. Please try again later. #sometimes this message inform that I have my sendgrid account banned. When I try to install this addon in a deployed project in another account(@gmail.com), I get this message: ▸ The account "victor.santos.cd@gmail.com" is not permitted to install the ▸ sendgrid add-on … -
Django/mod_wsgi/Apache - mod_wsgi is not using the Python version it was compiled for - "ModuleNotFoundError: No module named 'math' "
I'm attempting to deploy a Django application with Apache2 and mod_wsgi on a Ubuntu 16.04.6 server, but I'm struggling with getting mod_wsgi to use the correct python version. I installed mod_wsgi from source, and configured it to compile against the system python3, specifically python3.7.8 My Virtual environment for the Django app is also running python3.7.8. My VirtualHost config file looks like this: <IfModule mod_ssl.c> <VirtualHost *:443> ServerName kumberas.com ServerAdmin webmaster@localhost.com WSGIScriptAlias / /home/dan/app/kumberas/kumberas/main/wsgi.py Alias /static/ /home/dan/app/kumberas/kumberas/static/ <Directory /home/dan/app/kumberas/kumberas/static> Require all granted </Directory> <Directory /home/dan/app/kumberas/venv> Require all granted </Directory> <Directory /home/dan/app/kumberas/kumberas/main> <Files wsgi.py> Require all granted </Files> </Directory> <Location /> AuthType Basic AuthName "Restricted Content" AuthUserFile /etc/apache2/.htpasswd Require user kr AuthBasicProvider file </Location> WSGIDaemonProcess kumberas \ python-home=/home/dan/app/kumberas/venv \ python-path=/home/dan/app/kumberas WSGIProcessGroup kumberas </VirtualHost> </IfModule> And when I try to access the site, I get a 500 Error and the following in my Apache error log. [wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] mod_wsgi (pid=21635): Failed to exec Python script file '/home/dan/app/kumberas/kumberas/main/wsgi.py'. [wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] mod_wsgi (pid=21635): Exception occurred processing WSGI script '/home/dan/app/kumberas/kumberas/main/wsgi.py'. [wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] Traceback (most recent call last): [wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] File "/home/dan/app/kumberas/kumberas/main/wsgi.py", line 12, in <module> [wsgi:error] [pid 21635] [remote xx.xx.xx.xx:58603] from django.core.wsgi import get_wsgi_application … -
How to create a Django queryset that fetch unique objects based on two fields in the same model?
Currently, I am working on a project in which I create a message chatbox. I want to work it like a Facebook messenger dashboard. This is my simple Model class: class Messages(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='senders') receiver = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='receivers') message_content = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) And this is my view query: message_list = Messages.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).\ order_by('-created_at') I want to fetch the most recent messages of each user whether it's sent or received and exclude the duplicate messages like in Facebook messenger. And used database Sqlite3 for this project. It's my first question on Stackoverflow. Sorry if I can't elaborate my question well. Please guide me on how to achieve such functionality. -
Django batch Insert data with foriegn key
How do I perform a batch insert in Django? This is what i have done so far in my views.py for product_id in request.POST.getlist("product"): products=Product(id=product_id) insert_groupofproduct = ProductRelatedGroupAndProduct( product = products ) insert_groupofproduct.save() when i tried to print the print(product_id) the result is '30' but when i tried to print(request.POST.getlist("product")) i get this result " ['30', '31'] " only one data save in my database