Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
retrieve distinct values of manytomanyfield of another manytomanyfield
I have a simple question but multiple google searches left me without a nice solution. Currently I am doing the following: allowed_categories = self.allowed_view.all().difference(self.not_allowed_view.all()) users = [] for cat in allowed_categories: for member in cat.members.all(): users.append(member) return users I have a ManyToManyField to Objects that also have a ManyToManyField for instances of Users. In the code above, I am trying to get all the users from all those categories and get a list of all Users. Later I would like the same in a method allowed_to_view(self, user_instance) but that's for later. How would I achieve this using Django ORM without using 2 for-loops? -
Django-channels error during websocket handshake: unexpected response code: 404 local
When trying to connect to websocket getting response code 404. library versions: channels==3.0.3 channels-redis==3.2.0 Django==3.0.5 django-environ==0.4.5 djangorestframework==3.12.2 djongo==1.3.3 settings.py: ASGI_APPLICATION = "core.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } asgi.py: import os import apps.visitors.routings from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(apps.visitors.routings.websocket_urlpatterns)) ), } ) routings.py: from django.urls import re_path from .consumers import TrackConsumer websocket_urlpatterns = [ re_path(r"ws/track/$", TrackConsumer.as_asgi()), ] consumers.py: from channels.consumer import AsyncConsumer class TrackConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({"type": "websocket.accept"}) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) Redis server is running locally. _._ _.-``__ ''-._ _.-`` `. `_. ''-._ Redis 3.2.9 (00000000/0) 64 bit .-`` .-```. ```\/ _.,_ ''-._ ( ' , .-` | `, ) Running in standalone mode |`-._`-...-` __...-.``-._|'` _.-'| Port: 6379 | `-._ `._ / _.-' | PID: 14918 `-._ `-._ `-./ _.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | http://redis.io `-._ `-._`-.__.-'_.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | `-._ `-._`-.__.-'_.-' _.-' `-._ `-.__.-' _.-' `-._ _.-' `-.__.-' 14918:M 14 Jan 17:14:29.439 # Server … -
Django Fast Access for Time Series Data
I'm working on a web application with Django & PostgreSQL as Backend tech stack. My models.py has 2 crucial Models defined. One is Product, and the other one Timestamp. There are thousands of products and every product has multiple timestamps (60+) inside the DB. The timestamps hold information about the product's performance for a certain date. class Product: owner = models.ForeignKey(AmazonProfile, on_delete=models.CASCADE, null=True) state = models.CharField(max_length=8, choices=POSSIBLE_STATES, default="St.Less") budget = models.FloatField(null=True) product_type = models.CharField(max_length=17, choices=PRODUCT_TYPES, null=True) name = models.CharField(max_length=325, null=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="children") class Timestamp: product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) product_type = models.CharField(max_length=35, choices=ADTYPES, blank=True, null=True) owner = models.ForeignKey(AmazonProfile, null=True, blank=True, on_delete=models.CASCADE) clicks = models.IntegerField(default=0) spend = models.IntegerField(default=0) sales = models.IntegerField(default=0) acos = models.FloatField(default=0) cost = models.FloatField(default=0) cpc = models.FloatField(default=0) orders = models.IntegerField(default=0) ctr = models.FloatField(default=0) impressions = models.IntegerField(default=0) conversion_rate = models.FloatField(default=0) date = models.CharField(null=True, max_length=25) I'm using the data for a dashboard, where users are supposed to be able to view their products & the performance of the products for a certain daterange inside a table. For example, a user might have 100 products inside the table and would like to view all data from the past 2 weeks. For this scenario, I'll describe the … -
How can I make page for 403 and 404 errors in Django?
In other website like github I saw when the path is not found it returns error template for example look at github.com/ddfushdvbjkvuirfjvscvuiihkbfdsuhkb this page does not exist. Also I want to make for deleted path's that returns 403 error. Please send me some docs I didnt find out :| -
How to hide field from admin change page but keep it in admin add page in Django
I have a data model in which some fields can only be set initially per each instance of the class, and once set, they should never change. The only way that can be allowed to change such an object should be by deleting it and creating a new one. Pseudo code: from django.db import models from django.core.exceptions import ValidationError class NetworkConnection(models.Model): description = models.CharField(max_length=1000) config = models.CharField(max_length=1000) connection_info = models.CharField(max_length=5000) def clean(self): from .methods import establish_connection self.connection_info = establish_connection(self.config) if not self.connection_info: raise ValidationError('Unable to connect') def delete(self): from .methods import close_connection close_connection(self.config) super(NetworkConnection, self).delete() As in the above code, the user should initially input both the config and the description fields. Then Django verifies the config and establishes some sort of network connection based on such configurations and saves its information to another field called connection_info. Now since each object of this class represents something that cannot be edited once created, I need to hind the config field from the admin page that edits the object, leaving only the description field; However, the config field still needs to be there when adding a new connection. How do I do this? The following is an example of my last admin.py … -
How to save a MultipleChoiceField in Django
I was wondering how can I save a MultipleChoiceField to Django's database (in form submission)? models.py class Model1(models.Model): field = models.CharField(max_length=200, null=False, blank=False, default='') forms.py OPTIONS = ( ('Option 1', 'Option 1'), ('Option 2', 'Option 2'), ('Option 3', 'Option 3'), ) class Model1Form(forms.ModelForm): field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS) class Meta: model = Model1 fields = '__all__' If you need additional information let me know! Thanks for helping out. -
How to integrate paypal in React Js with server side ( Django REST ) payment execution?
I am trying to integrate paypal in my application. My application has to be built using React JS and backend should be in Django. I have done the Client Side Integration using one npm package which is https://www.npmjs.com/package/react-paypal-express-checkout This is my code in React JS import React from "react"; import ReactDOM from "react-dom"; import PaypalExpressBtn from "react-paypal-express-checkout"; import "./styles.css"; function App() { const client = { sandbox: "AXMUBOcaszqCzfEOC-r--Rn7rMVoEbH9c6XbmyKb04nURqcLhpFxWwwnaUytaMR9UTaE2vwLfi5tqKbT", production: "" }; return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <PaypalExpressBtn client={client} currency={"USD"} total={500} onSuccess={(p) => console.log(p)} /> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); I am getting the following response { paid: true cancelled: false payerID: "TLCF8J8F3CZUY" paymentID: "PAYID-MAADRGI6U311288V5285313C" paymentToken: "EC-32J40105H07711055" returnUrl: "https://www.paypal.com/checkoutnow/error?paymentId=PAYID-MAADRGI6U311288V5285313C&token=EC-32J40105H07711055&PayerID=TLCF8J8F3CZUY" address: Object email: "sb-ueclm4695520@personal.example.com" } After the payment, also my sandbox account balance is been deducted. So this is working fine. But I want to do the payment execution securely in server side. How do i achieve it in Django? I have read the docs, they mentioned use SDK. So I have looked into the python sdk which is https://github.com/paypal/Checkout-Python-SDK from paypalcheckoutsdk.orders import OrdersCaptureRequest # Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders # Replace APPROVED-ORDER-ID with the actual … -
Error when converting pandas to postgers in django app
Goal: adding data from a fetched json file into a postgres database. Error when running the script: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. After fetching the data from a link (json), i convert and edit it with pandas. Once done, the goal is to add it to the databas, but i get the mentioned error. The code snippet i use is taken from this answer. [https://stackoverflow.com/questions/37688054/saving-a-pandas-dataframe-to-a-django-model] second_pipeline.py (gets the error) import pandas as pd import requests fox_url = "https://saurav.tech/NewsAPI/everything/fox-news.json" fox_news = requests.get(fox_url).json() df = pd.json_normalize(fox_news) fox_articles = pd.json_normalize(df["articles"].loc[0]) del fox_articles['source.id'] fox_articles["date_publised"] = pd.to_datetime(fox_articles['publishedAt']) del fox_articles['publishedAt'] import os from django.conf import settings import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') settings.configure(DEBUG=True) django.setup() from sqlalchemy import create_engine from models import Article user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( # user=user, # password=password, # database_name=database_name, article_author = fox_articles["author"], article_date_publised = fox_articles["date_publised"], article_title = fox_articles["title"], article_description = fox_articles["description"], article_url = fox_articles["url"], article_urlToImage = fox_articles["urlToImage"], article_content = fox_articles["content"], article_network = fox_articles["source.name"], ) engine = create_engine(database_url, echo=False) fox_articles.to_sql(Article, con=engine) models.py class Article(models.Model): article_author = models.CharField(blank=True, max_length=1000) article_date_publised = models.CharField(blank=True, max_length=500) article_title = models.TextField(blank=True) article_description = models.TextField(blank=True) article_url = models.TextField(blank=True) article_urlToImage = models.TextField(blank=True) article_content = models.TextField(blank=True) … -
match two models field (django)
I have a question answer quiz. I want each form to be responsible for each query when I publish the forms in html. For example I have it now current result. I have to choose the question manually. I want it to happen automatically, i.e. no matter how many questions I have so many forms for each question. what i want -> the end result. I do not understand what I have to change, view or formset should I use, please if you can help me change the code. models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question import random def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, "e":e}) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" … -
Django - Display ValidationError using Ajax
I'm trying to display ValidationErrors using Ajax. I've read many posts about this and tried many things but can't get it to work. forms.py class ContactForm(forms.ModelForm): name = forms.RegexField( regex=r'^[a-zA-Z]+$', max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}), error_messages={'invalid': _("Wrong First Name, use only letters")}) Error details are stored in data['error'] also having item is_valid. I inspected response data structure in console logging data in Ajax error. According to the structure access values and assign to elements. script - (Ajax error) error: function(data, xhr, errmsg, err){ console.log("data") console.log(data.responseJSON) //console.log(data.responseJSON.errors.name[0]) $('.error').html(data['error']) }, In views.py form.errors passed in JsonResponse() as a dictionary. def contact(request): form = ContactForm(request.POST) data = {} if request.is_ajax(): if form.is_valid(): form.save() return JsonResponse(data) else: data = { 'error': form.errors, 'is_valid': False } return JsonResponse(data, status=400) else: context = { 'form': form, } return render(request, 'pages/contact.html', context) In my script when using console.log('data.responseJSON') i see: In the above image I can access the error message for the field 'name' as data.responseJSON.error.name[0] In my eyes everything seems to be ok however i cannot display message in user. I'm using crispy forms in the template contact.html <div class="col-lg-6"> <div class="form-box"> <h3>Write A Comment</h3> <form class="form" id="contact" method="POST" action="" autocomplete="off"> {% csrf_token %} <div class="messages"></div> <div class="input__wrap … -
In django, when user registered using CustomForm tries to login using Oauth
My Django app has an option for login/register using CustomForm (inherited from the UserCreationForm) as well as Outh. Now the problem is if a user has already signed up using the CustomForm and if the next time he tries to log in using google Oauth then instead of logging in, google Oauth is redirecting to some other signup form which looks like: But as the user is already registered, if he enters the same username/email here then it displays says username taken. So how can I resolve this issue? I mean I want the user to be able to use both custom form as well as Oauth, how can I implement that? My register function in views.py: def register(request): if request.method == 'POST': form = CustomForm(request.POST or None) if form.is_valid(): form.save() return redirect('login') else: return redirect('register') else: return render(request, 'accounts/register.html') forms.py looks something like this: class CustomForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ("username", "email") -
In django, when user registered using CustomForm tries to login using Oauth
My Django app has an option for login/register using CustomForm (inherited from the UserCreationForm) as well as Outh. Now the problem is if a user has already signed up using the CustomForm and if the next time he tries to log in using google Oauth then instead of logging in, google Oauth is redirecting to some other signup form which looks like: But as the user is already registered, if he enters the same username/email here then it displays says username taken. So how can I resolve this issue? I mean I want the user to be able to use both custom form as well as Oauth, how can I implement that? My register function in views.py: def register(request): if request.method == 'POST': form = CustomForm(request.POST or None) if form.is_valid(): form.save() return redirect('login') else: return redirect('register') else: return render(request, 'accounts/register.html') forms.py looks something like this: class CustomForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ("username", "email") -
django: don't register ModelAdmin (exclude module-level code) when running makemigrations / migrate
I have made multiple changes to an existing django model (added new foreign key relation, etc). Before creating and applying these changes with manage.py makemigrations / migrate, I adapted the corresponding admin module's ModelAdmin for that app to reflect these unapplied changes. Running makemigrations now fails with "ProgrammingError: {new_field} does not exist". I figure this happens because when makemigrations runs system checks, the ModelAdmins in admin.py are registered (executing queries on non-existant models that I try to create with the migrations). Question: Is there any straight-forward way to exclude the ModelAdmins from being registered when running manage.py makemigrations / migrate without disabling system checks in total (see Django migration - disabel system checks)? I can solve the problem by deleting my admin.py modules when running makemigrations / migrate and recreating them afterwards. There is really no need to check the admin modules when migrating, but I guess this will happen when registering ModelAdmins on the module-level of admin.py (as in the examples in the django admin documentation). I do not use a custom AdminSite. On more general terms: is there any straight-forward way to exclude specific top-level module code from being executed when running a specific manage.py command like makemigrations … -
How to delete a record after a certain time of it's creation in Django?
I am building an application that has a 'Story Feature' which is quite similar to Instagram's story feature, So I want to delete a story after 24 hours of its creation. So if a story was created on 12:00 PM 1 January 2021, I want to delete it automatically at 12:00 PM 2 January, 2021. I am using django3.1 My Model: class Story(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) text = models.CharField(max_length=200) image = models.ImageField(blank=True, null=True) video = models.FielField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) expiration_time = models.DateTimeField() I want to delete every record after their particular expiration time. [Expiration time is set in a post_save function ] -
how to create a dictionary from a merged django queryset
Django newbie here trying create a dictionary looking like this {<Course: Phonics>: [40,72,76], <Course: Social Studies>: [48,72,60]} from a merged queryset bla = result1 | result2 | result3 where result1 = Result.objects.filter(pupil__exact = pk,session = session1) result2 = Result.objects.filter(pupil__exact = pk,session = session2) result3 = Result.objects.filter(pupil__exact = pk,session = session3) Here is snippet Result & Session class in models.py class Result(models.Model): pupil = models.ForeignKey('Student', on_delete = models.CASCADE) subject_course = models.ForeignKey('Course', on_delete = models.CASCADE) subject_score = models.IntegerField(default=0) session = models.ForeignKey('Session', on_delete = models.CASCADE) def __str__(self): return '{}, {} result'.format(self.pupil.surname,self.session) class Session(models.Model): sessionedu = models.CharField(choices = SESSION ,max_length=20) term = models.CharField(max_length=15, choices=TERM) resumption = models.DateField(blank=True,default= one_month_away) #active = models.BooleanField(default=False) class Meta: verbose_name = "Session" verbose_name_plural = "Sessions" def __str__(self): return '{} {}'.format(self.sessionedu, self.term) `` thanks -
Django Migrate With Specific Database And Models
I was tried to create a multiple database and i did it. i wrote the code on setting.py like this : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'baseDB', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '1234', }, 'android': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'androidDB', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '1234', }, 'ios': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'iosDB', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '1234', } } And i was already create a two models.py like : class AndroidModel(models.Model): name = models.CharField(default=False) version = models.CharField() class Meta: app_label = 'android_label' class IosModel(models.Model): name = models.CharField(default=False) version = models.CharField() class Meta: app_label = 'ios_label' And than i created a routes with the name file is dbrouters and the class is MyDBRouter, and the code is like : from api.models import AndroidModel, IosModel class MyDBRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'android_label': return 'android' if UserJembatani._meta.app_label == 'ios': return 'ios' else: return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'android_label': return 'android' if UserJembatani._meta.app_label == 'ios_label': return 'ios' else: return 'default' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'android_label' or \ obj2._meta.app_label == 'android_label': return True if obj1._meta.app_label == 'ios_label' or \ … -
How to store an image without using django forms
All the solutions that I see are done using django forms, I want to avoid that as I have made a bigger form with image field plus some other input (and added styling and Js check for validation). So how to retrieve a file from a form and store it in django. html form: <form action="{% url 'newcomplaint' %}" class='newc' method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="fileToUpload">Add an image(optional)</label> <input type="file" name="fileToUpload" id="fileToUpload"> </div> <button type="submit" class="btn btn-dark bb">Post New Complaint</button> </form> views.py: Here I am getting "MultiValueDictKeyError at /hood/new" def newcomplaint(request): if request.method == "POST": # I dont know how to store a image here image = request.FILES['fileToupload'] #print(image) return HttpResponse('works') model.py from django.db import models from django.core.exceptions import ValidationError from django.contrib.auth.models import User class Complain(models.Model): image = models.ImageField(upload_to='images/', blank=True) -
Notify user if data has changed since page loaded
I have 3 users that can view and commit changes to a database. Let's take for example an app called "personel". These 3 users can view the list of personel, edit personel data, and remove personel entries, from custom views. I am trying to solve this scenario: User A goes to /view_personel_list/ User B goes to /edit_personel/3/, and saves changes. User A is still viewing the non-updated personel list. I know this could be solved using AJAX, but I do not want to refresh. I am looking for a way to notify User A that the database has been changed. -
How can I draw a plot for a model in a Django-admin change list template with all days of the year, including those without data in my model?
I am not very skilled for programming but our little research team has no mean to pay somebody for this project. I have a simple model that I want to display by creation date in django admin class Project(models.Model): date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.DO_NOTHING) class Meta: ordering = ['-date'] # def get_identification_day(self): dt=self.date y=(dt.strftime("%b, %d, %Y")) z=y[0:5].replace(",",".")+y[5:] if z[5]=='0': z=z[0:5]+z[6:] return z I have a change-list template declared in admin.py, working fine to do graphs by user.username It can do a graph by date also but monday 11 january 2021 follows friday 8 2021 on the graph. How is it possible to insert saturday and sunday (no Project with the dates) with zero values? I have created a list of all the dates since 1/1/2020 in js and a list "predata1" of same length filled by "1" This can be seen on the graph So I prepared a list "predata0" filled by zeros I wanted to replace the "0" with the total of projects when they exist in my model. And there I am stuck. My function is not good. On console this work fine so I guess I couldn't figure out how to rewrite it … -
Django Admin form Taggit Library through model
I am using Taggit library. I need to use some additional fields like featured_tag and hence I created a through model. Now, I need to modify Django Admin for the same. So, on front end, I have used VueJs to create assign which tag is featured, but, how we would handle in BackEnd form while saving. As I understand, we need to call save_m2m() function, but how we will pass these addtional attributes. Any thoughts ? -
Filter itens without direct relation in Django Rest Framework API
I'm trying to implement some filters in my API endpoint for a property management company. I want to filter reservations in a range of check-in dates and properties. I have three models called Reservation, Listing and Property. The reservation has a Foreign Key to Listing, which has a Foreign Key to Property. I want to filter a reservation with a specific Property, but they don't have a direct relation, the Listing is in the middle. models.py from django.db import models from .helpers import support_models class Reservation(models.Model): code = models.CharField(max_length=50) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) check_in_date = models.DateField(blank=True, null=True) check_out_date = models.DateField(blank=True, null=True) def __str__(self): return self.code class Listing(models.Model): code = models.CharField(max_length=50) property = models.ForeignKey(Property, on_delete=models.CASCADE) def __str__(self): return self.code class Property(support_models.Address): code = models.CharField(max_length=50) location = models.ForeignKey(Location, on_delete=models.CASCADE) def __str__(self): return self.code I have many more itens in the models, but I'm showing you only what I need. My views are looking like this at the moment: views.py from rest_framework import viewsets, permissions, filters from sapron import models, serializers class ReservationViewSet(viewsets.ModelViewSet): queryset = models.Reservation.objects.all() serializer_class = serializers.ReservationSerializer filterset_fields = { 'check_in_date': ['gte', 'lte'], 'listing': ['exact'], } The date range filter is working fine, but I want 'property' instead of 'listing' in … -
Django + sorl_thumbnail no thumbnails shown
i wanna use sorl_thumbnail to show thumbnails from my images uploaded by users. My key-value database is Redis. I've set things up but no images are shown, onlu broken links. Apparantly the path to the thumbnails is not correct?! Here is my setup: First i have installed Redis and pillow. After that i made following changes to the django settings.py file: #INSTALLED_APPS = [ ................. 'sorl.thumbnail', ] #sorl_thumbnail setup with a redis local key-value server THUMBNAIL_DEBUG = True THUMBNAIL_BACKEND = 'sorl.thumbnail.base.ThumbnailBackend' THUMBNAIL_KVSTORE = 'sorl.thumbnail.kvstores.redis_kvstore.KVStore' THUMBNAIL_REDIS_DB = 0 THUMBNAIL_REDIS_PASSWORD = '' THUMBNAIL_REDIS_HOST = 'localhost' THUMBNAIL_REDIS_PORT = 6379 THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.pil_engine.Engine' # Setting up cache for sorl_thumbnail package. CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1/6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient' }, 'KEY_PREFIX': 'intra_' } } In my HTML-template i have the following for showing the thumbnails: {% load thumbnail %} <td> {% thumbnail stripboek.kaft.url "100x100" crop="center" as im %} <img src="{{ im.url }}"/> <!-- <img src="{{stripboek.kaft.url }}" width="100px" /> --> {% endthumbnail %} </td> When i inspect the thumbnail element on my website i see the following: http://192.168.178.24/media/cache/40/2a/402af0436a0c51c70391884f705938b1.jpg /media/ is the path from my MEDIA_URL in Django. I think the problem is that with the installation of Redis no Django Database/Model … -
Multiple filter parameters in the foreign key relation with reduce function
I have a model ToBePosted that has a foreign key to Campaign and Size. class Campaign(models.Model): name = models.CharField(max_length=100) class Size(models.Model): name = models.CharField(max_length=5) class ToBePosted(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='to_be_posted_posters') size = models.ForeignKey(Size, on_delete=models.CASCADE, related_name='to_be_posted_posters') My queryset in views.py: def get_to_be_posted_queryset_with_filter(self, request): filter_params = ToBePostedParameterConverter(request.GET) queryset = ToBePosted.objects.all() return queryset.filter(filter_params.get_filter()) And helpers.py where ToBePostedParameterConverter is located class ParameterConverter: # Convert url query params to queryset filter params query_patterns = { "campaign": 'to_be_posted__campaign__name', "size": 'reference__size__name', } def __init__(self, query_dict): self._query_dict = query_dict self._filter_params = [] self._convert() def _convert(self): for key in self._query_dict: for search_key in self._query_dict.getlist(key): if query_param := self.query_patterns.get(key): self._filter_params.append(Q(**{query_param: search_key})) def get_filter(self): if self._filter_params: return reduce(operator.or_, self._filter_params) return Q() class ToBePostedParameterConverter(ParameterConverter): query_patterns = { "campaign": 'campaign__name', "size": 'size__name', } def get_filter(self): if self._filter_params: return reduce(operator.or_, self._filter_params) return Q() The question is: when I try to get an object Tobeposted with a size of 666 but only associated with campaigns Acamp and Bcamp I get all objects that have a size of 666 regardless of the specified campaigns in the url EXAMPLE OF REQUEST URL WITH PARAMETERS: http://localhost:8000/api/v2/posters/get_lookups/?campaign=Acamp&campaign=Bcamp&size=666 How I can change the code to get only posters that are related to specified campaigns in the url paramters? I … -
Sort added elements inside Django autocomplete_fields
I have Django application and admin page. Inside admin page, I have one model that has autocomplete_fields. I can sort results but, I can't sort the results. It always sort by pk and not by value that I set. @admin.register(Assortment) class AssortmentAdmin(ImportExportActionModelAdmin): list_display = ['name'] exclude = ['customers'] # inlines = [ProductAssortmentInLine] autocomplete_fields = ['products'] @admin.register(Product) class ProductAdmin(ImportExportActionModelAdmin): exclude = ['associated_products', 'subsidiary_excluded', 'customers'] list_display = ['product_ref', 'name', 'price', 'group', 'retail_unit', 'active'] list_editable = ['price', 'retail_unit', 'active'] list_filter = ['group'] search_fields = ['product_ref', 'name', 'group'] resource_class = ProductResource # inlines = [CustomerInLine] def get_queryset(self, request): qs = super(ProductAdmin, self).get_queryset(request) qs = qs.order_by(Cast(F('product_ref'), IntegerField())) return qs How to solve this? -
Heroku-deployed Django application does not appear in mobile browser
Situation: I've bought a specific domain, let's say 'example.ch' for my Django application which is deployed in Heroku. I also created an automated SSL certificate on Heroku (ACM). This certificate is valid for the WWW-subdomain, i.e. ACM Status says 'OK'. It fails for the non-WWW root domain, so I deleted the root domain entry on Heroku. I use 'swizzonic.ch' as webhostserver. Question: The redirection from 'example.ch' to 'https://www.example.ch' does not work on my mobile device, while everything is fine when I use my Mac and all common browsers. I found an older (unanswered) similar post to this topic (Django app on heroku: content wont appear in mobile browser). I don't know where to start, since seemingly nobody else faces this issue... Many thanks for your help.