Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
access attribute via serializer django
I got following models: class OrderItem(models.Model): ordered_amount = models.IntegerField(validators=[MinValueValidator(0)]) amount = models.IntegerField(default=0) order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="order_items" ) class Order(models.Model): reference = models.CharField(max_length=50) purchase_order = models.CharField(max_length=15, blank=True, null=True) I'm now writing a serializer for listing orders. In this OrderSerializer I need to access amount and ordered_amount in the OrderItem class. How do I do this? This is What I have now: class AdminOrderListSerializer(serializers.ModelSerializer): amount = serializers.IntegerField() ordered_amount = serializers.IntegerField() class Meta: model = Order fields = [ "purchase_order", "reference", "amount", "ordered_amount", ] # noinspection PyMethodMayBeStatic def validate_amount(self, order): if order.order_items.amount: return order.order_items.amount return # noinspection PyMethodMayBeStatic def validate_ordered_amount(self, order): if order.order_items.ordered_amount: return order.order_items.ordered_amount return This gives me following error: AttributeError: Got AttributeError when attempting to get a value for field amount on serializer AdminOrderItemListSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Order instance. Original exception text was: 'Order' object has no attribute 'amount'. -
Using DjangoCMS Wizards Without Temp Files Directory
I have tried creating a custom Wizard for the first time recently. It works well; however, there is a questions. Is there a way to prevent the Wizard from needing "wizard_tmp_files" directory and uploading files there? In our setup we use AWS S3. The files get uploaded there, but their copies also linger in "wizard_tmp_files", which is annoying, especially if the files are large. I wonder if there is a way to avoid using "wizard_tmp_files" altogether. Any help or advice is appreciated. Model: class Video(models.Model): title=models.CharField(max_length=500) description=models.TextField(default="") hash=models.CharField(max_length=10, default=_createHash, unique=True) creation_date=models.DateTimeField(default=timezone.now) videofile=models.FileField(upload_to='videos/', null=True, verbose_name="Video") poster=models.ImageField(upload_to='videos/thumbnails ', null=True, verbose_name="Poster") tags = TaggableManager() CMS Wizard: from django.utils.translation import override as force_language from .forms import VideoForm class VideoWizard(Wizard): def get_success_url(self, obj, **kwargs): """ This should return the URL of the created object, «obj». """ if 'language' in kwargs: with force_language(kwargs['language']): url = obj.get_absolute_url() else: url = obj.get_absolute_url() return url video_wizard = VideoWizard( title="New Video", weight=200, form=VideoForm, description="Create a new video", ) wizard_pool.register(video_wizard) -
I am using codepen animation with django templates but nothing happen
I used codepen loader, before loading the main page this effect must take place I think I get confused in extends tag. all files are connected to each other. The below code doesn't give me an error just a white blank page. Here is my base.html {% block content %} <!DOCTYPE html> {% load static %} <html> <head> <title></title> <link rel="stylesheet" type="text/css" href="{% static 'css/my-loader'%}"> </head> <body> h1.intro cat loader .box .cat .cat__body .cat__body .cat__tail .cat__head </body> </html> {% endblock %} This is my-loader.css position: $type; @if $dir != 'bottom' {top: 0; } @if $dir != 'right' {left: 0; } @if $dir != 'left' {right: 0; } @if $dir != 'top' {bottom: 0; } } .cat { position: relative; width: 100%; max-width: 20em; overflow: hidden; background-color: #e6dcdc; &::before { content: ''; display: block; padding-bottom: 100%; } &:hover > * { animation-play-state: paused; } &:active > * { animation-play-state: running; } } %cat-img { @include fill-full; animation: rotating 2.79s cubic-bezier(.65, .54, .12, .93) infinite; &::before { content: ''; position: absolute; width: 50%; height: 50%; background-size: 200%; background-repeat: no-repeat; background-image: url('https://images.weserv.nl/?url=i.imgur.com/M1raXX3.png&il'); } } .cat__head { @extend %cat-img; &::before { top: 0; right: 0; background-position: 100% 0%; transform-origin: 0% 100%; transform: rotate(90deg); } … -
DRF SerializerMethodField how to pass parameters
Is there a way to pass paremeters to a Django Rest Framework's SerializerMethodField? Assume I have the models: class Owner(models.Model): name = models.CharField(max_length=10) class Item(models.Model): name = models.CharField(max_length=10) owner = models.ForeignKey('Owner', related_name='items') itemType = models.CharField(max_length=5) # either "type1" or "type2" What I need is to return an Owner JSON object with the fields: name, type1items, type2items. My current solution is this: class ItemSerializer(serializers.ModelSerializer): class Meta: model = models.Item fields = ('name', 'itemType') class OwnerSerializer(serializers.ModelSerializer): type1items = serializers.SerializerMethodField(method_name='getType1Items') type2items = serializers.SerializerMethodField(method_name='getType2Items') class Meta: model = models.Owner fields = ('name', 'type1items', 'type2items') def getType1Items(self, ownerObj): queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType="type1") return ItemSerializer(queryset, many=True).data def getType2Items(self, ownerObj): queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType="type2") return ItemSerializer(queryset, many=True).data This works. But it would be much cleaner if I could pass a parameter to the method instead of using two methods with almost the exact code. Ideally it would look like this: ... class OwnerSerializer(serializers.ModelSerializer): type1items = serializers.SerializerMethodField(method_name='getItems', "type1") type2items = serializers.SerializerMethodField(method_name='getItems', "type2") class Meta: model = models.Owner fields = ('name', 'type1items', 'type2items') def getItems(self, ownerObj, itemType): queryset = models.Item.objects.filter(owner__id=ownerObj.id).filter(itemType=itemType) return ItemSerializer(queryset, many=True).data In the docs SerializerMethodField accepts only one parameter which is method_name. Is there any way to achieve this behaviour using SerializerMethodField? (The example code here is overly simplified … -
Getting an additional HTML data using xhttp in Django
I'm working now with Django form based on ModelForm class which uses some JavaScript on my page to receive form data using POST. class MyForm(ModelForm): data_url = '/form-data/' dep_fields = '__all__' class Meta: model = Sign fields = '__all__' exclude = ['name', ] class Media: js = ('js/form.js',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) attrs_dict = {'onchange': 'addForm(this)', 'style': 'display:', 'data-url': f'{self.data_url}'} if self.data: '''form fields logic''' My Javascript does the following. It stores my form data like this: var data = new FormData(obj.form); and then sends in to my server every time I change any form field: xhttp.send(data); And form data looks like this: data1 = {'csrfmiddlewaretoken': ['cpWuNU1JfK'], 'country': ['2'], 'region': [''], 'area': [''], 'quality_mark': [''], 'sign': ['']} (I reduced the token for convenience) So all I need is to get ID of chosen field from my HTML page (country ID in this case). I added the following code to my JS: var field_id = parseInt(obj.id ); xhttp.send(field_id); And it seems to be working but I can’t understand where or how I can get this data (field_id) on my Django server. -
Django updateView always updating the first element in database
I have a simple model.py which has a ForeignKey relation. class Release(models.Model): name = models.CharField(max_length=200, db_index=True, unique=True) class Feature(models.Model): release = models.ForeignKey(Release, on_delete=models.SET_NULL, null=True, related_name='features') name = models.CharField(max_length=200, db_index=True, unique=True) In url.py path('release/<int:pk>/feature/<int:pk1>/update/', views.FeatureUpdate.as_view(), name='feature-update'), In views.py: class FeatureUpdate(UpdateView): model = Feature fields = ['name'] In feature_form.html {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> <input type="button" value="Cancel" onclick="history.back()"> </form> {% endblock %} Lets say I have 1 release(release-A) and 2 features(feature-A and feature-B) in database. When i try to edit feature-A it works. However when i try to edit feature-B: the form shows feature-A data and also edits feature-A. I am new to django and not able to go further. Please help.. -
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.