Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get single object with Django ORM with lazy evaluation?
I have a wrapper class which I want that some of its fields evaluate lazy, so it hit database when that field called. I use queryset for fields that contain a list. But I don't know how can I achieve this for fields that have single object. Because if I use objects.get() or .first() at the end of queryset it will be evaluated immediately. -
NSQ: how can i check content of deferred or requeued messages in nsq
NSQ deferred or requeued messages How NSQ manage deferred or requeued message and how can I check the actual content of this message is there any way check either with admin UI or with console -
How to modify multiple objects with same values in certain fields?
I have this model: class Connection(models.Model): CONNECTION_CHOICES = [ ('REST-API', 'REST-API'), ('SSH', 'SSH'), ('SFTP', 'SFTP'), ('SOAP-API', 'SOAP-API'), ] endpoint = models.CharField(max_length=240, blank=True, null=True) port = models.IntegerField(blank=True, null=True) connection_type = models.CharField(max_length=240, choices=CONNECTION_CHOICES) source_tool = models.ForeignKey(Tool, on_delete=models.CASCADE, related_name='source-tool+') target_tool = models.ForeignKey(Tool, on_delete=models.CASCADE, related_name='target-tool+') def __str__(self): return self.source_tool.name + " to " + self.target_tool.name def get_absolute_url(self): return reverse('tools:connection-detail', kwargs={'pk': self.pk}) In a view, I am trying to combine objects, where source_tool and target_tool are the same, but the connection_type differs. Currently, I have this view: def api_map_view(request): json = {} nodes = [] links = [] connections = Connection.objects.all() for connection in connections: if {'name': connection.source_tool.name, 'id': connection.source_tool.id} not in nodes: nodes.append({'name': connection.source_tool.name, 'id': connection.source_tool.id}) if {'name': connection.target_tool.name, 'id': connection.target_tool.id} not in nodes: nodes.append({'name': connection.target_tool.name, 'id': connection.target_tool.id}) if {'source': connection.source_tool.id, 'target': connection.target_tool.id} in links: links.replace({'source': connection.source_tool.id, 'target': connection.target_tool.id, 'type': links['type'] + '/' + connection_type}) else: links.append({'source': connection.source_tool.id, 'target': connection.target_tool.id, 'type': connection.connection_type}) json['nodes'] = nodes json['links'] = links print(json) return JsonResponse(data=json) This returns me e.g. { 'nodes': [ {'name': 'Ansible', 'id': 1 }, {'name': 'Terraform', 'id': 2}, {'name': 'Foreman', 'id': 3} ], 'links': [ {'source': 1, 'target': 2, 'type': 'SSH'}, {'source': 2, 'target': 3, 'type': 'REST-API'} {'source': 1, 'target': 2, 'type': 'REST-API'} ] } … -
Is there a way to update an object's specific field using an api in django?
Apologies if my question seems a bit basic, or too complicated, but I'm still learning django. What I'd like to do is somehow update a model object's field, preferably using an api call. I'll try to demonstrate. I have several different model objects that look like this. class Quarterback(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=20, blank=True) score = models.IntegerField(blank=True, null=True) I'd like to know if it's possible to populate the "score" field with data pulled via an api url. Of course, I can populate the score manually, or with an event listener like onclick, but because scores are dynamic and change every week, I'd really like to find a way to have the score field populate via the api because their data updates each week. At the moment, I'm displaying individual scores in my html by comparing the player's name in the model shown above with a list of names and scores stored in a variable that gets its info from the api. If I could somehow get the "score" field of this model to get its info from the url/api, I could just iterate through the object and display the score very easily. Even if this is … -
Mapbox Leaflet Marker Cluster in Django
I have used Mapbox for my Django project and I add a Cluster marker to the map, now I want to add more info to the popup for each marker like title form my django database any one have any idea haw i can add information to this code I used my code like this: L.mapbox.accessToken = mapkey; var map = L.mapbox.map('map') .setView([37.82, 22.215], 4) .addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11')); var markers = new L.MarkerClusterGroup(); var addressPoints = [ {% for r in resto %} {{ r.terrain|tuple_to_array }}, {% endfor %} ]; //console.log(addressPoints); for (var i = 0; i < addressPoints.length; i++) { var a = addressPoints[i]; var info = a[2]; var marker = L.marker(new L.LatLng(a[1], a[0]), { icon: L.mapbox.marker.icon({'marker-symbol': 'restaurant', 'marker-color': 'f86767'}), title: info }); marker.bindPopup(info); markers.addLayer(marker); console.log(a) } map.addLayer(markers); -
Appending formdata is not working properly
Here I made an array from the images inside the ul tag and append in the formdata.console.log(files,'files') this data gives me the in this format ["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD…7uefxPcmWZ5CBgF2LED05rw89q9TDRXsovvr95NS6la+2h//Z", "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD…/qGldWDfsQAKCg/5nKrPVXMM0eq6v/DigKQAKCg//AIr/AP/Z"] I appended this array to the input file with name image[]. Now when I try to get the images in the django view with request.GET.getlist('image[]') it only returns the last selected image. I think the appends is not working here. js var formdata = new FormData($('#form-id')[0]); var imgArray = []; $('#blah li .image #ig').each(function(){ imgArray.push($(this).attr('src')); }); var files = imgArray; for (var i = 0; i < files.length; i++) { formdata.append('image[]', files[i]); } console.log(files,'files') var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value; $.ajax({ url: ' {% url 'add' %}', type: 'POST', beforeSend: function(xhr, settings){ xhr.setRequestHeader("X-CSRFToken", csrftoken); }, data: formdata, cache: false, contentType: false, processData: false, enctype: 'multipart/form-data', success: function(data) { window.location.href = "/" } }); }); html <ul class="list list-inline list--image" id="blah"> <li class="selected"> <div class="image"> <img id="thumbnail" src="" width="83" height="100"/> </div></li> <div class="files--upload"><input class="d-none imgUpload" name="image[]" multiple type="file" id="imgInp" placeholder=""/><label class="upload-label" for="imgInp"> <div class="ic-add"></div> <div class="mt-2">Add Photo</div> -
Getting this error UNIQUE constraint failed: store_order.id
Whenever i try to update an order I get this error, Here is my model: CHOICES = ( ('Pending', 'Pending'), ('Processing', 'Processing'), ('Picked', 'Picked'), ('Shipped', 'Shipped'), ('Completed', 'Completed'), ) class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.CharField( max_length=100, blank=True, null=True, default="Unpaid", unique=True) order_status = models.CharField( max_length=100, choices=CHOICES, null=True, blank=True, default="In Review") payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) def save(self, *args, **kwargs): self.total = self.quantity * self.price return super().save(self, *args, **kwargs) I don't know why I am getting this kind of error can someone please explain why I am getting its error and how can I solve this issue. Here is my order view: class Checkout(View): def post(self, request): fname = request.POST.get('fname') phone = request.POST.get('phone') address = request.POST.get('address') cart = request.session.get('cart') customer = request.session.get('customer') products = Product.get_products_id(list(cart.keys())) for product in products: order = Order(customer=Customer(id=customer['id']), product=product, fname=fname, price=product.price, phone=phone, address=address, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect('user_orders') -
check if object in ManyToMany field django rest framework
here is my models.py: class Post(models.Model): id = models.AutoField(primary_key=True) body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') class Meta: ordering = ['-date'] serializers.py: class PostSerializer(serializers.ModelSerializer): user = UserSerializers() total_likes = serializers.SerializerMethodField() total_comments = serializers.SerializerMethodField() class Meta: model = Post fields = ('id','body','date','user','total_likes','total_comments') def get_total_likes(self, instance): return instance.liked_by.count() def get_total_comments(self, instance): return instance.comment_set.count() Q1: how do i check if a user exists in ManyToManyField of a single post? Q2: shouldn't i use ManyToManyField in drf? then which would be better? -
Django - Retrieve all FK as objects
Can I retrieve from my watchlist all the books directly so I can work with them? Like, same as if I did Book.objects.all(). So instead of getting Wachlist querySet (with pk, user, book, date_added) I just get the books. class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True, null=True, blank=True) -
Is there any way to run many functions in a django view?
I have written a view function that converts CSV files as well as count the no of lines in CSV files. views.py def submit(request): csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding='ascii', errors='replace') def file_conversion(input_file): #conversion work def total_lines(input_file): return sum(1 for line in input_file) file_conversion(csv_file) total = total_lines(csv_file) In this only ,file_conversion is working as while total is returning 0, If I switch the position of the functions, throws exception. Is there any way to run both functions? -
Django changing models field into views
I everyone, I have a problem with a django's view. My goal is to change the 'execute' field into 'True' if newOrder is buy and there is some other sell order with a inferior price. And reverse for sell newOrders. I want to change the 'execute' field for the newOrder and also for the other order (in pairs). That's my code: views.py def order(request): form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): new_order = form.save() if new_order.buy is True: sellOrder = Order.objects.filter(sell=True, execute=False, price__lte=new_order.price).first().update(execute=True) new_order.execute = True sellOrder.save() else: buyOrder = Order.objects.filter(buy=True, execute=False,price__gte=new_order.price).first().update(execute=True) new_order.execute = True buyOrder.save() new_order.profile = request.user new_order.save() return redirect('home') else: form = OrderForm() contex = {'form': form} return render(request, 'app/new_order.html', contex) models.py class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) wallet = models.FloatField() class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(User, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) buy = models.BooleanField(blank=True) sell = models.BooleanField(blank=True) price = models.FloatField() quantity = models.FloatField() execute = models.BooleanField(blank=True) But something goes wrong. This is the error: AttributeError at /new_order/ 'NoneType' object has no attribute 'update' -
Hello could someone please tell me what I'm doing wrong the path is not being detected
path('product-accordion.html/< slug>/', ProductDetailView.as_view(), name='prod') - I think there is a syntax error here could someone help -
Django channels update event status on fullcalendar
I am searching if is possible to update status on events in fullcalendar Javascript plug in with Django channels in real time, I don't find anything about this, I am lost in this task, can you point me in the right direction? Thanks. -
Pagination with variable page and size Django
I tried to create a pagination api without a html file (only for the backend) and woth size and page as variables. urls.py urlpatterns= [path('api/units?page=<int:page>&size=<int:size>/', ListingsView.as_view()),] views.py class ListingsView(self,request): http_method_names = ['get'] permission_classes = (permissions.IsAuthenticated,) serializer_class = ListingsSerializers def get(request, page_num=1, units_perPpage=16): units = Unit.objects.all() units_per_page = request.GET.get('size') unit_paginator = Paginator(units, units_per_page) page_num = request.GET.get('page') page = unit_paginator.get_page(page_num) return JsonResponse({ 'totalPages': unit_paginator.count(), 'itemsCount': units.count(), 'units': page, }, status=200) However the url doesn't even get resolved. Any suggestions? -
Application error while deploying on heroku
I'm following django for beginners by william vincent and i followed every step carefully and in the end while deploying my pages app on heroku, i see this application error. Please guide me, I'm a beginner in programming.here in the image you can see application error -
Template does not exist in django 3.1.3 version
Am using django 3.1.3 version and am quite to this framework. On running the server am getting template does not exist, i tried all the possible solutions provided by statckoverflow but to no avail. -
how to download records into .xls file from according to Change in django filter
I have a Django web app where users can see table data and I am using django_filters to see data according to shift Time(Morning/Evening/General). It is working fine and just wanted to know how to implement download functionality into .xls format for the filter result(now I am downloading all records). filter.py import django_filters class ShiftChangeFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = ShiftChange fields = ['ConnectID', 'EmailID','id','SerialNumber','Project_name','Shift_timing'] My code to download all records(which I want it to work based on filter e.g if user select General shift then all filtered result should get downloaded). views.py from django.utils import timezone now_aware = timezone.now() import xlwt,openpyxl def exportgenesys_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Genesys_ShiftTiming.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('GenesysShiftChange Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['id','ConnectID','Shift_timing','EmailID','Vendor_Company','Project_name','SerialNumber','Reason','last_updated_time'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = ShiftChange.objects.all().values_list('id','ConnectID','Shift_timing','EmailID','Vendor_Company','Project_name','SerialNumber','Reason','last_updated_time') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response One thing which I have tried is as below but I … -
Search Serialized for table using django and javascript
I want to extract the data from the serialized data into my table in my webpage using ajax and javascript. But my data are not being pulled to the table. how should I pull the two array in a serialized data into my table. Sample look of the output: column1 column2 column3 column4 column5 column6 column7 column8 column9 12-abc sal 113 113 113 113 113 113 113 tree 113 113 113 113 113 113 113 pal 113 113 113 113 113 113 113 tot 113 113 113 113 113 113 113 14-xyz ...n . . . n views.py: @api_view(['GET']) def get_processedoutputs(request): major_cd = request.query_params.get('major_cd', None) processedoutputs = ProcessedOutputs.objects.all() p_majors = ProcessedOutputs.objects.only('major_cd') majors = Major.objects.only('description').filter(major_cd__in=p_majors.values_list('major_cd', flat=True)).distinct().order_by("pk") if major_cd: processedoutputs = processedoutputs.filter(major_cd=major_cd) majors = majors.filter(major_cd=major_cd) if processedoutputs: serialized_p = ProcessedOutputsSerializer(processedoutputs, many=True) serialized_m = MajorSerializer(majors, many=True) newdict={ 'serialized_p': serialized_p.data, 'serialized_m': serialized_m.data, } return Response(newdict) else: return Response({}) processedoutputs.js: $.ajax({ method: 'GET', url: 'api/get_processedoutputs', beforeSend: function() { console.log('before send'); }, success: function(result) { update_table(result); console.log('after send'); }, error: function() { console.log('error'); } }); function find_majorcd() { let majorcd = document.getElementById('major_cd').value; let param = 'major_cd=' + majorcd; send_request(param); } function send_request(param) { $.ajax({ method: 'GET', url: 'api/get_processedoutputs?' + param, beforeSend: function() { console.log('before send'); }, … -
customize simple JWT functionality in DRF
I'm using JWT in my DRF project for authentication. I want to implement a logout view and I want to store user refresh token in my Redis DB for one day but my problem is that I don't know how simple jwt, generate a new access token using the refresh token. because I want to check the user refresh token before generating a new access token for the user. -
Django with Docker stuck on "Watching for file changes with StatReloader"
This is my code https://imgur.com/A49j4Dd When I run "python manage.py runserver 0.0.0.0:8000" it works perfectly fine. But when I use docker with "make compose-start" it doesnt work. Im trying to follow a python tutorial and cannot progress without fixing this. It just hangs there. https://imgur.com/fiujufu What do I do? Is something wrong? Anything else I could screenshot to help? -
TypeError: string indices must be integers error while uploading images
Here I have an array of image which I want to get in the django view and create each image object with every image. But I encounter this error TypeError: string indices must be integer view formdata = request.POST files = base64.decodestring(json.dumps(formdata)['files']) print('files',files) for file in files: Image.objects.create(img=file) template I have this array of files ["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD…/qGldWDfsQAKCg/5nKrPVXMM0eq6v/DigKQAKCg//AIr/AP/Z", "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…QF9qQZ7Hiiii4h2Tjrz796YSQQCaKKXUbEyc0oAx1NFFMR//Z", "data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAYABgAAD…tQEbmJcBs9Uxg8LzjFaQlGpdr5dv+HO3E0amEdndbfd1Z/9k="] "files -
How to indexing JSONField inside NestedField in Django using django_elasticsearch_dsl?
I have user model and comment, I am using django_elasticsearch_dsl to index in ElasticSearch # models.py class Comment(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) reply_type = models.JSONField(default=dict) Indexing to elastic I am doing it like this # documents.py @registry.register_document class UserDocument(Document): email = fields.TextField() username = fields.TextField() first_name = fields.TextField() ... ... ... comment = fields.NestedField(properties={ # other fields... 'some_field': fields.TextField(), 'reply_type': fields.ObjectField(), }) class Index: name = 'user' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = User The problem is that when I do the indexing the reply_type is empty "reply_type": [ { }, { } ] Any suggestion? -
new post gets inserted with other Post.. when i post, a separate box should be formed automatically for that perticular post. in django,html,css
1. css <style> li{ list-style-type: none; } </style> <style> *{ padding: 0; margin: 0; } h1{ font-size: 4vw; color: aqua; font-family: 'Lobster', cursive; position: relative; top: .8vw; left: .5vw; } h1 span{ color: yellow; } ul li a{ text-decoration: none; color: aqua; padding: .3vw; font-family: 'Hammersmith One', sans-serif; font-size: 2vw; } ul li a:hover{ color: yellow; } .nav li{ display: inline-block; position: relative; left: 65vw; bottom: 2.5vw; } .navbar{ background-color: #141526; height: 7.2vw; border-bottom: .5vw aqua solid; } body{ background-color:#090c12; } .main_body{ border: .5vw yellow solid; height: auto; width: 70vw; border-radius: 2vw; margin-left: 2vw; padding: 3.5vw; padding-top: 12vw; padding-bottom: 5vw; overflow: hidden; } .main_body ul li{ color: white; font-family: 'Poppins', sans-serif; position: relative; bottom: 6vw; font-size: 3vw; } #title{ font-size: 4vw; position: relative; bottom: 9vw; color: red; text-decoration: underline; font-family: 'Poppins', sans-serif; } #author{ font-size: 5vw; position: relative; bottom: 10vw; font-family: 'Poppins', sans-serif; color: white; } #delete{ position: relative; top: -3vw; text-decoration: none; background: red; color: black; font-size: 3vw; border-radius: .8vw; padding: .2vw; border: .2vw red solid; font-family: 'Hammersmith One', sans-serif; } #update{ position: relative; top: -3vw; left: .5vw; text-decoration: none; background: greenyellow; color: black; font-size: 3vw; border-radius: .8vw; padding: .2vw; border: .2vw greenyellow solid; font-family: 'Hammersmith One', sans-serif; } … -
Django: Is it possible to initialize an empty form (from formset) in template with a set prefix (other than __prefix__)?
I am using a model formset and adding new forms dynamically to it with {{ formset.empty_form }}. The thing is that I am also using django-ckeditor's RichTextField for one of the fields and, when I add a new form, the editor is not initialized for it. I can type in the text area, but I can't do anything with the editor. I have been told that django-ckeditor is not activated for new forms that are initialized with __prefix__ instead of a new form index. I can change the prefix after I get the new form, but it has already been initialized with __prefix__. The documentation doesn't seem to say much about this. I have also been told that I can change some javascript so django-ckeditor is activated for these newly added forms with __prefix__, but I'm a bit lost there and don't know which or where. So, if I can change this, I think I'll get the editor activated for these forms. -
How to get the latest file of an S3 bucket using Boto3?
I'm trying to get last added file in S3 specific folder. and I refer this(How to download the latest file of an S3 bucket using Boto3?) post and try. @api_view(("GET",)) def get_protocol(request, pk): union = Union.objects.get(pk=pk) s3 = get_s3_client() filepath = "media/private/" + str(pk) + "/certificate/docx" get_last_modified = lambda obj: int(obj["LastModified"].strftime("%s")) objs = s3.list_objects_v2( Bucket="unifolio", Prefix=filepath + "/" + "Union" + str(pk) + "_" + "certificate" + "3", ) last_added = [obj["Key"] for obj in sorted(objs, key=get_last_modified)][0] url = s3.generate_presigned_url( ClientMethod="get_object", Params={"Bucket": "unifolio", "Key": last_added}, # url 생성 후 60초가 지나면 접근 불가 ExpiresIn=60, ) return Response() but the error occur like below: File "/Users/kimdoehoon/project/unifolio/unions/api_views.py", line 199, in get_protocol objs_sorted = [obj["Key"] for obj in sorted(objs, key=get_last_modified)] File "/Users/kimdoehoon/project/unifolio/unions/api_views.py", line 194, in <lambda> get_last_modified = lambda obj: int(obj["LastModified"].strftime("%s")) TypeError: string indices must be integers I don't recognize why indices must be integer error. Could anybody kindly help me?