Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write a text or binary file to a Django response?
I am trying to hook up Django and React. See here or here. This is serving up some Django URLs, but then passing the rest on to React. I want to serve up not only React's index.html, but also any of its files from the "public" directory. There is HTML, JSON, could be images or icon files, etc. A mix of text files and binary files. Here is some code to serve up a binary file (like an image) with FileResponse: from django.http import FileResponse def view_func(request): # .. find a static file to serve content = open(some_file_path, 'rb') return FileResponse(content) Note that it opens content as a binary file (rb). But if I am serving index.html, presumably that is not binary. For example, it might be UTF-8. (I think that's the default if I open with r, no binary.) Is there an easy way to serve up a file in Django whether it is text or binary? P.S. I feel like there should be a way to hook up Django's static file serving, but after a few hours of fiddling, it is harder than it looks. This is not going to get super-high traffic, so I'm fine with this. -
hi can help me in this issu wth database whith django
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' how can resolv this issue .im alrady install psycopg2 in my vertualenv -
Django-CMS add content to the first page
How to add contents to the first Page? After installing Django-CMS according to the documentation, starting the docker project, and logged in to Django-CMS, the user is presented with the screen shown below. In the upper right corner there is a button New Page. Clicking on New Page After clicking on New Page the user is presented with the form for a New page, as shown below, I added some text. Saving the page and enter the Page Tree After the form is saved, then Page Tree is shown. Clicking the circle and select Publish, and the on the eye, the user is presented with a blank page with the page title correct. My question is: How do I add content to this page? Template used For this basic example the minimal template is used, I know this because when I add some place holder text to the template it comes up on the page. {% load cms_tags sekizai_tags %} <html> <head> <title>{% page_attribute "page_title" %}</title> {% render_block "css" %} </head> <body> {% cms_toolbar %} {% placeholder "content" %} {% render_block "js" %} <p>Writing this text to find what template is used!</p> </body> </html> The question is, how do I … -
Django custom template tag sort long list of 'elif'
I have a Django custom template tag that changes the color of a font depending on the value that is put in. Everything works fine but I was wondering if there was a cleaner way of writing this instead of making all these elif statements. Shown isn't even half of the teams, there are still 3 other leagues of teams that would be included in that tag. Thanks so much for any help you can offer. @register.filter(name='teamColor') def teamColor(team): if team == "Celtics" or team == "Jazz": return "green" elif (team == "Hawks" or team == "Bulls" or team == "Rockets" or team == "Pistons" or team == "Clippers" or team == "Heat" or team == "Trail Blazers" or team == "Raptors"): return "red" elif team == "Nets": return "grey" elif (team == "Hornets" or team == "Lakers" or team == "Suns" or team == "Kings"): return "purple" elif team == "Cavaliers": return "#b11226" elif team == "Mavericks" or team == "Grizzlies" or team == "76ers": return "blue" elif team == "Nuggets" or team == "Pacers": return "yellow" elif (team == "Warriors" or team == "Timberwolves" or team == "Thunder" or team == "Knicks"): return "#1D428A" elif team == "Bucks": … -
How can I fix this sh*t?
What am I doing wrong? Problem: The if statement is always ignored. The else statement is always returned. Desired result: If test == 'True' (I want to match against the 'Digits' param) then proceed to twilio_view3, otherwise redirect to twilio_view1. example.py import re def test(): if re.match(r'99\d{10}') return True else: return False views.py from example import test def twilio_view2(request: HttpRequest) -> HttpResponse: digits = request.POST.get('Digits') response = VoiceResponse() if test == 'True': gather = Gather(input='dtmf', action='/twilio_view3', method='POST') gather.say('Blah blah blah.') response.append(gather) return HttpResponse(str(response), content_type='text/xml') else: response.say('Something other than Blah blah blah.') response.redirect("/twilio_view1") return HttpResponse(str(response), content_type='text/xml') TwiML response: <Response> <Say>Something other than Blah blah blah.</Say> <Redirect>/twilio_view1</Redirect> </Response> -
Django - one field to many columns in db table
I would like to create a custom field with choices that store data in n (number of choices) db columns. It's should looks like dummy vector. Example: Choose type of product This product in db table id kind_hygine kind_road_equipment kind_relax kind_food 1 0 0 1 0 It is a legacy db, so I can not change db tables layout. How can I achieve it? -
Can i print the instance of has_object_permission?
I'm trying to create REST API with django-rest-framework. My question is can I print the instance of has_object_permission method so I can see what is going on in that part. I'm trying that only the owner of an object can update and delete the object but right now anyone can delete or update anybody object. Please tell if there is other way to do besides permissions. Can we do all these with checks in serializer. If yes then please guide me that too with example. I shall be very thankful. class ObjectOwnerPermission(BasePermission): message = "This object is expired." # custom error message def has_object_permission(self, request, view, obj): if request.user.is_authenticated: return True return False if obj.author == request.user: return True return False class RetrieveUpdateProjectAPIView(generics.RetrieveUpdateAPIView,ObjectOwnerPermission): """This endpoint allows for updating a specific Project by passing in the id of the Project to update/Retrieve""" permissions_classes = [ObjectOwnerPermission] queryset = Project.objects.all() serializer_class = serializers.ProjectSerializer class DeleteProjectAPIView(generics.DestroyAPIView,ObjectOwnerPermission): """This endpoint allows for deletion of a specific Project from the database""" permissions_classes = [ObjectOwnerPermission] queryset = Project.objects.all() serializer_class = serializers.ProjectSerializer -
Question regarding Django - IIS - Postgres
I've recently built my first real web app for 'work' using Django. I'm using Postgres for my backend database. I'm also hosting my app and database on the same Windows 2019 server. IIS is the tool that I'm using to host my web app. Essentially what my issue is when I have my website live in production, my export count in the csv doesn't match my filtered records count in my search. It works sometimes but usually when the row count is smaller. The issue usually happens if the row count is in the tens of thousands (shown in screenshot). My hunch is that it's due to some network setting somewhere in IIS but i could be wrong. Everything works perfectly when I'm just running on localhost. I'm not too familiar on what database or IIS settings should be set to allow for optimal performance. I have 16 GB of ram on my server and a 8 core processor so i don't think that's the issue but i could be wrong. My database is like 8 million some rows so there is definitely a lot of data to go through. Below is code of my export_to_csv view as well. I'm … -
Django: Unique_Together
My Django form allows teachers to choose which period they would like to request a student, "Academic Period 1" or "Academic Period 2" or "Both Periods". I currently have a unique_together option working perfectly for "Academic Period 1" and "Academic Period 2" where a duplicate request is not allowed, but how do I make the option named "Both Periods" block future submissions requesting periods "Academic Period 1" and "Academic Period 2"? See my code below. In the model, these choices are options for the field "Period". MODEL class RequestAStudent(models.Model): PERIODS=( ('Academic Network 1', 'Academic Networking 1'), ('Academic Network 2', 'Academic Networking 2'), ('Both Periods', 'Both Periods'), ) MARK=( ('None', 'None'), ('Present', 'Present'), ('Tardy', 'Tardy'), ('X', 'X'), ('Absent', 'Absent'), ) student = models.ForeignKey(Student, on_delete= models.CASCADE) date_created = models.DateField(auto_now_add=True, null=True) Requesting_Teacher = models.ForeignKey(AdvisoryTeacher, on_delete= models.CASCADE) Period = models.CharField(max_length=18, null=True, choices = PERIODS) teacher = models.ForeignKey(Teacher, verbose_name='Advisory Teacher',default="None", on_delete= models.CASCADE) date_requested = models.CharField(max_length=200, verbose_name='Date for Student Request (Use format MMDDYY)', default="2021-11-04",null=True) attendance = models.CharField(verbose_name='UPDATE ATTENDANCE HERE!',max_length=18, default="None",choices = MARK) #null=True, blank=True, owner = models.IntegerField("Request Owner", blank=False, default=1) def __str__(self): return "" + str(self.student) + ", Teacher: " + str(self.owner) class Meta: unique_together = ["student", "Period", "date_requested"] -
What is the exact name of the table in database in django admin?
Which one among the following is the name that belongs to my database table? Tbl_categories tbl_categorie tbl_categories TBL_Categorie This is my class in models.py: class tbl_Categorie(models.Model): category_id = models.AutoField(primary_key=True) category_name =models.CharField(max_length=14) def __str__(self): return self.category_name This is the screenshot from my django admin: -
Python - Single thread executor already being used, would deadlock
I'm trying to create an async view that accesses the DB and returns data with two separate queries. @sync_to_async def get_tweets(request): return (Tweet.objects. annotate(full_text=Concat(F('title'), F('body'))). order_by(F('date').desc(nulls_last=True)). values('full_text', 'title', 'body', 'date', tweet_id=F('uuid'), sent_to_app=F('sent'))) @sync_to_async def get_users(request): return User.objects.filter(is_active=True).values('username', 'email', full_name=Concat(F('first_name'), F('last_name'))) @sync_to_async @csrf_exempt @async_to_sync async def async_view(request): funcs = [get_tweets, get_users] tasks = [asyncio.ensure_future(func(request)) for func in funcs] data = await asyncio.wait(tasks, return_when=FIRST_EXCEPTION) return JsonResponse({'data': data}, safe=False) when debugging the code, before the response, I get an exception for every task in tasks: RuntimeError('Single thread executor already being used, would deadlock') so I can't collect the results, I don't understand why it's happening except it originated in asgiref. I downgraded the asgiref version like said here: django RuntimeError at /admin/users/user/1/change/, Single thread executor already being used, would deadlock but it didn't help. I don't understand if it comes from something in the way I set up the async code or from exception that's being raised in one of the functions and is hidden in the traceback. -
Django adding an user as a model
im trying to make a "seller" in my "Products" model. The seller should be the user who made the product (the user who is logged in currently). How can i take the current user and use it like a foreign key but without choices? Products model: from django.db import models import uuid from user.models import User class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) name = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to='images', blank=True, null=True) price = models.FloatField(max_length=255, blank=True, null=True) description = models.TextField(max_length=255, blank=True, null=True) category = models.ManyToManyField(Category, blank=True) seller = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name User model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, Group, Permission import uuid from user.managers import UserManager class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) image = models.ImageField(upload_to='images', blank=True, null=True) date_of_birth = models.DateField(null=True, blank=True) about = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) groups = models.ManyToManyField(Group, blank=True) permissions = models.ManyToManyField(Permission, blank=True) USERNAME_FIELD = 'email' … -
Django, Nginx, uWSGI sock - Internal Server Error
I created the Django project and the .ini file for uWSGI (/home/luca/uwsgi/siti/project.ini): [uwsgi] home = /home/luca/progetto/venv chdir = /home/luca/progetto/progetto wsgi-file = /home/luca/progetto/progetto/progetto/wsgi.py socket = /home/luca/uwsgi/progetto.sock vacuum = true chown-socket = luca:www-data chmod-socket = 660 If I issue the command: uwsgi /home/luca/uwsgi/siti/project.ini It work fine. To make uWSGI start automatically on boot I used systemd (/etc/systemd/system/uwsgi.service): [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown luca:www-data /run/uwsgi' ExecStart=/usr/local/bin/uwsgi --emperor /home/luca/uwsgi/siti Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target I created the configuration file for my website (/etc/nginx/sites-available/progetto): server { listen 8000; server_name [IPdelVPS]; location / { include uwsgi_params; uwsgi_pass unix:/home/luca/uwsgi/progetto.sock; } } and sudo ln -s /etc/nginx/sites-available/progetto /etc/nginx/sites-enabled I use this configuration for other websites and it works, but in this case it responds: Internal Server Error Thanks in advance to anyone who can help me. -
Is there any point in defining models.Index or models.UniqueConstraint in class Meta of a Django Model, if managed = False
I'm trying to configure Django models with a legacy database. After running inspectdb I've started going through the recommended basic clean up steps (ie rearrange models' order, make sure each model has a primary key, foreign keys 'on delete', etc.). I've decided to keep managed = False in class Meta in each model to avoid migration issues with legacy app that it may cause. In addition to the basic cleanup steps I'm wondering if it's recommended or necessary at all to add models.Index and models.UniqueConstraints to class Meta for my tables that already have these indexes and constraints defined in the database. Are these specific (class Meta) settings only needed for migrations or does Django use them to enforce constraints and for indexing at the app level in addition to what my database server (mysql 5.7) already is designed to do? -
request.session['pk'] = user.pk AttributeError: 'QuerySet' object has no attribute 'pk'
I need to get a user for account_verify to compare the input verification code with the correct login code, but I got this error also I want to show user phone number in account verify I used context for that but I think that is wrong view def account_register(request): if request.user.is_authenticated: return redirect("store:home") if request.method == "POST": registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): username = registerForm.cleaned_data["user_name"] phone_number = registerForm.cleaned_data["phone_number"] password = registerForm.cleaned_data["password"] user = User.object.filter(phone_number=phone_number) if not user.exists(): new_user = User(phone_number=phone_number) new_user.username = username new_user.phone_number = phone_number new_user.set_password(password) new_user.is_active = False new_user.save() else: return HttpResponse("this phone number already taken", status=400) request.session['pk'] = user.pk return redirect("account:account_verify") else: registerForm = RegistrationForm() return render(request, "account/authentication.html", {"form": registerForm}) def account_verify(request): form = CodeForm(request.POST or None) print(form) pk = request.session.get('pk') print(pk) if pk: user = User.object.get(pk=pk) code = user.code user_phone_number = user.phone_number code_user = f"{user.code}" if not request.POST: print(code_user) send_sms(code_user, user.phone_number) if form.is_valid(): num = form.cleaned_data.get('number') if str(code) == num: user.is_active = True user.save() login(request, user) return redirect("store:home") else: return redirect("account:register") context = { 'form': form, 'user_phone_number': user_phone_number } return render(request, "account/verify.html", context) error File "C:\Users\_rickoutis_\djx\Rex_acs32\account\views.py", line 49, in account_register request.session['pk'] = user.pk AttributeError: 'QuerySet' object has no attribute 'pk' -
Hosting Django web application on IIS error
My organization has implemented a web application in Django, and we need to host it on a Windows system. We are using Django 3.2.8 and Python 3.8.8. The Django project is currently stored here: C:\inetpub\wwwroot\CED_HRAP <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="\*" verb="*" modules="FastCGIModule" scriptProcessor="c:\python38\python.exe|c:\python38\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <defaultDocument> <files> <clear /> <add value="Default.htm" /> <add value="Default.asp" /> <add value="index.htm" /> <add value="index.html" /> <add value="iisstart.htm" /> <add value="base.html" /> </files> </defaultDocument> <directoryBrowse enabled="false" /> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\CED_HRAP" /> <add key="WSGI_HANDLER" value="CED_HRAP.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="CED_HRAP.settings" /> </appSettings> </configuration> Our settings.py file is located at C:\inetpub\wwwroot\CED_HRAP\CED_HRAP\settings.py We are currently seeing this error message: HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory. Most likely causes: A default document is not configured for the requested URL, and directory browsing is not enabled on the server. How should we configure the default documents in the web.config file so that it links to Django's internal routing (urls.py)? Thanks. -
Python PasswordGenerator how can I code it
I'm trying to make a password generator on which you can select the length and if you want to have digits, characters or special characters inside. I'm struggeling with the code because I dont know how I can let the program choose 1 character out of every list for each length loop This is my code now alphabets = list(string.ascii_letters) digits = list(string.digits) special_characters = list("!@#$%^&*()") a_d = list(alphabets, digits) a_s = list(alphabets, special_characters) d_s = list(digits, special_characters) characters = list(string.ascii_letters + string.digits + "!@#$%^&*()") random.shuffle(characters) length = int(request.GET.get('length')) alphabets_b = bool(request.GET.get('alphabets')) digits_b = bool(request.GET.get('digits')) special_characters_b = bool(request.GET.get('special_characters')) password = [] for i in range(length): if alphabets_b == True: if digits_b == True: password.append(random.choice(a_d)) elif special_characters_b == True: password.append(random.choice(a_s)) elif digits_b == True: if special_characters_b == True: password.append(random.choice(d_s)) elif special_characters_b == True: if digits_b == True: password.append(random.choice(d_s)) I know this is really bad coding, how can I impove the code that it works. With this code the program says that I cant put 3 other lists in 1 list which makes sense but I cant think of a better way to seperate the characters. In my template I have this code: <form method="get" action="{% url 'home:passwordgenerator' %}"> <div class="fake_input"> <p … -
Django 403 error after installing a pip package with my static file server
So I have a Django website that needs to use both a pip package that introduces new static files to the admin and also a static file server from Linode (it's technically equivalent to AWS S3 buckets from everything that I've seen only cheaper for my use cases). This is the pip package, it basically adds a widget on the admin side of the Django website so that admin users can enter certain fields from a model in rich text as opposed to plain text. https://github.com/django-ckeditor/django-ckeditor And this is what I think is the relevant source code to my settings.py: import os from pathlib import Path import environ env = environ.Env() # reading .env file environ.Env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'ckeditor', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'products.apps.ProductsConfig', # ... ] CRISPY_TEMPLATE_PACK = 'bootstrap4' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, "live-static-files", "static-root") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] … -
Django migration revert: will the operations be reverted in reverse order?
I have three operations in my migration file. The first operation needs to happen first for the other 2 operations to run without issues. My understanding is that the operations will happen in order, but what if I wanna revert the migrations? Are the 3 operations reverted in reverse order, i.e., the RunPython will be reverted last? operations = [ migrations.RunPython(migrate_forward, reverse_code=migrate_backward), migrations.AlterField(...), migrations.AddField(...), ] -
How to do a join on more than two tables with Django?
I have been able to figure out how to join 2 tables with the below statement which worked perfectly for me, how I can't figure out how to do it with 3 tables. For 2 Tables trailers = TrailerLocation.objects.all().values('trailer__trailerNumber', 'trailer__trailerPlateNumber', 'trailer__trailerPlateState', 'trailer__trailerLeaseCompany', 'locationCity', 'locationState', 'locationCountry','statusCode', 'trailer__id') Now for the 3 models I want to do a join statement on, are below. Shipment class Shipment(models.Model): CARRIER_CHOICES = [ ('GW', 'Greatwide'), ('BL', 'Brian Williams'), ] dateTendered = models.DateField() loadNumber = models.CharField(max_length=50) masterBolNumber = models.CharField(max_length=50) carrier = models.CharField(max_length=100, blank=True, choices=CARRIER_CHOICES) destinationCity = models.CharField(max_length=70) destinationState = models.CharField(max_length=50) rateLineHaul = models.DecimalField(max_digits=15, decimal_places=2) rateFSC = models.DecimalField(max_digits=15, decimal_places=2) rateExtras = models.DecimalField(max_digits=15, decimal_places=2, default=0.00) rateTotal = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) loadDelivered = models.BooleanField(default=False) customCarrierRate = models.BooleanField(default=False) trailer = models.ForeignKey(Trailer, on_delete=models.PROTECT, blank=True, null=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) CarrierRate class CarrierRate(models.Model): shipment = models.OneToOneField(Shipment, on_delete=models.PROTECT, primary_key=True) rateLineHaulCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0.00) rateFSCCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0.00) rateExtrasCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0.00) rateTotalCarrier = models.DecimalField(max_digits=15, decimal_places=2, null=True, default=0.00) Shipment Margin class ShipmentMargin(models.Model): shipment = models.OneToOneField(Shipment, on_delete=models.PROTECT, primary_key=True) shipmentMargin = models.DecimalField(max_digits=15, decimal_places=2, null=True) shipmentMarginPercentage = models.DecimalField(max_digits=15, decimal_places=3, null=True) I am needing access to all fields in all 3 of the models so my eventual jinga code would … -
why wagtail TableBlock don't displed at admin panels
I have this code, want to make TableBlock at my admin panel, make migrations, migrate but it not displayed at admin panel from wagtail.contrib.table_block.blocks import TableBlock from wagtail.core.blocks import StreamBlock from wagtail.core.fields import StreamField class BaseStreamBlock(StreamBlock): table = TableBlock() class ArticlePage(Page): parent_page_types = ['home.HomePage'] subpage_types = [] content = StreamField(BaseStreamBlock(), verbose_name=_('Content'), blank=True) content_panels = [ MultiFieldPanel([ FieldPanel('title'), ]), MultiFieldPanel( [ StreamFieldPanel('content'), ] ), ] -
Detecting proxy or VPN user in Django
I want to be showing if the user request is using a VPN proxy or not in Django. I want if a user is using a VPN it shows this "Network Error: Not Connected" and if a user is not on VPN it shows this "Network Active: Connected". I have tried looking for the answers on the internet but nothing is working. Here is my views.py code: from django.shortcuts import render from django.views.generic.base import TemplateView from django.http import HttpResponse, JsonResponse import os import platform def check_ping(): hostname = "xyz.com" #hostname will be..Name under: "Connection-specific DNS Suffix" when you type "ipconfig" in cmd.. response = os.system("ping " + ("-n 1 " if platform.system().lower()=="windows" else "-c 1 ") + hostname) # and then check the response... if response == 0: pingstatus = "Network Active: Connected" else: pingstatus = "Network Error: Not Connected" return pingstatus response = check_ping() #print(response) # Create your views here. def home(request): return JsonResponse({'status':response}) -
Django and DRF-DataTables - Fixing Filtering Behavior
I am using DRF-DataTables to create a browsable table on the client side. The model I am working with contains some nullable boolean fields like so: models.py class Record(...): name = models.CharField(..., blank=True, null=True) is_active = models.BooleanField(blank=True, null=True) The table is rendered with serverside=true, however there is some unwanted behavior when trying to filter on the is_active column: filtering with "True" or "true" correctly retrieves only the records where is_active=True filtering with "False" (or any iteration where the 'F' is capitalized) correctly retrieves the records where is_active=False filtering with "false" incorrectly retrieves all records (but "fals" pulls the records where is_active=False) Furthermore - there does not seem to be anyway to filter for the records where is_active=None or name=None An idea solution would be to override the filtering logic by writing my own FilterSet, however when trying to follow the docs I run into this error: views.py class RecordGlobalFilter(...): name = GlobalCharFilter(lookup_expr='icontains') class Meta: model = Record fields = '__all__' class RecordViewSet(...): ... filter_backends = [DatatablesFilterBackend] filterset_class = RecordFilter The error: AttributeError: type object 'RecordFilter' has no attribute '_meta' -
How to require a specific field gets passed a value when saving Django model
I’m trying to track which user last updated an object: Class MyModel(models.Models): updater_id = models.ForeignKey(Users) …other fields… However, I can’t figure out how to require that updater_id be included each time my object is saved. First I tried overriding save: def save(self, updater_id, *args, **kwargs): self.updater_id = updater_id super(MyModel, self).save(*args, **kwargs) I realized however that this will break anything native to Django (i.e. MyModel.objects.create()) Next I tried grabbing it from kwargs: def save(self, *args, **kwargs): try: self.updater_id = kwargs[“update_fields”][“updater_id”] catch exception: raise Error super(MyModel, self).save(*args, **kwargs) updated_fields, however is only rarely used (i.e. default behavior for object.save() is to not use updated_fields) Then I tried adding a flag: Class MyModel(models.Models): updater_id = models.ForeignKey(Users) updater_updated_flag = models.BooleanField(default=True, editable=False) # default=True so first create/save works def update_updater_id(self, user_id): self.updater_id = user_id self.updater_updated_flag = True def save(self, *args, **kwargs): if self.updater_updated_flag: self.updater_updated_flag = False else: raise Exception("Must call update_updater_id() before calling save on this object") super(MyModel, self).save(*args, **kwargs) I figured I would ensure the updater_id is updated before save can be called. I realized, however, that this will break create_or_update(), unless I want to wrap it in a try catch and, if the object exists, get the object and call update_updater_id, which already … -
'Media' object has no attribute 'render_q'
screenshothow to fix "'Media' object has no attribute 'render_q'" appears when editing the model in the admin panel