Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django path in boutton page not found
button Update urls path('devices/', views.devices, name='devices'), path('update_device/str:pk/', views.update_device, name='update_device'), views @login_required(login_url='login') def update_device(request, pk): device = Device.objects.get(id=pk) form = Adevice(instance=device) context = {'form':form} return render(request, 'accounts/device.html', context) #ajouter device @login_required(login_url='login') def device(request): form = Adevice() if request.method == 'POST': form = Adevice(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'accounts/device.html', context) -
How to enable the ltree extension on google cloud sql
First of al: ltree is a postgres plugin, which seems to be officially supported by google (see GCP PostgreSQL extensions) In the same documentation I read that you need to enable the extension first (like on a normal postgres database). My backend application is written in the django framework and I basically instruct it to run the following command, which works without hick ups on my local machine: CREATE EXTENSION IF NOT EXISTS ltree; However, when I run that migration, I get the following error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.InsufficientPrivilege: permission denied to create extension "ltree" HINT: Must be superuser to create this extension. This makes sense since according to the documentation, "the postgres user must be part of the cloudsqlsuperuser role". However, I see no way to give my user that role. I tried the default postgres user, which according to the documentation page above should be configured correctly, but it basically does not work. When I dig deeper in the cloudsql documentation, I read something even more surprising: it does not seem to be possible to create superusers according to this documentation. So, the question is quite simple: How … -
Djoser not sending emails when default emails are overridden
I have a DRF project that uses Djoser for authentication. The plan is to override Djoser's default activation email and send something an HTML template email. Here's what I have: # settings.py DJOSER = { "SEND_ACTIVATION_EMAIL": True, "ACTIVATION_URL": "activate/{uid}/{token}", "EMAIL": {"activation": "base.emails.ActivationEmail"}, } # base/emails from django.contrib.auth.tokens import default_token_generator from djoser import email, utils from djoser.conf import settings class ActivationEmail(email.ActivationEmail): template_name = "emails/activation.html" def get_context_data(self): # ActivationEmail can be deleted context = super().get_context_data() user = context.get("user") context["first_name"] = user.first_name context["uid"] = utils.encode_uid(user.pk) context["token"] = default_token_generator.make_token(user) context["url"] = settings.ACTIVATION_URL.format(**context) return context # templates/emails/activation.html {% extends "emails/base.html" %} {% load static %} {% block subject %}Account Activation on Dummy{% endblock %} {% block heading %} Account Activation {% endblock %} {% block content %} You're receiving this email because you need to finish activation process. Please click on the button below to activate your account: <br><br><br> <a href="{{ url }}" target="_blank" style=" text-decoration: none; font-family: lato, 'helvetica neue', helvetica, arial, sans-serif; font-size: 20px; color: #fff; background-color: #0b913a; padding: 10px 25px; border-radius: 5px; " >Activate</a > <br><br><br> Best Regards,<br> The DUMMY Team <br><br> <p style=" margin: 0; -webkit-text-size-adjust: none; -ms-text-size-adjust: none; mso-line-height-rule: exactly; font-size: 14px; font-family: lato, 'helvetica neue', helvetica, arial, sans-serif; line-height: … -
Django extend base.html work on all pages but one
Today i tried to setup Django authentification on an app and it's working a 99%. The registration and login are working perfectly but i have a problem on the userprofile page. Registration, login and userprofile templates all have the extends base.html and it's working for the registration and login, but on the userprofile page i get an error saying that the source base.html can't be round. Strangest thing is that the path value that Django trie is the correct one, same as the other two templates. This is the structure of my templates folder : Templates Account Registration.html Login.html Userprofile.html Base Base.html Most of the post if have found about extend base error usualy incombe the extend not working at all or not working in one folder but working in the others where mine work for two templates out of 3 in the same folder. I tried to remove most of the code in my userprofile template to see if anything was messing with the extend but even there i get the same error. -
Django Content Management System
When I try to add a new data in CMS of Django. So I press the button, and then it shows me this. RuntimeError at /admin/booktest/bookinfo/add/ generator raised StopIteration Request Method: POST Request URL: http://../admin/booktest/bookinfo/add/ Django Version: 1.8.2 Exception Type: RuntimeError Exception Value: generator raised StopIteration Exception Location: C:\Users\Nitro5\Desktop\pyango\lib\site-packages\django\http\multipartparser.py in read, line 337 Python Executable: C:\Users\Nitro5\Desktop\pyango\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\Nitro5\\Desktop\\pyango\\pyango\\test1', 'C:\\Users\\Nitro5\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Nitro5\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Nitro5\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Nitro5\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Nitro5\\Desktop\\pyango', 'C:\\Users\\Nitro5\\Desktop\\pyango\\lib\\site-packages'] And I went to the file 'multipartparser.py'. I tried to add 'try-except StopIteration'.But it didn't work. So....anyone can help? -
How to descrease SQL queries count generated by model method in Django?
I have model method that calculates object status using some data that is not "ForeignKey" from django.db import models class Product(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=20, null=True) def status(self): sales_data = Sale.objects.filter(some_string_parameter='goods', entity_ref=self.id).aggregate(Max('discount')).get('value') if not sales_data: return "No Sale" elif sales_data >= 50: return "Sale over 50%" elif sales_data < 50: return "Sale less than 50" I have a page with the product list (all products in the database) where I need to show its status. {% for product in products %} {{ product.name }} - {{ product.status }} {% endfor %} Each product.status generates extra SQL request. Is there any way to "prefetch" model method result for all objects in queryset? -
how to play a specific timestamp in a video file using django 3
I want to create a website similar to http://playphrase.me in this project the user searches for a word or phrase and then short video clips of that phrase being used in different movies and tv series is played for the user. In my views.py, i search srt subtitles for a keyword or phrase and then get the name, url path, and the timestamp during which a word or phrase is being said in a video file. I can send these info in a json or dict to template, my problem is how to play these files. I want my video player to start and stop playing a video at the specific timestamp that i provided. Please tell me which video player to use and how. -
How to save and run python function in HTML button?
Context: For a face recognition project, user should upload a selfie and that pic will be saved in a S3 bucket (AWS) so the final result will be a template with that selfie and the person who looks like you. So, I want a button that save the image uploaded by user and at the same time, run the face recognition function. template: <form method="post" enctype="multipart/form-data" id="upload-form" action="{% url 'erp:fibocal' %}"> <div class="card-footer"> <button type="submit" class="btn btn-primary btn-flat" onclick="showLoaderOnClick('{% url 'erp:fibocal' %}')"> <i class="fas fa-save"></i> ¡Encontrá tu parecido! </button> </div> </form> And that button don´t save the image in my s3 bucket, only runs "erp:fibocal" that is a function in views.py: def fibocal(request): if request.method == 'POST': img_loaded = request.FILES['image'] imagenes = FR(img_loaded) return render(request, 'base.html', {'name': imagenes[0], 'prct':imagenes[1]}) else: return render(request, 'home/register.html', {}) ``` I think that I should save the image at the "fibocal" function but I don´t know how. Thanks! -
AttributeError: 'ParsedRequirement' object has no attribute 'req' in PIP 21.1.1
I am currently upgrading a project from Django 2.1 to Django 2.2. In doing so, I have been getting the following error when doing pip install -r requirements.txt. Running command git clone -q git://github.com/user/djangocms-comments /tmp/pip-req-build-x00esn u5 ERROR: Command errored out with exit status 1: command: /home/user/miniconda3/envs/python-3.6-test-web/bin/python -c 'import io, o s, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-req-build-x00esnu5/setup.py'"'"'; __file__='" '"'/tmp/pip-req-build-x00esnu5/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if o s.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read ().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_i nfo --egg-base /tmp/pip-pip-egg-info-xm4vt9bf cwd: /tmp/pip-req-build-x00esnu5/ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-req-build-x00esnu5/setup.py", line 188, in <module> install_requires = [str(ir.req) for ir in requirements] File "/tmp/pip-req-build-x00esnu5/setup.py", line 188, in <listcomp> install_requires = [str(ir.req) for ir in requirements] AttributeError: 'ParsedRequirement' object has no attribute 'req' ---------------------------------------- It appears that the package djangocms_comments is outdated in how it uses pip. I have gathered that much by searching this site. However, I am unsure how to fix this. The error happens here. Any help or guidance would be appreciated. -
403 forbidden when accessing django admin folder
I found many threads about similar problems but nothing worked so far. I'm deploying a web app on production server using uwsgi and nginx. The backend is in Django, frontend in Vue.js. I want to access the Django admin panel. I ran python3 manage.py collectstatic, chown -R www-data:www-data /home/debian/public/static/ and made sure that rights are ok (rwx r-x r-x www-data:www-data for folders and www-data:www-data rw- r-- r-- for files). nginx.conf user www-data; ... location /admin/ { alias /home/debian/public/static/admin/; } When I try accessing the admin panel (https://my-site.com/admin/) I get a 403 forbidden from nginx. error.log from nginx directory index of "/home/debian/public/static/admin/" is forbidden, [...] However, if I go to https://my-site.com/admin/css/base.css, I can see the css file. Other unrelated static folders, such as swagger doc (using drf-yasg), work fine. If I add an index.html file in /home/debian/public/static/admin/, nginx serves the index.html file as expected. Any idea what am I missing ? -
why isn't the code inside head tag working when code inside body is working?
<!DOCTYPE html> <html> <head> {% if title %} <title> Django blog - {{title}} </title> {% else % } <title> Django blog </title> {% endif %} </head> <body> {% for post in posts %} <h1>{{post.title}}</h1> <p>By {{post.author}} on {{post.date_posted}} </p> <p>{{post.content}} </p> {% endfor %} </body> </html> When i run the code the head tag is empty and there is no title but the for loop executes to give the result i expected. -
CreateUser View returning IntegrityError on form submit
I have a CreateUser view that uses the generic CreateAPIView as a sign up view in the API I'm working on. I'm using a custom User model which uses the django.contrib.auth.models.AbstractUser model. On submitting the form (or sending data via a frontend), I'm getting an error, and I can't seem to find what I'm doing wrong. class UserSerializer(ModelSerializer): class Meta: model = User fields = ("username", "email", "password") extra_kwargs = {"password" : {"write_only" : True}} def create(self, validated_data): user = User.objects.create( email=validated_data["email"], username=validated_data["username"] ) user.set_password(validated_data["password"]) user.save() Token.objects.create(user=user) return user View. class CreateUser(CreateAPIView): serializer_class = UserSerializer permission_classes = () authentication_classes = () Error: "IntegrityError at /api/users/sign_up/ NOT NULL constraint failed: users_user.email -
Django rest framework merging two serializers data based on following requirement
I have two models one is Video which contains all the user uploaded details and other model is LikedVideo which contains details of liked videos by the user. Video model class Video(models.Model): """ All videos available for the users """ video = models.FileField(blank=True, default='') user = models.ForeignKey(User, related_name='user_videos', related_query_name='person', on_delete=models.SET_NULL, null=True) category = models.ForeignKey(VideoCategory, related_name='video_category', on_delete=models.SET_NULL, null=True) channel = models.ForeignKey(Channel, related_name='video_channel', on_delete=models.SET_NULL, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) deleted_at = models.DateTimeField(null=True) active = models.BooleanField(default=1) description = models.TextField(null=True) short_description = models.CharField(max_length=150, null=True) def __str__(self): return f"{self.user.username}_{self.category.video_type}_{self.channel.channel_name}" LikedVideo model class LikedVideo(models.Model): """ Contains all the liked videos by user """ video = models.ForeignKey(Video, related_name='video_liked', on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, related_name='user_liked', on_delete=models.SET_NULL, null=True) liked = models.BooleanField(default=0) def __str__(self): return f"{self.user.username}" VideoSerializer class VideoSerializer(ModelSerializer): uploaded_at = serializers.ReadOnlyField() class Meta: model = Video fields = ["id", "video", "category", "uploaded_at", "channel", "description", "short_description"] def to_representation(self, instance): rep = super(VideoSerializer, self).to_representation(instance) rep['category'] = instance.category.video_type rep['channel'] = instance.channel.channel_name return rep def validate_channel(self, value): print(self.context['request'].user) if Channel.objects.filter(user=self.context['request'].user, channel_name=value).exists(): return value raise serializers.ValidationError(_(f"Channel {value} does not belongs you. Please, enter a channel belongs to you")) LikedVideoSerializer class LikedVideoSerializer(serializers.ModelSerializer): class Meta: model = LikedVideo fields = ["id", "video", "liked", "user"] VideoListAPIView class VideoListAPIView(generics.ListAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer def list(self, request, format=None): … -
Showing same template for all url of an Django app
Here are the two views : from django.shortcuts import render from django.views import View from django.http import HttpResponse class sectionOfficer_home(View): def get(self, request, *args, **kwargs): return render(request, 'sectionofficer/UI/index.html', {}) class sectionOfficer_main(View): def get(self, request, *args, **kwargs): return render(request, 'sectionofficer/UI/404.html', {}) Here is my urls.py of the app sectionOfficer: from django.urls import path from .views import (sectionOfficer_home, sectionOfficer_main) app_name= 'sectionofficer' urlpatterns = [ path('', sectionOfficer_home.as_view(), name = "sectionofc"), path('secmain', sectionOfficer_main.as_view(), name = "sectionofc") ] And here is the global urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',views.home), path('students', views.dataViewer), path('sectionoffc', include('sectionofficer.urls')), path('secmain', include('sectionofficer.urls')), ] But it showing always the first view template for any different url. What is wrong here ? Help please. -
django.db.utils.IntegrityError: NOT NULL constraint failed: like model
I am getting django.db.utils.IntegrityError: NOT NULL constraint failed: feed_like.user_id on my model . How can i solve it my models.py class Like(models.Model): post = models.ForeignKey(Posts, related_name='likes', on_delete=models.CASCADE) user = models.ForeignKey(HNUsers, related_name='likes', on_delete=models.CASCADE) liked = models.BooleanField(default=False, blank=True, null=True) class Meta: verbose_name_plural = "Likes" my views.py @api_view(['GET', 'POST']) @permission_classes((permissions.AllowAny,)) @parser_classes([FormParser, MultiPartParser]) def like_post_api(request): if request.method == 'POST': data = request.data print(data) serializer = PostLikeSerializer(data=request.data) print("print ", serializer) post = Posts.objects.get(id=data['post']) print(post) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) my serializer.py class PostLikeSerializer(serializers.ModelSerializer): user = CommentUserSerializer(read_only=True, many=False) class Meta: model = Like fields = ( 'id', 'user', 'post', ) -
Django- How to get element index in a queryset by using F expression
I have following models: class Topic(models.Model): title = models.CharField(max_lenght=32) # Some other fields. class Thread(models.Model): topic = models.ForeignKey(Topic, related_name=threads', on_delete=models.CASCADE) # some other fields class Message(models.Model): thread = models.ForeignKey(Thread, related_name='messages', on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I want to calculate index of each element in each Thread, in the queryset by F(). For example If in the Thread 1 I have 5 messages, I want to messages have indexes as 1 to 5. my code doesn't work. code comes in the following: from django.models import Count, Q, F messages = Message.objects.all().annotate( index=Count('id', filter=Q(thread_id=F('thread_id'), created__lt=F('created'))) + 1 ) This return same index for all elements. For example this returns index=5 for all items in queryset. How can I calculate index of elements in the queryset? -
Django Rest: How to update fields of a foreign key object from the related object API endpoint
I have the following two models with a ForeignKey relationship: models.py class DataModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) name = models.CharField(max_length=1000,unique=True,) class DataPoint(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) name = models.TextField() unit = models.ForeignKey(Unit,related_name='+',on_delete=models.PROTECT) data_model = models.ForeignKey(DataModel,on_delete=models.PROTECT,related_name='data_points') With the following respective serializers serializers.py class DataPointSerializer(serializers.ModelSerializer): unit = serializers.CharField(source="unit.unique_key") class Meta: model = models.DataPoint fields = ['id', 'name', 'unit'] class DataModelSerializer(serializers.ModelSerializer): dataPoints = DataPointSerializer(source='data_points', many=True) class Meta: model = models.DataModel fields = ('id', 'name', 'dataPoints') read_only_fields = ('id',) Then I have an API endpoint /api/v1/data-models/ where I can GET all the DataModels and POST to create a new one. Then on api/v1/data-models/{id}, I can edit the name of the DataModel object or add more DataPoints by passing a name and unit. What I want to do now is through the api/v1/data-models/{id} endpoint, edit (PATCH) DataPoints that are already linked to the DataModel, so I can change their name or unit given it's id like so: { "dataPoints": [ { "id": "6eb3878d-ea5b-47b9-b9e5-7a606d3596ff", "name": "Test DataPoint", "unit": "V" } ] } views.py class DataModelViewSet(viewsets.ModelViewSet): queryset = models.DataModel.objects.all() serializer_class = DataModelSerializer permission_classes = (IsAuthenticated, ) def update(self, request, pk=None, **kwargs): dm = get_object_or_404(self.get_queryset(), pk=pk) serializer = self.serializer_class(dm, data=request.data, partial=True) if not serializer.is_valid(): return Response(serializer.errors, … -
django save method dosen't fire up post_save signal
I'm struggling with post_save signal with django model , my project works at first time with signals without any problems , now even the save() method save record to database without any exceptions ( save method without override), post_save signal are not triggered but when I used admin panel to save record the result is good all suggestions are welcomes -
Django - disable a system check for a specific management command
I have a circular problem with a system check in django: $ python manage.py search_index --rebuild -f SystemCheckError: System check identified some issues: ERRORS: {'search.documents.applications': 'entities'}: (search.E001) No elasticsearch index 'entities' exists HINT: Run `manage.py search_index --rebuild -f` to recreate then repopulate the indices. One workaround is to disable this check using system settings but I don't want to have to change system settings to disable it, deploy, run the rebuild, change back, redeploy every time I attach a different search index or flush elasticsearch. Is there a way of disabling this error (eg by overriding that setting) by passing something to the actual manage.py command? -
Render dropdown in django view using values from postgres arrayfield
Here is an example from the model: class Shipment(models.Model): shipment_id = models.BigAutoField(null=False, primary_key=True) potential_shipping_dates = ArrayField(models.DateField(), verbose_name='Ship Dates', null=True) Here is what I'm sort of attempting in my form: class ShippingForm(forms.Form): potential_shipping_dates = forms.ModelChoiceField(queryset=Shipment.objects.all()) def __init__(self, *args, **kwargs): super(ShippingForm, self).__init__(*args, **kwargs) And here is where my form is added to context: context['shippingForm'] = ShippingForm(initial=??what_goes_here_maybe??) My form renders fine but I want to show a dropdown with a date for each option. -
Django Full height template
I am trying to have all the templates to use the whole height of the browser page (using chrome) In my CSS body { min-height: 100vh; } Then in by base.html {% load static%} {% load custom_tags %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %}My Platform{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/base.css'%}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <div> <body> <nav class="navbar navbar-expand-lg nav3" > ....stuff.... </nav> <main> <div class="container"> {% block content %} {% endblock content %} </div> </main> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> </body> <div class="d-flex justify-content-between flex-wrap footerstyle" > <div> <i class="far fa-copyright"></i> All rights reserved by WozNot </div> <ul class="list-inline "> <li class="list-inline-item"><a href="{% url 'web_terms' %}" class="hidelink"> Terms & Conditions </a> | </li> <li class="list-inline-item "><a href="{% url 'web_privacy' %}" class="hidelink"> Privacy Policy </a>| </li> <li class="list-inline-item "><a href="{% url 'web_contact' %}" class="hidelink"> Contact Us</a> </li> </ul> </div> </div> </html> Unfortunately it looks like the min-height does not go across when the base … -
Django: MultiPartParser is skipped when uploaded file size > DATA_UPLOAD_MAX_MEMORY_SIZE
I have a view in my DRF app which accepts Content-type: multipart/form-data which I use to POST multiple files together, sample represents a binary file data is a string-yfied JSON. Code: from rest_framework.parsers import MultiPartParser from rest_framework.decorators import api_view, parser_classes class CustomMultiPartParser(MultiPartParser): def parse(self, stream, *args, **kwargs): print("----- inside MultiPartJSONParser ------") ## for debug req = super().parse(stream, *args, **kwargs) data_str = req.data.get("data", None) if data_str: parsed = json.loads(data_str) mutable_data = {"data": parsed} mutable_files = {} for key, value in req.files.items(): if key != "data": mutable_files[key] = value return parsers.DataAndFiles(mutable_data, mutable_files) return req @api_view(["POST"]) @parser_classes((CustomMultiPartParser,)) def my_view(request): print(type(request.data)) ## for debug serializer = CustomFileSerializer(data=request.data) # ...snip... When the sample POSTed to this endpoint is < 2.5 mb in size, the type(request.data) is dict whereas if file size > 2.5 mb, the type(request.data) is django's QueryDict. Logs: # file size < 2.5mb ----- inside MultiPartJSONParser ------ {'data': {'private': False}, 'sample': <InMemoryUploadedFile: pafish.exe (application/x-ms-dos-executable)>} # file size > 2.5mb <QueryDict: {'data': '[{"private": false}]', 'sample': [<TemporaryUploadedFile: wannacry.bin (application/octet-stream)>]}>> On debugging more, I find out that: The 2.5mb threshold is the django's DATA_UPLOAD_MAX_MEMORY_SIZE. When I set this variable to a higher value, the threshold becomes exactly that. the CustomMultiPartParser is skipped all-together in the second … -
Is there a better way to import load_model from tensorflow in a django web app?
I have deployed a keras model on a django app on a shared hosting environment. The model is working well. The problem is, it takes much time to load. From my experiment I have seen that it is taking time to excute: from tensorflow.keras.models import load_model This only occurs at the first page load. Is there any way to solve it? Thanks in advance. -
I'm having trouble looping through my dataset objects in django
<script src='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js'>></script> <link href='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css' rel='stylesheet' /> <form method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Submit Address"/> </form> <div id='map' style='width: 100%; height: 700px;'></div> <script> mapboxgl.accessToken = 'pk.eyJ1IjoiZHVueWFzYWlkIiwiYSI6ImNrb2FmNHA1czA2ZTAzMXBnYTBrZ253a3QifQ.7vcmfsekylXlTOnloBHpiA'; // var geocoder = new Google.maps.geocoder(); var map = new mapboxgl.Map({ container: 'map', // container ID style: 'mapbox://styles/mapbox/streets-v11', // style URL center: [17.6, 59.8], // starting position [lng, lat] zoom: 9 // starting zoom }); // Set options {% for task in qs %} console.log(qs) {% if task.address != '' %} var marker = new mapboxgl.Marker({ color: 'green', draggable: true }).setLngLat([task.long, task.lat]) .addTo(map); {% endif %} {% endfor %} views.py in the same app as the task def map(request, *args, **kwargs): qs = Task.objects.all() Address = request.GET.get('Address') if Address != None: qs = qs.by_Address(Address) return render(request, 'pages/map.html', qs) Model class class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tasks") #many users can have many tasks accepts = models.ManyToManyField(User, related_name = "task_user", blank = True, through = TaskAccept) title = models.TextField(blank = True, null = True) content = models.TextField(blank = True, null = True) image = models.FileField(upload_to= 'images/', blank = True, null = True) timestamp = models.DateTimeField(auto_now_add = True) completed = models.BooleanField(default=False) accepted_by = models.ManyToManyField(User, through = TaskAcceptedUsers , blank = True, related_name "accepted_by") Address = … -
LINE 1: ..." timestamp with time zone NOT NULL, "attributes" hstore NOT
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres dbi5k: image: postgres volumes: - ./data/dbi5k:/var/lib/postgresql/data environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } and $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_i5k', 'USER': 'django', 'PASSWORD': 'postgres', 'HOST': 'dbi5k', 'PORT': '5432', } } Please below the logs after I ran docker-compose build docker-compose up # I had to wait for 2 minutes and do CTRL+C in order to give the database to start docker-compose up …