Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytest fails on distinct with sqlite
I've a django system with drf where my views work fine, however, I'm unable to write a test for a view which has the following query: Object.objects.filter(...).order_by(...).distinct('comdate') . The problem is the distinct and it fails with the following error: #python -m pytest -k celler --pdb self = <django.db.backends.sqlite3.operations.DatabaseOperations object at 0x7f9dd7418a90>, fields = ['"tis_tislog"."comdate"'], params = [[]] def distinct_sql(self, fields, params): """ Return an SQL DISTINCT clause which removes duplicate rows from the result set. If any fields are given, only check the given fields for duplicates. """ if fields: > raise NotSupportedError('DISTINCT ON fields is not supported by this database backend') E django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database backend env/lib/python3.9/site-packages/django/db/backends/base/operations.py:176: NotSupportedError entering PDB PDB post_mortem (IO-capturing turned off) > /home/user/prj5/env/lib/python3.9/site-packages/django/db/backends/base/operations.py(176)distinct_sql() -> raise NotSupportedError('DISTINCT ON fields is not supported by this database backend') (Pdb) c PDB continue (IO-capturing resumed) [100%] short test summary info FAILED prj5/tests/test_tis_view.py::TestBillingUpdatedTransactionsView:: test_responds_ok_for_authorized_clients - django.db.utils.NotSupportedError: DISTINCT ON fields is not supported by this database backend . The test itself is pretty simple: class SomeTestingView: @pytest.mark.django_db def testTisView(self, client: Client): client.get(URL) Is there any way how I could make this test running? -
How to link hierarhical data into another model in Django?
Consider the following hierarchical data. It can be 3 to 4 levels deep. I understand I can use existing packages like django-mptt or django-treebeard to create a tree data structure. Mercedes Consumer ModelA ModelB SUV ModelC Luxury ModelD Nissan Consumer ModelA ModelB SUV ModelC Now let's say I have another model called Battery. A battery can be compatible with multiple models for different market segments by different car vendors. So what I want to do is assign this battery to one or more compatible models above. I'm not sure how to accomplish this linkage in Django. Would it just be a ManytoMany field to the hierarchical model? Some pseudo-code would help. class Battery(models.Model) name = Charfield(max_length=50) compatible_models = ???? I would also like to know how a query would be written. For example, I want to query all the battery that are compatible with ModelA by Mercedes, etc. -
Getting Fatal Python error running Django on Apache
I am trying to deploy my Django app through a Digital Ocean droplet server using Ubuntu 22.04 and MySQL. When I try to run the app through Apache, I get a "Forbidden Access" message. I checked the error log and see this error (I have removed my username from the directories): Permission denied: mod_wsgi (pid=983): Unable to stat Python home /home///mm_venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home///mm_venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home//mm_venv' sys.base_exec_prefix = '/home//mm_venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '//mm_venv' sys.exec_prefix = '//mm_venv' sys.path = [ '/home//mm_venv/lib/python310.zip', '/home//mm_venv/lib/python3.10', '/home//mm_venv/lib/python3.10/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' I have checked the etc/apache2/sites-available files, and this is what I have as the python path: WSGIDaemonProcess mommind_new python-home=/home//mommind_new/mm_venv python-path=/home//mommind_new These look correct to me, so I am really at a loss. Can someone please help me … -
In django how to remove a string value storing parent id from child table when the parent is deleted in M2M relationship?
I am storing some values from the parent in the child table as csv in a character field. Problem is when the parent is deleted, though the m2m relation is deleted, the value that was selected in the child table string remains as it is. How do I take care of it? Will I have to run a post_save method on the parent to access all the children's string and remove the value from there. There will be a lot of performance issues. eg: class Child1(models.Model): name = models.CharField(max_length=30, unique=True) class Teacher1(models.Model): name = models.CharField(max_length=30, unique=True) children = models.ManyToManyField( Child1, blank=True,null=True, related_name='children') child_list = models.CharField(max_length=500, unique=True) Above, the child_list is populated with the child names as CSV, when the children are selected in Teacher1Admin in admin.py. But when any child is deleted, though the corresponding relationships are deleted, the name of the child remains in the Teacher table in the child_list. How can this be removed, whenever the Child1 table is edited/ child deleted, without much performance overhead? -
Add UID or Unique ID in Wagtail/Django
So my question was how I can generate a random UID or slug for my CMS. If I use the default id which is coming from API v2 people can easily guess my next post URL easily. Is there any way to add a unique slug/ID/UUID for my wagtail CMS? -
Django Rest Framework with gunicorn gevent
I'm using Django Rest Framework(class views), with configs gunicorn --workers=5 --worker-class=gevent --worker-connections=100 When interacting with ORM, it gives You cannot call this from an async context - use a thread or sync_to_async Can someone help me with this. -
what way can i fix django DB migration error without deleting migration files
what is the best way to fix this kind of DataBase Errors without having to delete my db and migration files and starting to enter data from scratch? django.db.utils.IntegrityError: The row in table 'store_product_category' with primary key '1' has an invalid foreign key: store_product_category.category_id contains a value '1' that does not have a corresponding value in store_category.id. while inspection the sqlit DB i observe that there is a mismatch in the IDs of the store_product_category and store_category.id. is there anyway i can modify the id directly on the DB, i dont want to start deleting database files and migrations -
Cleaning a specific field in Django forms.Form?
I have a Django form like this. class TransactionForm(forms.Form): start = forms.DateField() end = forms.DateField() I wanted to change the value before running validation: def clean_start(self): start = sef.cleaned_data.get('start') return bs_to_ad(start) //This function returns date in 'YYYY-MM-DD' format The problem is that this method runs in forms.ModelForm object but doesn't in forms.Form object. Help appriciated. Thank You. -
How to maintain the log name for an unhandled exception in Django
I am a bit lost about the logging topic. I declare all my loggers with logger = logging.getLogger(__name__) so when logging I have this info available. However, if an unhandled exception happens, I know that Django logs the exception with log name as django.request and so on because of this https://docs.djangoproject.com/en/4.0/ref/logging/#loggers, but what if I would like to use the log name I have declared? I know I am not actually calling the logger when the exception happens, but I would like to know the originary module for the exception. Any ideas? Thanks! -
Django Simple Jwt Authenticate multiple models
I'm working on a project that includes users communicating with devices( rpi's) via websockets. They only way I can think to make it more secure so other's can't access a websocket 'room' they aren't allowed to be in, is to have a separate way for the rpi's to login like users do. Then somehow check if they are authenticated when connecting to a socket room. Any tips for how to do this? -
Django - DateTime Model field saving time as midnight
I'm experiencing an unusual and frustrating challenge: I have formatted the date/time input inside of the form so it knows what format I'm sending it in, the form validates, and there are no challenges with the data, however when it's saving it saves the time as midnight no matter what way I plug it in. The failing value is sample_date, in the below model. Database Pic: https://imgur.com/yUObctR Model class WaterTest(models.Model): name = models.CharField(max_length=200) sample_date = models.DateTimeField() sample_address = models.TextField() mailing_address = models.TextField(blank=True, null=True) sample_point = models.CharField(max_length=200) job_site = models.ForeignKey(JobSite, on_delete=models.CASCADE, blank=True, null=True) template = models.ForeignKey(Template, on_delete=models.CASCADE, blank=True, null=True) collected_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) def __str__(self): return f"{self.name}: {self.sample_address}" class Meta: verbose_name = 'Water Test' verbose_name_plural = 'Water Tests' Form class CreateWaterTestForm(forms.ModelForm): sample_date = forms.DateField(input_formats=['%m/%d/%Y %H:%M']) class Meta: model = WaterTest fields = ['name', 'sample_date', 'sample_address', 'mailing_address', 'sample_point', 'job_site', 'template', 'collected_by'] create_report.html <div class="col-md-6"> <div class="mb-3"> {{ form.sample_date.errors }} <label class="form-label" for="{{ form.sample_date.id_for_label }}">Sample Date/Time <span class="text-danger">*</span></label> {{ form.sample_date|add_class:"form-control" }} </div> </div><!-- Col --> <script> $("#{{ form.sample_date.id_for_label }}").datetimepicker({ {% if THEME == 'demo2' %}theme: 'dark',{% endif %} format: 'm/d/Y H:i' }); </script> DateTime picker: https://xdsoft.net/jqplugins/datetimepicker/ GitHub: https://github.com/varlenthegray/wcadmin/tree/dev -
Fetch relations from ManyToMany Field using Annotation
I have my database here. Where I have 2 users connected to one instance of ChatRoomParticipants with a ManyToManyField. I'm trying to get list of related users from a ManyToMany Relation Field from ChatRoomParticipants where I don't want to show the currently authenticated user in the list with other fields i.e room present in the model. Considering user f4253fbd90d1471fb54180813b51d610 is currently logged in and is related to all ChatRooms via ChatRoomParticipants model. Things I've tried but couldn't get the desired output chatrooms = list(ChatRoomParticipants.objects.filter(user=user).values_list('user__chatroom_users__user__username', 'room').distinct()) ##### chatrooms = ChatRoomParticipants.objects.filter(user=user).annotate(user!=User(user)) #### chatrooms = Chatrooms.objects.filter(user=user) rooms = chatrooms.values('user__chatroom_users__user__username').distinct().exclude(user__chatroom_users__user__username=user) I want an output like [ { 'user': '872952bb6c344e50b6fd7053dfa583de' 'room': 1 }, { 'user': '99ea24b12b8c400689702b4f25ea0f40' 'room': 2 }, { 'user': 'eecd66e748744b96bde07dd37d0b83b3' 'room': 3 }, ] models.py class ChatRoom(models.Model): name = models.CharField(max_length=256) last_message = models.CharField(max_length=1024, null=True) last_sent_user = models.ForeignKey( User, on_delete=models.PROTECT, null=True) def __str__(self): return self.name class Messages(models.Model): room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) content = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class ChatRoomParticipants(models.Model): user = models.ManyToManyField(User, related_name='chatroom_users') room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) -
Creating a handler for user_activated signal
I want to receive a signal when user is activated (i.e. when auth_user.is_active becomes 1). I only want to receive this signal once, the very first time that the user is activated. I have used the answer given to this question, and it works for me: @receiver(pre_save, sender=User, dispatch_uid='get_active_user_once') def new_user_activation_handler(sender, instance, **kwargs): if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists(): logger.info('user is activated') However this seems to be a customized signal, I believe django has a built-in user_activated signal. I have tried using the built-in signal but it does not fire: from django_registration.signals import user_activated @receiver(user_activated, sender=User, dispatch_uid='django_registration.signals.user_activated') def new_user_activation_handler(sender, instance, **kwargs): logger.info('user is activated') Any idea why this signal is being fired? -
How to properly make a signup view with django
I'm made a sign up view with Django but it's not working, it's stored in the database and all but I can't login with the data stored by that view while I can login with the user I made with manage.py createsuperuser here's my signup view def signup(request): if request.method == 'POST': user = User.objects.create( username=request.POST['username'], password=request.POST['password'], email=request.POST['email'], first_name=request.POST['first_name'], last_name=request.POST['last_name'], ) user.save() return HttpResponseRedirect(reverse('posts')) else: signupform = SignUpForm() return render(request, 'users/signup.html', {'form': signupform}) and here's my signup form class SignUpForm(forms.Form): username = forms.CharField(max_length=30, required=True) password = forms.CharField(widget=forms.PasswordInput(), required=True) email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) I just need to know what exactly is wrong and how to fix it exactly or what do I need to learn to perform this task properly. -
Is there a Django extension that does something similar to Ruby on Rails AttrJson
I've tried looking for a Django equivalent to RoR ActiveRecord AttrJson but I can't seem to find one. Is there a similar Django extension? -
How to use Django's DurationField with Postgres, when defined previously using sqlite?
I recently moved all my data from sqlite to postgres. All fields seem to work fine except for the duration field. It is shown as an integer in the admin panel and it does not let me edit or save. It works fine with sqlite. However after moving to Postgres, I get the following errors (upon saving or updating): ProgrammingError at /admin/content/movie/add/ column "duration" is of type bigint but expression is of type interval HINT: You will need to rewrite or cast the expression. class Movie(models.Model): """ Stores movie related information. """ unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(verbose_name='name', max_length=100, blank=False, unique=True) slug = models.SlugField(verbose_name='slug', null=True, blank=True) description = models.TextField(verbose_name='description', blank=True) poster = models.ImageField(verbose_name='poster',upload_to='posters/movies', default='defaults/video.webp', validators=[validate_image]) # Field of interest duration = models.DurationField(verbose_name='duration') created_at = models.DateTimeField(verbose_name='created_at', auto_now_add=True) I also used the following length method for successfully converting the field to human readable form (when using sqlite), but it does not work after moving to postgres. It says: duration (int) does not have 'days' attribute def length(self): """ Converts timedelta into hours and minutes. """ days, seconds = self.duration.days, self.duration.seconds hours = days * 24 + seconds // 3600 minutes = (seconds % 3600) // 60 seconds = (seconds % … -
Does Django cache clear when the server is restarted?
I am trying to use Django's caching API like this: from django.core.cache import cache cache.set('test',[],None) ... list = cache.get('test')... I have 2 questions about this Do I need to set the caching backend in settings for this type of usage? It seems to work without that. Will the cache get reset when the server is restarted. My use case is that I have a function that grabs all classes in the project that are a subclass of a certain class. I only need that function to run when the server loads, because obviously the code is not changing. So if I cache this list of classes and then add a class to the codebase that also inherits from this class, will the cache get reset and have this new class in it now also? -
Most efficient way of storing and retrieving 3 lists of related data in python
I have a django model name, the model and the record of the model. What is the most efficient way of storing and retrieving them. I was thinking of 3 separate lists or a dictionary with the model name as the key and tuple containing the model and record as the value. Any other options? -
How to Show message when anonymosuser post something in Django
I used this method to show message when user send post request. this method works until the user is authorized ... but if anonymous user send post request , something is wrong here.... cause the request is not valid anymore... belong error occurs for me on this line messages.error(request, "Error. Message not sent.") The view shop.views.add_to_cart didn't return an HttpResponse object. It returned None instead. Then I tried to pass a HttpRequest... not working again How can I show message when anonymosuser post something in Django ? -
Availability Schedule field in Django Models?
I am quite new to Django and I'm trying to build a web application where some users will be able to input their available weekly schedule and also show at what times of a day they are available. The picture below(this is just front-end part) shows something similar to what I'm trying to build. What type of Model field do I use to store this type of information inside of a Model class? -
How i can realize multiple pagination(drf)
If I'll send get request like thisenter image description here, i need to have multiple pagination (LimitOffset and PageNumber). models.py: from django.db import models class Products(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d/", null=True) hashtag = models.CharField(max_length=255) is_hit = models.BooleanField(default=False) category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True) def __str__(self): return self.title class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name views.py: from rest_framework import generics from rest_framework.pagination import PageNumberPagination from .models import * from .serializers import ProductsSerializer class PaginationProducts(PageNumberPagination): page_size = 2 page_size_query_param = 'page_size' max_page_size = 2 class ProductsAPIList(generics.ListCreateAPIView): queryset = Products.objects.all() serializer_class = ProductsSerializer pagination_class = PaginationProducts serializers.py from rest_framework import serializers from .models import * class ProductsSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" def get_photo_url(self, obj): request = self.context.get('request') photo_url = obj.fingerprint.url return request.build_absolute_uri(photo_url) I need something that can help API client choose number of page and quantity of posts on that page. Think that in this case i need NumberPagePagination and LimitOffsetPagination. -
protect a django rest api against sql injection
I have a REST API using django and i want to secure it against sql injection. For example when i type on the browser : localhost:8080/MyApi/?id=3 or 'a'='a', i want to get an error. I searched on the net and i find that sanitizing is a solution, but this solution can validate the fields of my api and not from the url This is what i tried : class FieldSerializer(serializers.Serializer): Field = serializers.CharField(max_length=100) def validate_field(self, value): return bleach.clean(value) How can i do that? -
Hi there I am fairly new to heroku and would like some information on server capabilities
I want to deploy a social media app on heroku with an expected total of about 5000users and 1000 concurrent users. -All users are allowed to post products with a maximum of 3 pics -Upload Profile pictures. What heroku plan would best serve my needs or what other options are there. Thanks in advance -
HTML Checkbox: automatic checkable prop update based on value with Javascript Jquery
This is my JS file to make the checkboxes, i just want that the checked prop of the checkbox updates itself base on the value of the input because my template engine renders the value of the boolean fields directly to my input value attr. But is not working $(document).ready(function () { $("input:checkbox").each(function (e) { console.log($(this).val()) value = $(this).val() $(this).prop('checked', value); }); }); <tr class="checkbox_widget_button"> <td> <div class="card-header"> {{item.validation}}</div> </td> <td> <form method="POST" name="validationFormName_{{item.id}}" id="validationFormId_{{item.id}}"> {% csrf_token %} <div class="card-body"> <input type="hidden" name="id" value="{{item.id}}"> <input type="hidden" name="user_id" value="{{user.profile.custom_user_id}}"> <label for="validation">{{item.validate|lower}}</label> <input type="checkbox" name="validation" value="{{item.validate|lower}}" id="validation"> </div> </form> </td> </tr> -
How can I loop over S3 Media folders in Django?
For context, my AWS S3 media folder consists of subfolders. Each one contains only images for an advertisement. In local, I can loop over each image within a folder and render it to the advertisement page however I can't get it to work in production. The relevant view rendering the location looks like below: def carmodel(request, carmodel_id): carmodel = get_object_or_404(CarModel, id=carmodel_id) folder_name = carmodel.title.replace(" ", '%20') image_folder = os.listdir('media/'+carmodel.title) return render(request, 'vehicles/vehicle.html', {"carmodel": carmodel, "image_folder":image_folder, "folder_name":folder_name}) Each folder is named using the carmodels title. And in the vehicles.html file, I'm looping over it like so. {% for image in image_folder %} <img src="/media/{{ folder_name }}/{{ image }}" class="slider-thumbnail"> {% endfor %} I know that the os.listdir from the image_folder variable within carmodel view doesn't work in production. But I'm stuck trying to figure out how to fix it. I'm ultimately trying to construct the media url by using MEDIA_URL, then folder name then at the end, at the iteration for each image . Hope this makes sense!