Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework's IsAdminUser doesn't prevent non-admin users
I want to make one view admin-only. I'm using a simple function-based view with the @permission_classes decorator. I want this to be available only to admin users. from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAdminUser from django.http import JsonResponse @permission_classes([IsAdminUser]) def testing(request): return JsonResponse({"status": "ok", "user": request.user.username, "is_staff": request.user.is_staff}) However when I curl as an anonymous user the check clearly isn't applied: curl http://localhost:8000/testing/ {"status": "ok", "user": "", "is_staff": false} I would expect to be rejected if I wasn't logged in, or wasn't an admin user. It looks like I'm using them correctly according to the permissions and decorators docs. -
How to fix the error when configuring saml on Django?
Here are the items I use: python 3.6.8 django 2.1.5 django_saml2_auth all is installed correctly without an issue When I run the server, I get the error message as follows: saml2.sigver.SigverError: Cannot find ['xmlsec.exe', 'xmlsec1.exe'] How to fix this error? -
many to many array field in djano model
I'm building a work orders model in django. I'd like to have an array field for parts required with quantities and another array field of parts produced with quantities. The parts would be foreign keys from a model in an inventory app I have already created. From what I've read PostgreSQL won't allow for foreign keys in an array field. so I would need to have a many to many field in a new model. But I'm not sure how to construct that. what would be the best way to go about this? models.py from django.db import models from django.contrib.postgres.fields import ArrayField from inventory.parts.models import partslist # Create your models here. class jobs(models.Model): jobid = models.CharField(max_length=100) partsrequired = ArrayField( ArrayField( models.ForeignKey(partslist, on_delete=models.CASCADE) ) ) partsproduced = ArrayField( ArrayField( models.ForeignKey(partslist, on_delete=models.CASCADE) ) class instruction(models.Model): job = models.ForeignKey(jobs) pdf = models.FileField(upload_to='pdf') -
Celery worker best practices
I am using Celery to run background jobs for my Django app, hosted on Heroku, with Redis as broker. and I want to set up task prioritization. I am currently using the Celery default queue and all the workers feed from. I was thinking about implementing prioritization within the only queue but it is described everywhere as a bad practice. The consensus on the best approach to deal with the priority problem is to set different Celery queues for each level of priority. Let's say: Queue1 for highest priority tasks, assigned to x workers Queue2 the default queue, assigned to all the other workers The first problem I see with this method is that if there is no high priority task at some time, I loose the productivity of x workers. Also, let's say my infrastructure scales up and I have more workers available. Only the number of "default" workers will be expanded dynamically. Besides, this method prevents me from keeping identical dynos (containers on Heroku) which doesn't look optimized for scalability. Is there an efficient way to deal with task prioritization and keep replicable workers at the same time? -
Django REST framework, serializer performance degradation
I have a simple list API view which is using serializer: class ListCreateDeploymentView( generics.ListCreateAPIView ): permission_classes = (IsAuthenticated,) renderer_classes = [JSONRenderer] content_negotiation_class = IgnoreClientContentNegotiation def get_queryset(self): queryset = Deployment.objects.all() return queryset def list(self, request, version): queryset = self.get_queryset() serializer = DeploymentListSerializer(queryset, many=True) data = serializer.data return Response(data) Serializer is simple: class DeploymentListSerializer(serializers.ModelSerializer): class Meta: model = Deployment fields = ( 'id', 'query', 'config', 'started_at', 'finished_at', 'status', 'project', ) read_only_fields = ( 'id', 'query', 'config', 'started_at', 'finished_at', 'status', 'project', ) Then I do a local load test with 10 users and delay 1s each execution so target rps is 10 req/s and see this picture with a clear performance degradation after few minutes What means If I open 10 tabs in browser with ajax request every second to this endpoint the server will get unresponsive in a minute: Then I used recommendations from here and used read-only regular serializer: class DeploymentListSerializer(serializers.ModelSerializer): # commands = CommandListSerializer(read_only=True, many=True) # clients = ClientSimpleSerializer(read_only=True, many=True) id = serializers.IntegerField(read_only=True) query = serializers.CharField(read_only=True) config = serializers.CharField(read_only=True) started_at = serializers.DateTimeField(read_only=True) finished_at = serializers.DateTimeField(read_only=True) status = serializers.IntegerField(read_only=True) project = serializers.CharField(read_only=True) class Meta: model = Deployment fields = ( 'id', 'query', 'config', 'started_at', 'finished_at', 'status', 'project', ) The situation became … -
Serializing context on Django CBV?
I'm having issues serializing a 3rd party package (django-organizations) as I want to receive the context in JSON. The class itself looks like this: class OrganizationUserMixin(OrganizationMixin, JSONResponseMixin): """Mixin used like a SingleObjectMixin to fetch an organization user""" user_model = OrganizationUser org_user_context_name = 'organization_user' def get_user_model(self): return self.user_model def get_context_data(self, **kwargs): kwargs = super(OrganizationUserMixin, self).get_context_data(**kwargs) kwargs.update({self.org_user_context_name: self.object, self.org_context_name: self.object.organization}) return kwargs def get_object(self): """ Returns the OrganizationUser object based on the primary keys for both the organization and the organization user. """ if hasattr(self, 'organization_user'): return self.organization_user organization_pk = self.kwargs.get('organization_pk', None) user_pk = self.kwargs.get('user_pk', None) self.organization_user = get_object_or_404( self.get_user_model().objects.select_related(), user__pk=user_pk, organization__pk=organization_pk) return self.organization_user And I'm trying to pass this custom JSONResponseMixin to my OrganizationUserMixin class: class JSONResponseMixin: """ A mixin that can be used to render a JSON response. """ def render_to_json_response(self, context, **response_kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ return JsonResponse( self.get_data(context), **response_kwargs ) def get_data(self, context): print(context) return context And then overriding the render_to_response in OrganizationUserMixin as such: def render_to_response(self, context, **response_kwargs): return self.render_to_json_response(context, **response_kwargs) If I print context It looks something like this # { # 'object': <OrganizationUser: Erik (MyOrgName)>, # 'organizationuser': <OrganizationUser: Erik (MyOrgName)>, # 'organization': <Organization: MyOrgName>, # 'view': <organizations.views.OrganizationUserDetail … -
Multithreading in Python with multiple for loops inside main function
Am checking if you can thread multiple for loops inside a main function as per below code. reason for this is because am trying to save this data inside a database. But while running the code new values are coming in which makes data inconsistent between the lists. I use zip function to pair all the list values together. So if I can run each for loop as a seperate thread, it will be fast enough to get acurate data. # Creating empty list to store the values ana_username = [] publicip = [] privateip = [] bytes_Tx = [] bytes_Rx = [] group_policy03 = [] duration03 = [] def ana(): # SSH Connection parameters remote_conn_pre = paramiko.SSHClient() remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_conn_pre.connect(hostname='10.10.10.10', port=22, username='root', password='*******', look_for_keys=False, allow_agent=False) remote_conn = remote_conn_pre.invoke_shell() # Initiating list of commands remote_conn.send('\n') remote_conn.send('en\n') remote_conn.send(str(password)+ '\n') remote_conn.send('conf t\n') remote_conn.send('pager 0\n') remote_conn.send('end\n') time.sleep(1) remote_conn.send('sh vpn-sessiondb anyconnect | grep Username\n') time.sleep(1) policy_user = remote_conn.recv(11111) remote_conn.send('sh vpn-sessiondb anyconnect | grep Assigned\n') time.sleep(1) policy_ip = remote_conn.recv(11111) remote_conn.send('sh vpn-sessiondb anyconnect | grep Bytes\n') time.sleep(1) policy_bytes = remote_conn.recv(11111) remote_conn.send('sh vpn-sessiondb anyconnect | grep Group Policy\n') time.sleep(1) policy_group = remote_conn.recv(11111) remote_conn.send('sh vpn-sessiondb anyconnect | grep Duration\n') time.sleep(1) policy_duration = remote_conn.recv(11111) # End the SSH session remote_conn.send('pager … -
'NoneType' object is not iterable ERROR when editting profile in Django framework Python 3.7
I'm still junior developer in Django and webframe. Working on developing a coworkspace management system in django 3. In the profile page of user, when they click edit profile they get this error. Note: Editting the profile using the 'admin' works perfectly fine with no errors. but the users themselves get this error. if theres any details needed more i will post it. Heres the traceback: Traceback (most recent call last): File "/home/maha/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/maha/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/maha/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/maha/venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/maha/venv/nadine/member/views/profile.py", line 232, in edit_profile return render(request, 'member/profile/profile_edit.html', context) File "/home/maha/venv/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/maha/venv/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/maha/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/maha/venv/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File … -
Django ModalForm unable to process requests correctly
I'm currently trying to implement modal forms in my Django application ( I installed this library: https://pypi.org/project/django-bootstrap-modal-forms/ My urls.py looks like this: from django.urls import path from cloudapp.server_users.views import * app_name = "server_users" urlpatterns = [ path("", ServerUsersManagement.as_view(), name="user_management"), path('add_user/', ServerUsersCreateView.as_view(), name='add_user') ] My views.py looks like this: ... from django.views import generic from bootstrap_modal_forms.generic import (BSModalCreateView, BSModalUpdateView, BSModalReadView, BSModalDeleteView) class ServerUsersManagement(LoginRequiredMixin, generic.ListView): model = ServerUsers context_object_name = 'server_users' template_name = "pages/user_management.html" queryset = ServerUsers.objects.all() def get_context_data(self, **kwargs): context = super(ServerUsersManagement, self).get_context_data(**kwargs) context['email_aliases'] = EmailAliases.objects.all() return context # Create User class ServerUsersCreateView(LoginRequiredMixin,BSModalCreateView): template_name = 'server_users/add_user.html' form_class = ServerUsersForm success_message = 'Success: User was created.' success_url = reverse_lazy('server_users:user_management') def form_valid(self, form, **kwargs): username = form.cleaned_data['username'] company_id = str(self.request.user.id) final_path = server_users_logic.create_path(settings.VPN_BUNDLE_PATH, company_id, username) form.instance.vpn_certificate = final_path #company_id FK in the company table form.instance.company_id = self.request.user.id return super().form_valid(form) My models.py: from django.db import models from cloudapp.users.models import Company class ServerUsers(models.Model): given_name = models.CharField(max_length=30) family_name = models.CharField(max_length=30) cloud_email = models.EmailField(max_length=254) date_of_registration = models.DateField(auto_now=False, auto_now_add=True) username = models.CharField(max_length=30) vpn_certificate = models.FileField(max_length=100, blank=True, default="OK") user_changed_password = models.BooleanField(blank=True, default=False) password = models.CharField(max_length=100, default="some_password") company = models.ForeignKey('users.Company', on_delete=models.CASCADE) My HTML part looks like this: user_management.html {% extends "pages/base.html" %} {% block title %}{% block head_title %}{% endblock … -
How to retrieve all data from foreign keys with Django ORM and return them as JsonResponse
I am trying to get all the data from a model and its foreign keys and I have a hard time using select_related() and values() or values_list(). I got an Order table who got two foreign keys. I need to query all the data and send it as a JsonResponse. This is the line: Order.objects.select_related('persoana_fizica__persoana_juridica').values() I saw I can write inside values what fields I need, I am looking for a method to select all of them without writing every single one, 'all' didn't worked. Any ideas? -
Django: how to update multiple records?
I need to update multiple records (rows) in a table. First, I get informations to select rows to be update: ran_st1 = 1 ran_st2 = 1 ran_bra = 'A' pay_ide = 'FR' bra_lib = 'Polyvitamines et oligo-éléments' Then, I select rows to be updated: rows= Randomisation.objects.filter(Q(ran_st1 = ran_st1) & Q(ran_st2 = ran_st2) & Q(ran_bra = ran_bra) & Q(pay_ide = pay_ide)) And then, I though to make a loop like that, but not sure: for row in rows: r = get_object_or_404(Randomisation, ran_ide = row.ran_ide) r.ran_act = 1 r.save() -
Filtering by CharField choices text property
How could you filter by the choices text instead of the choices key? Suppose you have the following CharField in a model: CHOICES = ( ('FI', 'First'), ('SE', 'Second'), ('TH', 'Third') ) choiceField = models.CharField(max_length=2, choices=CHOICES) Then you try to filter it in a view like so: query_in_choice_field = Model.objects.filter(choiceField__contains=query) This filter only checks 'FI', 'SE' and 'TH'. How would you filter by 'First', 'Second' and 'Third'? -
Django with Ajax with multiple values
I had a html page where on click of a button I open a modal window. Modal window will display some text from database. on button click below jquery executed $('.openbtn').click(function(){ var fname; var mname; var lname; fname="Rakesh"; mname="kumar"; lname="Sharma"; $.ajax( { type:"GET", url: "/myapp/member/search/", data:{ "fname":fname, "mname":mname, "lname":lname, }, success: function( data ) { $( '#divcontent' ).html(data); } }); }); Below is the view def displayModalView(request): return render(request, 'myapp/display_serch_member.html') and following is the url path('member/search/', views.displayModalView, name="display_modal"), No I need to pass fname,mname,lname to views. I have tried path('member/search/<fname>/<mname>/<lname>', views.displayModalView, name="display_modal"), def displayModalView(request,fname,mname,lname): return render(request, 'myapp/display_serch_member.html') but i dont get the desired result. What is wrong or what I need to change? -
NameError at / free variable 'y' referenced before assignment in enclosing scope
I need to make a small project for my university -create webapp that will solve Transportation Problem and well deadline is for tomorrow so I am making MVP version really. I am using Django for webapp and PuLP for transportation problem part. When launching my problem solving logic I receive an error: NameError at / free variable 'y' referenced before assignment in enclosing scope for line: prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x I was using PuLP example from their GitHub here My code for this part is as below: Warehouses = [0,1,2] supply = { 0: deliver1, 1: deliver2, 2: deliver3 } Distributors = [0, 1, 2] demand = { 0: receiver1, 1: receiver2, 2: receiver3 } costs = [ #dsitributors -static variables for debugging will change that later on #D E F [3, 5, 7],#A Warehouse [12, 10, 9],#B Warehouse [13, 3, 9],#C Warehouse ] prob = LpProblem("Transportation Problem",LpMinimize) Routes = [(x,y) for x in Warehouses for y in Distributors] route_vars = LpVariable.dicts("Route",(Warehouses,Distributors),0,None,LpInteger) prob += lpSum([route_vars[x][y]*costs[x][y] for (x,y) in Routes]), "Sum of Transporting Costs" for x in Warehouses: prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of … -
Returning array of deleted objects in single GraphQL mutation (graphene-django)
While in the past I used a GraphQL mutation that deletes a single record, I came up with the idea that this is not ideal in the case I want to delete several records at once since it ended up by calling the mutation that delete 1 record several times (in a loop) which results in several API call over the network. So I decided to instead modify the mutation to accept has an argument a list of objects or IDs (whatever) on which I can loop in the backend. By doing this, it does only 1 call to the API with all the records to delete. I managed to do it and the only blocking point that I face is the return statement. I couldn't figure out how to write it. So if I have a model (in my schema) such as : class UserType(DjangoObjectType): class Meta: model = User fields = ( 'id', 'username', 'password', 'first_name', 'last_name', 'is_active', 'group_ids', ) full_name = graphene.String() full_identification = graphene.String() In the past I used : class DeleteUser(graphene.Mutation): username = graphene.String() class Arguments: id = graphene.ID() def mutate(self, info, **kwargs): user = get_object_or_404(User, id=kwargs['id']) user.delete() return user class Mutation(graphene.ObjectType): delete_user = DeleteUser.Field() … -
How to make search in Django with SearchVector on ArrayField?
I have a Company model with related tags. I need to configure search by name, content and tags, and if search works with name, content fields , it doesn't on ArrayField -> tags models.py class Company(models.Model): name = models.CharField(max_length=150) content = models.TextField(blank=True) **tags** = ArrayField(models.CharField(max_length=200), blank=True, null=True utils.py def get_rank_search_result(q, category=None): ... vector = SearchVector('name', config='russian', weight='A') + \ SearchVector('content', config='russian', weight='B') + \ SearchVector('tags', config='russian', weight='B') #SearchVector(Func(F('tags'), Value(' '), function='array_to_string'), config='russian', weight='B') #doesn't work either query = SearchQuery(q, config='russian', search_type=search_type) return list(qs.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('-rank')) ``` Actually, the search stops working after i add line with SearchVector('tags').... -
Edit a unique field used as foreignkey in Django
I have two models, one Price and Market: class Market(models.Model): market_name = models.CharField(max_length=3, unique=True) class Price(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, to_field="market_name") I want to be able to edit the market_name field on the Market model and have the subsequent Price objects updated without causing errors. update or delete on table "appname_market" violates foreign key constraint "appname_price_market_id_5f75a816_fk_appnames" on table "appname_price" DETAIL: Key (market_name)=(Cute Martket Name) is still referenced from table "appname_price". Pointing them on the pk is one the solution, but I want to stick to using market_name as foreignkey for a reason. How would you do that ? I imagined a method for pre_save : @receiver(pre_save, sender=Market) def update_market_field(sender, instance, *args, **kwargs): try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass # Object is new, so field hasn't technically changed, \ # but you may want to do something else here. else: if not obj.market_name == instance.market_name: # Field has changed Price.objects.filter(market=obj.market_name).update_or_create(market=instance) But this still producing errors because actually the Market object hasn't been saved yet. A half solution also is to delete all Prices with that obj.martket_name in this pre_save method, and I have seen that it effectively update the unique field but ... -
If a user uploads an infected file but my Django server does not write it to disk, is my server still at risk?
In the Django docs, it mentions that image uploads below 2.5MB are not written to disk, just to memory. I just need my server to process these images. My concern though, is it possible for my server to still get infected despite not writing them to disk? -
i made an extra Template Tag and it bring a problem for me
Guys I already made an init.py for this to make this as a module so that's not the error from django import template from markdownx.utils import markdownify register = template.Library() @register.filter(name = 'markdown') def markdown(text): return markdownify(text) <p>{{ blog.| markdown |safe }}</p> This not giving any error to me but when I write a blog then on the webpage it is not showing anything, means for which I used markdown template tag, so please help me if you can. -
How do I resolve a 403 error upon accessing site with django?
The site is running on a vps with CentOS7. The server is using the latest version of httpd (apache2 for centos) and mod-wsgi. The website was made with django. Every time I try to access the site either through the ip I get a 403 forbidden error and when I try the site's domain I get a timed out error. sudo status httpd returns Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: active (running) since Wed 2020-04-29 01:44:44 MST; 1s ago Docs: man:httpd(8) man:apachectl(8) Process: 3698 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS) Process: 29778 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS) Main PID: 3703 (httpd) Status: "Processing requests..." CGroup: /system.slice/httpd.service ├─3703 /usr/sbin/httpd -DFOREGROUND ├─3704 /usr/sbin/httpd -DFOREGROUND ├─3705 /usr/sbin/httpd -DFOREGROUND ├─3706 /usr/sbin/httpd -DFOREGROUND ├─3707 /usr/sbin/httpd -DFOREGROUND ├─3708 /usr/sbin/httpd -DFOREGROUND └─3709 /usr/sbin/httpd -DFOREGROUND This is my sites config file stored in /etc/httpd/conf.d/mysite.com.conf # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value … -
Error in models, TypeError: on_delete must be callable
When I run the following command: python manage.py makemigrations I have this error: File "/home/user/project/myvirt/forum/boards/models.py", line 9, in <module> class Topic(models.Model): File "/home/user/project/myvirt/forum/boards/models.py", line 12, in Topic board = models.ForeignKey(Board, related_name='topics', on_delete='cascade') File "/usr/local/lib/python3.7/dist-packages/django/db/models/fields/related.py", line 801, in __init__ raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable. My models.py content is: from django.db import models from django.contrib.auth.models import User # Create your models here. class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics', on_delete='cascade') creator = models.ForeignKey(User, related_name='topics', on_delete='cascade') class Post(models.Model): message = models.TextField(max_length=4000) topic = models.CharField(Topic, related_name='posts', on_delete='cascade') created_by = models.CharField(User, related_name='posts', on_delete='cascade') created_at = models.DateTimeField(auto_now_add=True) updated_by = models.CharField(User, related_name='posts', on_delete='cascade') updated_at = models.DateTimeField(null=True) This is an exercise in sample forum and seems to be a problem with on_delete='cascade'. -
Django admin reset search box query on filter selection
I have the following class in Django admin of a model: class TopUpsAdmin(admin.ModelAdmin): search_fields = ('user__email', 'user__phone_number',) list_filter = ('status',) Currently the default behavior of the filter is if search box in the listing page is input with test_1 which is a user name and search up the result(url will have the following parameter /?q=test_1) , if select an option in the filter then the filter results also got affected by the search box query on the URL ?q=test_1&status__exact=1) I would like to not have the search results filter the list when i choose a filter. Reading Django docs only provide me how to override the filter with existed query in the parameter(which come from search box). Any help would be appreciate -
how to return several FileField from Queryset in Django?
I have a models with FileField for videos. When i upload only one video i can return it with this code in the view.py: def cours(request, id, slug): c = Cours.objects.get(id=id, slug=slug) p = Plan_simple.objects.filter(cours=c) return render(request, 'upload/cours.html', locals()) But when i upload two or more videos whith formset, and i change get fuction by filter it doesn't work: def cours(request, id, slug): c = Cours.objects.get(id=id, slug=slug) p = Plan_simple.objects.filter(cours=c) return render(request, 'upload/cours.html', locals()) the models.py class Cours(models.Model): titre = models.CharField(max_length=100) slug = models.SlugField(max_length=100) auteur = models.CharField(max_length=42) comment = models.TextField(null=True) link = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE) def save(self, *args, **kwargs): self.slug = slugify(self.titre) super(Cours, self).save(*args, **kwargs) class Meta: verbose_name = "cours" db_table = "cours" ordering = ['date'] class Plan_simple(models.Model): partie = models.CharField(blank=True, max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") vid = models.FileField(upload_to='file/', blank=True, null = True) cours = models.ForeignKey(Cours, related_name = "plan_simple", on_delete=models.CASCADE) def __str__(self): return self.partie class Meta: db_table = "plan_simple" Can you help me? Thanks -
Django JsonField Lookup Filtering with an unknown subkey
I want to filter a Django model by the value of a nested JSON field key when I don't know one of the key values. E.g. I want to do: Model.objects.filter(json_field__firstKey__{UNKNOWN_ID_KEY}__desiredKey__in=[OPTION1,OPTION2]) so that whenever this nested structure exists, and desiredKey exists, I can filter by the desiredValue being OPTION1 or OPTION2 i.e. {desiredKey: OPTION1} or {desiredKey: OPTION2}. I have not managed to find documentation supporting this. Is this possible? If not, does anybody have any alternavtive suggestions? -
Django combine two querysets
My model: class Renewal(models.Model): policy_number = models.integerField() invitation_date = models.DateTimeField() Snapshot of my table is as follows id policy_number invitation_date 86 4353 2020-04-21 16:37:39.071941 87 4354 2020-04-21 16:38:16.082238 97 4355 2020-04-21 17:18:03.997882 99 4377 2020-04-21 17:26:58.414530 162 4218 2020-04-22 18:42:23.066879 167 4218 2020-04-22 18:29:10.571033 171 4218 2020-04-22 18:39:17.546550 175 4238 2020-04-23 17:35:54.444945 176 4238 2020-04-23 17:36:01.482819 177 4239 2020-04-23 17:42:15.056850 178 4238 2020-04-24 13:00:06.886101 179 4243 2020-04-24 13:00:32.098504 180 4241 2020-04-24 13:21:31.215547 181 4360 2020-04-29 13:48:18.765400 in my views, I'm trying to get policy_number in a given date range, as follows def some_function(request): start_date = datetime.date.today() end_date = start_date - datetime.timedelta(days=5) renewals = Renewal.objects.filter(invitation_date__gte=star_date, invitation_date__lt=end_date) print(renewals) what i'm getting : [4238, 4243, 4241] expected answer : [4238, 4243, 4241, 4360] this should ideally give me all renewal records created in last 5 days. However, if today is 2020-04-29, the last policy record should have been 4360, but my last policy record is 4241