Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handling Long response in django App. Avoid 502 bad gateway error
Short description I have small E-mail scraping django App. App gets 'xlsx' file contains URLs to parse, from user and scrap the emails. During the scraping process csv files saved on local storage and can be downloaded any time using a separate button on html. The problem is, it takes many hours to complete the process and html front-end cannot wait for that long and give me error 502 bad gateway. my view.py file #view.py from django.shortcuts import render # from tp_scraper.models import Document from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.files.storage import default_storage from django.http import HttpResponse import os from tp_scraper.code.main_scraper import scraper_py,test_zip #from email_scraper.tp_scraper.code.main_scraper import scraper_py import csv # Create your views here. # def main_page(request): # return render(request,'page1.html',{}) def show_db(reqeust): context={} return render(reqeust,'page1.html',context) def scraper_main(reqeust): if reqeust.method == 'POST' and reqeust.FILES['myfile']: myfile = reqeust.FILES['myfile'] fs = FileSystemStorage() filename = fs.save('file_1.xlsx', myfile) uploaded_file_url = fs.url(filename) return render(reqeust, 'em_scrap.html', { 'uploaded_file_url': uploaded_file_url }) return render(reqeust, 'em_scrap.html') def output(request): res=scraper_py() #This is email scraping code does the scraping jon and take long time. msg='mesage' return render(request,'em_scrap.html',{'msg':msg}) def download_zip(request): res = test_zip() return (res) def how_to(reqeust): context={} return render(reqeust,'Howto.html',context) My URL file.py #urls.py from django.urls import path from tp_scraper … -
Access choices in serializer with a CharField
I have a CharField , which is empty, but I have added a method inside the models to get for me the choices, how can I attach the choices in the serializer field ? Below is my model : class Business(TimeStampedModel): business_id = models.CharField( 'Business ID', max_length=64, unique=True, null=True, blank=True) accordance = models.CharField( 'accordance', max_length=16, blank=True) def update_accordance(self): """ Update accordance field to return choices. """ radio_buttons = RADIO_BUTTON_SELECTIONS values = radio_buttons.get(self.legal_form) return values update_accordance, Just helps me to get the choices in this format : (('yes', _('YES')), ('no', _('NO'))) Then in my serializer : class BusinessDetailedSerializer(serializers.ModelSerializer): """Serializer for complete Business form""" accordance = serializers.CharField(source='update_accordance') class Meta: model = Business fields = '__all__' -
Django Queryset filter for ForeignKey elements
I have a problem with building a custom queryset inside one of my views. Here is a simplified version of my models. The idea is that I want to track the price of different products in different shops. A shop can have multiple products and a product can be present in multiple shops. Products can have set an is_special flag to highlight them. The following structure was choosen because it easily allows adding new products and shops later on: class Product(models.Model): product_id = models.CharField(max_length=255, primary_key=True) is_special = models.BooleanField(default=False) product_name = models.CharField(max_length=255, default='', blank=False, null=False) class ShopProductPrice(models.Model): product = models.ForeignKey("Product", on_delete=models.CASCADE) shop = models.ForeignKey("Shop", on_delete=models.CASCADE, related_name="shop_entry") price = models.FloatField(default=0.0, null=False) class Shop(models.Model): name = models.CharField(max_length=255, default='', blank=False, null=False) location = models.CharField(max_length=255, default='', blank=False, null=False) These are my serializers: class ShopProductPriceSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['product', 'price'] class ShopSerializer(serializers.ModelSerializer): shopProductPriceData = ShopProductPriceSerializer(many=True, source='shopProductPrice_set') class Meta: model = Shop fields = ['name', 'location', 'shopProductPriceData'] And finally, here is the corresponding view where I want to use a custom queryset: class ShopViewSet(viewsets.ModelViewSet): queryset = Shop.objects.all() serializer_class = ShopSerializer def get_queryset(self): queryset = Shop.objects.filter(shopproductpricedata__product__is_special=False) return queryset The important point now is the get_queryset() function. This is what I'm actually working on and … -
PIP installation for Python(Django)
enter image description hereenter image description here After installing python 3.9 version, this is what I am facing in cmd. I am being able to see pip version but if I am commanding pip upgradation it works. How can I solve this PIP problem? -
Website working fine but error in testing
I am getting this error in testing while the website is working perfectly fine. Can someone suggests some changes to be done in the url or html line ERROR: test_index_url_is_resolved (control.tests.test_urls.TestUrls) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/bhavya/Website/control/tests/test_urls.py", line 7, in test_index_url_is_resolved url = reverse('index') File "/usr/lib/python3/dist-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/usr/lib/python3/dist-packages/django/urls/resolvers.py", line 673, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'index' not found. 'index' is not a valid view function or pattern name. ---------------------------------------------------------------------- Ran 1 test in 0.003s This is url line url(r'^$',views.IndexView.as_view(),name='index'), This is used in html file "{% url 'control:index' %}" -
Javascript is not loaded in html in django
In my project,there is a register.html file . the file is given below: <!DOCTYPE html> {% load static %} <html> <head> <title>Page Title</title> </head> <body> <p>This is only for test.</p> </body> <script> src= "{% static 'js/register.js' %}" </script> </html> Here you can see the javascript part in the last section. This script should be load the register.js file which is exists in app_name/static/js/register.js . But the problem is that the register.js file is not loaded . The register.js file is given below: console.log(“this is working”); And you know the output should be this is working but when I run this , the console look as that picture which is given below: browser console screenshot Even If I give full path such as <script> src= "/home/name/python/django/python test/app_name/static/js/register.js" </script> then also the issue is still remain . But if I give direct code like <script> console.log("this is test"); </script> then it perfectly worked. How can I solve this issue? -
How To Stop All Site Associated User From appearing In Post Model ForeignKey During Post Creation
The post logic was to allow all users on my site to be able to create post and news which is a success but unfortunately when creating a post all the whole user in the database appears for the particular authenticated user to choose from and this are information i don't want the user to see when creating post and i do not not plan to remove the user foreign key from the post since it helps me implementing other site critical functions and the author. because the user will serve as author class Post(models.Model): image = models.ImageField(upload_to="images/") title = models.CharField(max_length=150) summary = models.CharField(max_length=250) category = models.ForeignKey(PostCategory, on_delete=models.CASCADE) content = RichTextUploadingField() date_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(max_length=250, unique=True, blank = True) def onlyselfuser(self, *args, **kwargs): self.user = self.request.user super().onlyselfuser(*args, **kwargs) #please take a look at my view.py files class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = __all__ def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) i will appreciate if someone can show me a way out where the login user( user=request.user) will only appear excluding other users on moder and i tried a OneToOneField still and it didnt work. i Don't want to see all site … -
Adding context to django admin changelist_view
I'm trying to add some context to a Django admin view when the change list is displayed. I have this class class LeadStatSummaryAdmin(admin.ModelAdmin): change_list_template = 'admin/stats/leadstatsummary/change_list.html' def get_queryset(self, request): qs = super().get_queryset(request) query=Q() if 'from_date' in request.GET: from_date = datetime.datetime.strptime(request.GET['from_date'], '%d/%m/%Y').strftime('%Y-%m-%d') to_date = datetime.datetime.strptime(request.GET['to_date'], '%d/%m/%Y').strftime('%Y-%m-%d') query = Q(date_of_lead__gte=from_date, date_of_lead__lte=to_date) return qs.filter(query) def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context,) qs = self.get_queryset(request) response.context_data['date_form'] = DateForm(request.GET or None) response.context_data['data'] = qs. \ values('type_of_lead', 'may_contact_provider', 'type_of_care_care_home', 'type_of_care_home_care', 'type_of_care_live_in_care', 'type_of_care_retirement_village') \ .order_by('type_of_lead', 'type_of_care_care_home', 'type_of_care_home_care', 'type_of_care_live_in_care', 'type_of_care_retirement_village','may_contact_provider') \ .annotate(count=Count('type_of_lead')) return response This provides a date form I can use to filter the queryset. This runs fine when called from the menu (so no date form) but when I enter dates and submit I get this error 'HttpResponseRedirect' object has no attribute 'context_data' It is referring to this line of code response.context_data['date_form'] = DateForm(request.GET or None) I do not understand why this should be causing an error and how to fix. Can you help please -
'Category' object is not iterable
I am new to programming I have different categoriries in my django website, I created the model, view. but when I try to go to the localhost/category/categoryname, I get the error: "Category object is not iterable" I appreciate your help in advance #url.py urlpatterns = [ path('', home, name='home'), path('article/<slug:slug>', detail, name='detail'), path('article', article, name='article'), path('category/<slug:slug>', category, name='category')] ############################################### #views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, JsonResponse, Http404 from .models import Article, Category # Create your views here. def home(request): context = { "articles": Article.objects.filter(status="Published") } return render(request, 'website/home.html', context) def detail(request, slug): context = { "article": get_object_or_404(Article, slug=slug, status="Published") } return render(request, 'website/detail.html', context) def article(request): context = { "articles": Article.objects.filter(status="Published"), "category": Category.objects.filter(status=True) } return render(request, 'website/article.html', context) def category(request, slug): context = { "category": get_object_or_404(Category, slug=slug, status=True) } return render(request, 'website/category.html', context) ############################### #models.py from django.db import models from django.utils import timezone # Create your models here. class Category(models.Model): title = models.CharField(max_length=300, verbose_name="Category Topic") slug = models.SlugField(max_length=100, unique=True, verbose_name="Category Address") status = models.BooleanField(default=True, verbose_name="Do you want to show?") position = models.IntegerField(verbose_name="position") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['position'] def __str__(self): return self.title class Article(models.Model): STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') … -
How to send text by template via url in Django?
I want to send text to a view via template. I have two different types of clients that will be processed differently, to take advantage of code I put it in a single view and the specific part treated it with an if else. In the template: <a href="{% url 'client' 'prime' %}"> Client prime </a> <a href="{% url 'client' 'free' %}"> Client </a> In the urls.py .... path('client/<str:typeclient>', Client, name='client'), ..... In the view: def Client(request, typeclient): ... if typeclient == "prime": ... else: .... However I get the following error: NoReverseMatch at / Reverse for 'client' with no arguments not found. 1 pattern(s) tried: ['client\\/(?P<typeclient>[^/]+)$'] Apparently the text is not passing as a parameter that I inserted in the url. In this sense, how can I pass a text from the template via url? -
How to filter in django by greater than or less than dates?
I'm a little confused with the documentation on Django Rest Framework. I have read it several times but I cannot makes sense of it. Maybe I'm not smart enough, I do not know, but I'm trying to create a filter in an Endpoint that let me consult information according to dates, like GET /my-endpoint/?created_at__lte=2020-01-01 // get items created in a date less than 2020-01-01 GET /my-endpoint/?created_at__gte=2020-01-01 // get items created in a date greater than 2020-01-01 I created a filter class class MyEndpointFilter(django_filters.rest_framework.FilterSet): created_at_gte = IsoDateTimeFilter(name="created_at", lookup_expr='gte') created_at_lte = IsoDateTimeFilter(name='created_at', lookup_expr='lte') updated_at_gte = IsoDateTimeFilter(name='updated_at', lookup_expr='gte') updated_at_lte = IsoDateTimeFilter(name='updated_at', lookup_expr='lte') class Meta: model = MyEndpointModel fields = ( 'created_at', 'updated_at', ) And a class view class MyEndpointViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, OrderingFilter ) filterset_class = MyEndpointFilter filterset_fields = {'created_at': ['gte', 'lte'], 'updated_at': ['gte', 'lte']} # I also tried without this line queryset = LogClaimAction.objects.all() serializer_class = MyEndPointSerializer But still, the filter doesn't work. Can someone point me to the mistake I am making? -
ValueError: Dimensions must be equal, with input shapes
I have written this code. My input shape is (100 x100 X3). I am new to deep learning. I have spent so much time on this, but couldn't resolve the issue. Any help is highly appreciated. init = tf.random_normal_initializer(mean=0.0, stddev=0.05, seed=None) input_image=Input(shape=image_shape) # input: 100x100 images with 3 channels -> (3, 100, 100) tensors. # this applies 32 convolution filters of size 3x3 each. model=Sequential() model.add(Conv2D(filters=16, kernel_size=(3, 3),kernel_initializer=init, padding='same', input_shape=(3,100,100))) model.add(Activation('relu')) model.add(Conv2D(filters=32,kernel_size=(3, 3),padding="same")) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2),padding="same")) model.add(Dropout(0.25)) model.add(Conv2D(filters=32,kernel_size=(3, 3),padding="same")) model.add(Activation('relu')) model.add(Conv2D(filters=32, kernel_size=(3, 3),padding="same")) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2),padding="same")) model.add(Dropout(0.25)) model.add(Flatten()) # Note: Keras does automatic shape inference. model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(10)) model.add(Activation('softmax')) model.summary() sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) len(model.weights) model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) Error : In [15]: runfile('/user/Project/SM/src/ann_algo_keras.py', wdir='/user/Project/SM/src') Random starting synaptic weights: Model: "sequential_3" Layer (type) Output Shape Param # conv2d_12 (Conv2D) (None, 3, 100, 16) 14416 activation_18 (Activation) (None, 3, 100, 16) 0 conv2d_13 (Conv2D) (None, 3, 100, 32) 4640 activation_19 (Activation) (None, 3, 100, 32) 0 max_pooling2d_6 (MaxPooling2 (None, 2, 50, 32) 0 dropout_9 (Dropout) (None, 2, 50, 32) 0 conv2d_14 (Conv2D) (None, 2, 50, 32) 9248 activation_20 (Activation) (None, 2, 50, 32) 0 conv2d_15 (Conv2D) (None, 2, 50, 32) 9248 activation_21 (Activation) (None, 2, 50, 32) 0 … -
Django form to save several records for a given model. bulk_create() buffer
Say I have the following: models.py class Project(models.Model): project_name = models.CharField(primary_key=True, max_length=100) # ... other fields ... comments = models.CharField(max_length=150) class Milestone(models.Model): milestone = models.CharField(primary_key=True) class ProjectMilestone(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) project_name = models.ForeignKey(Project) milestone = models.ForeignKey(Milestone) date = models.DateField() My purpose is to create a forms.py, and the corresponding views.py and .html files, so the user could enter one project and several milestones for that project at the same time. The ideal interface would allow the user to write the project and its fields, and then select a milestone and a date, buffer this data, and select as many other milestones more as wanted. Then, submit all to both models. I have been checking the "bulk_create()" approach, which I think it could work if several milestones are introduced in an auxiliary table via JavaScript to buffer their data, but there are some caveats in the documentation I am not confident about. Any guideline please? -
Upload file Vue 3 and Django REST
I dont get if i work with request correctly, after upload all files is 1 KB and i cant open them. How to create correct file? If i save file as .doc i can see: ------WebKitFormBoundaryt3UjlK5SVq8hgppA Content-Disposition: form-data; name="file" [object FileList] ------WebKitFormBoundaryt3UjlK5SVq8hgppA-- So my functions to submit in js file: async submitFiles() { let formData = new FormData(); formData.append('file', this.file); console.log(this.file) axios.put(`/api/v1/myapp/upload/${this.file[0].name}`, formData, { headers: { 'Content-Disposition': 'attachment', 'X-CSRFToken': await this.getCsrfToken(), }, } ).then(function () { console.log('SUCCESS!!'); }) .catch(function () { console.log('FAILURE!!'); }); }, To handle change of file in form fileChanged(file) { this.file = file.target.files }, And finally my view.py class FileUploadView(APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] handle_uploaded_file(file_obj) return Response({'received data': request}) Where def handle_uploaded_file(f): with open('path/to/my/folder/' + str(f.name), 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) -
My django objects get affected when I commit changes in heroku with git
My django admin panel objects get affected when I commit changes in git for my heroku website. I commit changes to my heroku website from following command in terminal - git add . git commit -am "make it better" git push heroku master before committing when I add new model - This is the image of the newly added object in django admin panel after committing changes it disappeared - image after committing changes Is there any solution for that committing changes does not affect these objects in django admin panel ? -
django autocomplete light can't input string
i've tried using django-autocomplete-light with following the docs guide, and in the end i cannot input string to search the data, here the picture I can't input string to search data. heres my code: views.py from django.shortcuts import render from .models import * from .forms import PendaftaranForm from dal import autocomplete # Create your views here. class DesaAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! #if not self.request.user.is_authenticated: #return Country.objects.none() qs = Desa.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs models.py class Desa(models.Model): nama = models.CharField(max_length=30) kecamatan = models.ForeignKey(Kecamatan, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.nama urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index, name='index'), url( r'^desa-autocomplete/$', views.DesaAutocomplete.as_view(), name='desa-autocomplete', ), ] forms.py from django import forms from .models import * from tempus_dominus.widgets import DatePicker from dal import autocomplete class PendaftaranForm(forms.ModelForm): class Meta: model=Pendaftaran fields= ( 'tanggal_pendaftaran', 'nama', 'desa', 'kecamatan', 'mutasi', 'jumlah', 'keterangan', 'tanggal_selesai', ) widgets = { 'tanggal_pendaftaran':DatePicker( attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ), 'nama':forms.TextInput( attrs={ 'class':'form-control', } ), 'desa':autocomplete.ModelSelect2( url='desa-autocomplete', attrs={ 'class':'form-control', } ), ... how can i input the string to search? is there anything wrong with my code? … -
Django Failed to load css
I have installed Geonode ( geospatial content management system), which is available on URL armsis.cas.am. It worked fine, but now there is a problem with CSS. I get an error GET http://armsis.cas.am/static/geonode/css/base.css net::ERR_ABORTED 403 (Forbidden) I thought the problem was in the path to static folder, but I get images from the same folder. Any ideas? ('m not a programmer, but I have some skills in Python/Web) -
Django verbose_name of reverse relation
I have a model like: class Question(models.Model): ... class Answer(models.Model): question = models.ForeignKey( Question, null=False, blank=False, on_delete=models.CASCADE, related_name='answers', verbose_name='translated name' ) I would now like to use the verbose_name in a template (as it is translated) over the reverse relation like {{ question.answers.verbose_name }}. Unfortunately this does not work. On the other hand {{ question.answers.related_name }} works. So it seems that in the reverse_relation only the related_name is available. Is there any way to get the verbose_name from the reverse relation? -
.mp4 file is not playing in Django template and FireFox or Chrome
I can save live RTSP video stream in .mp4 but when I run saved .mp4 video in Django template or Firefox or Chrome browser or VLC, video is not playing in ubuntu. I think I have a compatible issue problem in .mp4. Furthermore, I want to show and play .mp4 saved file in Django. I have a two IP camera which provides a live RTSP video stream. self.input_stream---> rtsp://admin:Admin123@192.168.1.208/user=admin_password=Admin123_channel=0channel_number_stream=0.sdp self.input_stream---> rtsp://Admin:@192.168.1.209/user=Admin_password=_channel=0channel_number_stream=0.sdp Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linux, Django==3.1.2 I am implementing this code in difference Ubuntu PCs Ubuntu = 18.04 and 20.04 opencv-contrib-python==4.4.0.46 opencv-python==4.4.0.46 ffmpeg version 4.2.4-1ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-10ubuntu2) I had tried different fourcc to save .mp4 but below fourcc work perfectly in Ubuntu. fourcc = cv2.VideoWriter_fourcc(*'mp4v') class ffmpegStratStreaming(threading.Thread): def __init__(self, input_stream=None, output_stream=None, camera=None, *args, **kwargs): self.input_stream = input_stream self.output_stream = output_stream self.camera = camera super().__init__(*args, **kwargs) def run(self): try:vs = cv2.VideoCapture(self.input_stream) fps_rate = int(vs.get(cv2.CAP_PROP_FPS)) ############################## ############################## # ~ print('fps rate-->', fps_rate,'camera id-->' ,str(self.camera.id)) # ~ vs.set(cv2.CAP_PROP_POS_FRAMES,50) #Set the frame number to be obtained # ~ print('fps rate-->', fps_rate,'camera id-->' ,str(self.camera.id),' ####### ') # initialize the video writer (we'll instantiate later if need be) writer … -
Different CMDs - difference for Python
I am a Windows10 user learning Django. And I am trying to run a server on my local device. While using the PyCharm command prompt, I constanly got some errors. A previous one, for example, was caused by SSLError (error was fixed thanks to Stackoverflow answers). Currently while doing the "runserver" command I am getting a new error: ImportError: DLL load failed while importing _sqlite3: module not found. At the same time there were and there still are absolutely no errors shown while using same django commands, but in Anaconda prompt. Why is that so? What's the difference between prompts? How to make the PyCharm command prompt work normally? "Anaconda3", "Anaconda3\scripts" and "Anaconda3\Library\bin" have been added to my PATH already. (According to answers found among Stakoveerflow, adding them is the number one solution / advice). Thank you! -
how to handle multiple keyword parameters in Django RestFramework URL
this my current url url("sample/userid",views.sample) I can query the data by userid or postid or x, or y parameters. how to handle this efficiently in a single url In the views, I will use kwargs to get the keywords, but not sure how to handle it in the url. -
Django ORM update field to NOW() returning 0 error
I am trying to loop through a list of results, process them, then update their "updated_details" field. users_to_update = TiktokUser.objects.filter(Q(updated_details__lt=datetime.utcnow() - timedelta(weeks=1)) | Q(updated_details__isnull=True))[0:1] for user_to_update in users_to_update: print(datetime.now()) user_to_update.updated_details = datetime.now() user_to_update.save() The idea being that on each loop, i set the updated_details to the current timestamp. My print() statement here correctly prints out the current date and time, however when I update the record itself and save, I get the following error: ['“0000-00-00 00:00:00.000000” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time.'] Which implies to me it is attempting to set it to 0. My model definition is: class User(models.Model): ... updated_details = models.DateTimeField(blank=True, null=True) ... How do I get Django to set the field to the current DateTime? -
Djnago background task function not excecuting
I am using Django background task in my project. pip install django-background-task and Django background task is started by cron-jobs But background task function is not executing all the time.. in the database entry is automatically generating in background_task and background_task_completedtask table. but my functionality is not executing. could any one check ? I am stuck here and not able to do other data. my code is showing below views.py @api_view(['DELETE']) @permission_classes([IsAuthenticated]) def remove_finger(request): try: validation_msg = '' employee = Employee.objects.get(pk=request.query_params.get("EmployeeId")) finger_data = FingerPrintInfo.objects.filter(Activation=request.query_params.get("FingerId"), Employee=request.query_params.get("EmployeeId")) if not finger_data: validation_msg = validation["FDP7"] if validation_msg != '': return Response({msg: validation_msg}, status=status.HTTP_400_BAD_REQUEST) else: fing = finger_data.order_by('FingerPrintId') fingerId = fing[3].FingerPrintId finger_data.delete() FingerPrintActivation.objects.filter(pk=request.query_params.get("FingerId")).update( ActivationStatus=progress_msg["removed"], ActivationMessage=validation["FDP31"], ModifiedDate=date.today(), ModifiedUser=request.user.id ) remove_fingerprint(request.query_params.get("EmployeeId"), fingerId) return Response({msg: successMsg}, status=status.HTTP_200_OK) my tasks.py @background(schedule=django.utils.timezone.now()) def remove_fingerprint(empId, fingerId): """ Remove FingerPrint data from all Device Parameters: EmployeeId: FingerPrint Data Returns: Background Process Execute """ try: json_input = { "EmployeeID": empId, "FingerPrintID": fingerId } employee = Employee.objects.get(EmployeeId=empId) if employee.Security == static_values["const1"]: emp_device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"])) else: emp_device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"]), DefaultAccess=True) for div in emp_device: try: url = "http://"+ div.DeviceCode + "/DeleteFingerprint" resp = requests.post(url, json=json_input) if not resp.text.__contains__('200'): logging.getLogger("info_logger").info("Fingerprint not removed from in " + div.DeviceCode) except Exception as ex: logging.getLogger("info_logger").info("Fingerprint not removed from in … -
Update specific ORM object with self object attribute from filtered queryset
I'm wondering is there any option to update current ORM object from filtered queryset with a new value which comes from current object? Seems bit complicated so maybe I show you an example: Model looks like: class Car(models.Model): car_id = models.CharField(max_length=100) initial_value = models.IntegerField(null=True) end_value = models.IntegerField(null=True) And some cars in my DB have initial_value but doesn't have an end value, and I want to copy/update the initial_value from specific object to end_value, where end_value is None: And I know that there exists an ORM formula which update my object with given value in queryset: Car.objects.filter(end_value__isnull=True).update(end_value=100000) But I cannot pass object initial_value to end_value in update method Car.objects.filter(end_value__isnull=True).update(end_value=initial_value) <-- Error Please help, how can I pass object attribute to update attribute? Maybe there is different approach? -
django admin sort calculated fields in listview
I have two models, one (Device) which has a foreign key to the other (Storage). In the admin overview of Storage I wanna be able to add a count of how many Device has pointed to each Storage. Using the code below I'm able to correctly count the number of Devices pointing to each Storage. However, when trying to sort by the number in storage it crashes with the following error. Cannot resolve keyword '_get_device_number' into field. Choices are: ... #List of fields So my question is, how do I add my calculated field into the list allowed searches. class Device(models.Model): ... storage_id = models.ForeignKey(Storage, on_delete=models.PROTECT, blank=True,null=True) #Allowed to be null since a Device may not be in storage. class Storage(models.Model): ... def _get_device_number(self,): return Device.objects.filter(storage_id=self.storage_id).count() class StorageAdmin(admin.ModelAdmin): ... list_display = ['str', 'get_device_number',] def get_device_number(self, obj): return obj._get_device_number() get_device_number.admin_order_field = '_get_device_number'