Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django how to create a serializer ListField that accepts DictField with images values
As the title describes I need to create a Custom serializer ListField that accepts dictionary of string keys and value of Image Example input: [ {'1':FirstImage} , {'3',ThirdImage} ] What I've tried: customSerializer = serializers.ListField( child=serializers.DictField( child=serializers.ImageField(allow_empty_file=True, use_url=False) ) ) Obviously my serializer doesnt work as it should, anyone have an idea how can I make this work? Thanks In Advance -
How to successfully INCLUDE extra fields & UPDATE/DELETE existing fields(at a go) using either modelformset_factory/inlineformset_factory
i have my models ready, adding new products, that i have figured out, but including extra fields and updating/deleting this newly added field on one html form has been such a pain, the following are my exact codes with slight changes #my models.py class Product(models.Model): title = models.CharField() class ProductSpecification(models.Model): name = models.CharField() class ProductSpecificationValue(models.Model): product = models.ForeignKey(Product) specification = models.ForeignKey(ProductSpecification) value = models.CharField() class ProductImages(models.Model): product = models.ForeignKey(Product) images = models.ImageField(upload_to="images/uploads/") So here i will show my working code for ADDING new Product objects(just incase am doing it wrong, and it has anything to do with why updating part isn't working) #MY Adding product forms.py class AddNewProductForm(forms.ModelForm): title = forms.CharField() class Meta: model = Product fields = ['title',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs.update{'class': 'form-control'}) class AddNewProductSpecForm(forms.ModelForm): class Meta: model = ProductSpecificationValue fields = ['specification', 'value'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['specification'].widget.attrs.update({'class': 'form-control'}) self.fields['value'].widget.attrs.update({'class': 'form-control'}) class AddNewProductImgForm(forms.ModelForm): #this is to upload multiple img in bulk at one go images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = ProductImages fields = ['images',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['images'].widget.attrs.update({'class': 'form-control'}) #MY Adding product views.py @login_required def add_new_product(request): AddNewProductFormSet = modelformset_factory(ProductSpecificationValue, form=AddNewProductSpecForm, extra=3) if request.method == "POST": product_form = AddNewProductForm(request.POST, … -
Will ignoring this (ValueError: signal only works in main thread of the main interpreter) affect anything?
I have a Django server running, and when it receives the user's data, it runs a separate program in views.py After it has completed what I have wanted I receive this error both in the terminal and the host server: handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler)) ValueError: signal only works in main thread of the main interpreter So I decided to do: try: #code except ValueError: return redirect('home') Which works perfectly fine as it redirects to the homepage of my website. Will it affect my website in the future when multiple users use the website? -
Override Save Model Django
I would like to override the save model in Django, to ensure a check that my User doesn't follow himself/herself. I know I can do this using serializer and put a check in view but I want to learn how to override def save. class Followable(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) followers = models.ManyToManyField(User, related_name="users", null=True, blank=True) class Meta: abstract = True def save(self, *args, **kwargs): if self.user != self.followers: return ValidationError("User cannot follow oneself.") super(Followable, self).save(*args, **kwargs) I tried printing out *args and **kwargs but it is empty. Also, User is my custom User Model. -
Staticfiles won't serve in production for Django application in Heroku
I am new both to Django and to project-deployment. I have gone trough all of the files a million times now, and I still cannot find what went wrong. The website itself gets displayed, but without any CSS, images or JavaScript. I would really appreciate any help. Here is the settings file import os import sys from .cdn.conf import * import mimetypes mimetypes.add_type("text/css", ".css", True) BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] DEBUG = os.getenv("DEBUG", "False") == "True" DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True" ALLOWED_HOSTS = ['scienz.herokuapp.com'] INSTALLED_APPS = [ 'main.apps.MainConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'storages', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' ROOT_URLCONF = 'scienZ.urls' -
Why do I get this error in django when I run this command?
python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() in wrapper fn(*args, **kwargs) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\config.py", line 223, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'hellodjango' -
How to add comment on django site with ajax call and without refreshing?
On site exists form where users able to comment products. Comments are connected with products. Jqery is used from Boostrap base.html.(it's worked with another ajax-call) I'm fighting with ajax comment during the week) Trying to do it only for one product to understand how it works. Without ajax system of comments works fine, but I decided to add smooth in comment add without refreshing of the page and I do task with POST and ajax for the first time (before I did two pretty simple examples with get and form reset after succesfull response to ajax from back-end). Could somebody advice what should be add in template and view ? I suppose problem is connected with my poor knowledge of js. I'am using "is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'" cause this working with django 4.0, and old function is_ajax() was removed. views.py def ajax_test(request): product = Product.objects.get(id=4) comments = product.comment_set.order_by('-created_at') form = UserCommentForm context = {'product':product,'comments':comments,'form': form} return render(request, 'store/ajax_test.html', context) def ajax_receiver(request): is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if request.method == 'POST' and is_ajax: product = Product.objects.get(id=4) form = UserCommentForm(data=request.POST) user = Comment.objects.get(author=user) if form.is_valid() and request.user.is_authenticated: new_comment = form.save(commit=False) new_comment.author = request.user new_comment.product = product new_comment.save() comment_info = { "author": … -
making hash of data in django rest framework serializers
i want to making a SHA256 hash of some fields in my serializer and set it to another field in the same serializer, this is my model: class Something(models.Model): x = models.CharField(max_length=300) y = models.IntegerField() z = models.IntegerField() f = models.IntegerField() hash = models.CharField(max_length=300) first user defines x,y,z and f. after that i need to generate hash automaticly like this hash = x + y + z + f my serializer : class SomethingSerializers(serializers.ModelSerializer): class Meta: model = Something fields = ['x', 'y', 'z', 'f', 'hash'] what is the best decision? -
Push rejected, failed to compile python project - Django , Heroku
It is my first deployment, I am trying to push my django project into heroku but it is saying push rejected; failed to compile python project. i have tried changing the python lower versions but no luck. Any help would be much appreciated!! Thanks. Here, is my cmd output > (blog-rHhqYg-f) C:\projects\blog>git push heroku master > Enumerating objects: 72, done. > Counting objects: 100% (72/72), done. > Delta compression using up to 4 threads > Compressing objects: 100% (67/67), done. > Writing objects: 100% (72/72), 22.87 KiB | 2.86 MiB/s, done. > Total 72 (delta 25), reused 0 (delta 0), pack-reused 0 > remote: Compressing source files... done. > remote: Building source: > remote: > remote: -----> Building on the Heroku-20 stack > remote: -----> Determining which buildpack to use for this app > remote: -----> Python app detected > remote: -----> No Python version was specified. Using the buildpack default: pyt > hon-3.9.9 > remote: To use a different version, see: https://devcenter.heroku.com/art > icles/python-runtimes > remote: cp: cannot stat '/tmp/build_9e902a87/requirements.txt': No such file or > directory > remote: -----> Installing python-3.9.9 > remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 > remote: -----> Installing dependencies with Pipenv … -
How to set field value expiration time?
I have model User like this: class User(AbstractBaseUser, PermissionsMixin): myfield_choices = (('foo', 'First value'), ('bar', 'Second value') myfield = CharField(choices=choices) objects = BaseUserManager() I set in the field myfield value foo. After I want to set in the field myfield value bar for 1 day and after this period expires, the value becomes foo again automatically. How can I set that expiration time? Is there any native django instruments for this? -
Plotly.js for tidy data - Bar color
I’m new to plotly JS, but I have good experience with python - I want to get the same results as the following: import plotly.express as px long_df = px.data.medals_long() fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input") fig.show() Essentially to use the data value to add distinct colors to my bars, is there any easy way to obtain that results?, obviously I have a tidy dataset <script> $(document).ready(function(){ var xValue = {{ date|safe }}; var yValue = {{ revenue|safe }}; var stage = {{ stage|safe }}; var Forecast = { x: xValue, y: yValue, type: 'bar', text: yValue.map(String), textposition: 'auto', hoverinfo: 'none', name:'Leads', marker: { color: 'rgba(255, 99, 132, 0.2)', opacity: 0.8, line: { color: 'rgba(255, 99, 132, 1)', width: 1.5 } } }; var data = [Forecast]; var layout = { title: 'Sales Forecast - Leads and Deals', barmode: 'stack' }; var config = {responsive: true} Plotly.newPlot('DivBarChart', data, layout, config); }); </script> What I want to do is to color the graph based on the Stage: Year Month Stage Revenue Date Cumulative 0 2022 Feb Lead 750.0 Feb-2022 NaN 1 2022 Mar Lead 16172.5 Mar-2022 NaN 2 2022 Apr Lead 43617.0 Apr-2022 NaN 3 2022 Oct Deal 120000.0 … -
Django double join with multiple models?
I've spent quite some time on it and still haven't been able to figure out how to join these tables with django. I have a Movie database with following models: class Movies(models.Model): MovieName = models.CharField(db_column='MovieName', primary_key=True, max_length=30) MovieRating = models.FloatField(db_column='MovieRating') MovieReleaseTime = models.DateTimeField(db_column='MovieReleaseTime') class Genre(models.Model): GenreID = models.IntegerField(db_column='GenreID', primary_key=True, max_length=30) GenreTitle = models.CharField(db_column='GenreTitle', unique=True, max_length=30) class MovieGenres(models.Model): MovieName = models.ForeignKey('Movies', models.DO_NOTHING, db_column='MovieName') GenreID = models.ForeignKey('Genre', models.DO_NOTHING, db_column='GenreID') In my PostgreSQL I can pair MovieName with GenreTitle using following query: SELECT "MovieName", "GenreTitle" FROM public."Movies" NATURAL JOIN public."MovieGenres" NATURAL JOIN public."Genres"; I then get something like this: MovieName | GenreTitle -----------|------------ MovieA | GenreA MovieA | GenreB MovieB | GenreA How can I achieve the same output with Django views? -
Django update formset not saving
Simple recipe database with an update form, but when adding a new ingredient to an existing recipe, it's not saving the update. I'm not getting any error message either. The setup is user goes go a recipe list and is presented with a create button for new recipes and a list of existing recipes with an update button next to the recipe name. When the user clicks the update button, it takes them to /recipe_update/#/ and is presented with the list of ingredients. It should allow them to add/remove/change ingredients and percent, and then save the changes, but it's not saving new ingredients or changes. models.py class Recipe(models.Model): name = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class Recipe_Ingredient(models.Model): recipe_name = models.ForeignKey(Recipe, null=True, on_delete = models.SET_NULL) ingredient = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) recipe_percent = models.DecimalField(max_digits=8, decimal_places=5, blank=True) views.py def recipeUpdate(request, recipe_id): recipe = Recipe.objects.get(pk=recipe_id) recipeingredient = inlineformset_factory(Recipe, Recipe_Ingredient, fields=('ingredient', 'recipe_percent',)) if request.method == 'POST': formset = recipeingredient(request.POST, instance=recipe) if formset.is_valid(): formset.save() return redirect('/') formset = recipeingredient(instance=recipe) context = {'formset':formset} return render(request, 'accounts/recipe_form.html', context) urls.py ... path('recipe_update/<recipe_id>/', views.recipeUpdate, name="recipe_update"), ... recipe_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md-6"> … -
Django model field values returning blank?
I'm a Django Beginner. I have a model named "Person" with two character fields - first_name and last_name. I have migrated them using makemigrations in the shell and have set the value of first_name to my first name. However, whenever I try to set a value for last_name it returns blank. For example: a = Person(last_name="...") a.save() a.id id=... Person.objects.get(id=...) <Person: > The value will just be blank in the brackets. Here is my models.py if it's relevant: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=6) def __str__(self): return self.first_name I'm not entering a value that is beyond the max_length. Thanks for your time. -
Django CKEditor does not work in all textarea fields
I have tried to use Django CKEditor to improve my text editor. It looks good; however not all my textarea fields can be impacted by Django CKEditor. It only influences at the first one, others don't.Here are my pictures and code. Hopefully you can help me solve the problem. Thank you! enter image description here enter image description here post-detail.html <section id="comments"> {% for child_comment in comment.children %} <div class="child-comment"> <a href="mailto:{{ comment.user.email }}" style="text-decoration: none;">{{ child_comment.author }}</a> <span style="font-style: italic;">{{child_comment.timestamp}}</span> <p>{{child_comment.text|safe}}</p> </div> {% endfor %} </section> <section id="comment-form"> <form action="{% url 'post-detail-page' post.slug %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for form_field in comment_form %} <div class="form-control {% if form_field.errors %}invalid{% endif %}"> {{ form_field.label_tag }} {{ form_field }} {{ form_field.errors }} {{ form.media }} </div> <button>Submit</button> {% endfor %} </form> </section> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> views.py @class_view_decorator(login_required) class PostDetailView(View, LoginRequiredMixin): def is_marked_post(self, request, post_id): marked_posts = request.session.get('marked_posts') if marked_posts is not None: is_saved_for_later = post_id in marked_posts else: is_saved_for_later = False return is_saved_for_later def get(self, request, slug): post = Post.objects.get(slug=slug) context = { "post": post, "post_tags": post.tags.all(), "comment_form": CommentForm(), "comments": post.comments.all().order_by("-id"), "saved_for_later": self.is_marked_post(request, post.id) } return render(request, "blog/post-detail.html", context) def … -
How to set Authorization header in Django?
I want to set the bearer token in the authorization header. why? Because I am using rest_framework_simplejwt in my Django project. I want to implement authorization using JWT. For that, I create an access token and save it in cookies on user login. Now I want to check if the access token which is stored in the cookie is invalid or expired? So, the user can see the data fetched from DB. Let me tell you some more detail then I will be able to tell you my problem. As you can see in the image I changes the token in the cookie but when I refreshed it it just shows that I am login. Can you please tell me the flow of Auth. in rest_framework_simplejwt. here is the code. https://i.stack.imgur.com/vAtxz.png https://i.stack.imgur.com/9htCS.png https://i.stack.imgur.com/HFgvp.png https://i.stack.imgur.com/ftJIA.png https://i.stack.imgur.com/Bh2At.png https://i.stack.imgur.com/3Hl6e.png https://i.stack.imgur.com/1kE5a.png -
Making a post http request of form data to a database with empty/blank fields
I have a consumer model with several fields, where I have also specified their default values; e.g. age = models.CharField(default="no information", max_length=50) I use the following snippet to post a new consumer to my MongoDB database: if request.method == 'POST': try: consumer_data = JSONParser().parse(request) consumer_serializer = ConsumerModelSerializer(data=consumer_data) if consumer_serializer.is_valid(): consumer_serializer.save() collection_name.insert_one(consumer_serializer.data) response = { 'message': "Successfully uploaded a consumer with id = %d" % consumer_serializer.data.get('id'), 'consumers': [consumer_serializer.data], 'error': "" } return JsonResponse(response, status=status.HTTP_201_CREATED) else: error = { 'message': "Can not upload successfully!", 'consumers': "[]", 'error': consumer_serializer.errors } return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST) except: exceptionError = { 'message': "Can not upload successfully!", 'consumers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) When I fill out all the fields on my Angular form and post, everything works fine. However, when I leave a field blank, I get a bad request error message and the post does not go through. Initially, I thought it was because I did not have default fields in my Django model, but even after I added them, I still get this. How can I modify the code snippet to allow me to post with blank fields? This not only saves me time in testing and filling out the form … -
Resize and convert mime image Django
I try resize and convert mime before save a image models.py class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to=upload_to_path, null=True, blank=True, default='magickhat-profile.jpg' ) def save(self, *args, **kwargs): #on update image delete old file try: this = ProductImages.objects.get(id=self.id) if this.image_file != self.image_file: this.image_file.delete(save=False) except: pass super().save(*args, **kwargs) image_manipulation(self) The function upload_to_path and image_manipulation is imported from utils.utils import upload_to_path, image_manipulation utils/utils.py from PIL import Image from pathlib import Path def upload_to_path(instance, filename): ext = filename.split('.')[-1] filename = instance.product.slug+"_"+str(instance.id)+"."+ext return 'user_{0}/{1}/{2}'.format(instance.product.user.id, instance.product.id, filename) def image_manipulation(self): pathx = self.image_file.path self.image_file = Image.open(pathx) img_x = self.image_file.resize((200,300)) img_x.save(pathx) With this code work, but I'm not getting implement this code to convert to png too... When i try something like: def image_manipulation(self): pathx = self.image_file.path self.image_file = Image.open(pathx) img_x = self.image_file.resize((200,300)) img_rgb = img_x.convert('RGB') img_split_ext = Path(pathx).stem img_rgb.save(img_split_ext+".png") When i made this change, the file is uploaded, but not resize and note convert to png. If possible, im appreciate if could i little explanation, about the flow of this process, between a callable upload_to that, receive 2 parameters (instance, filename) the method save() itself, becouse from my pov upload_to is about the record in database, and save() is about filesystem storage... … -
How to make two manytomany fields in a model hold different values
I have Two simplified models as bellow: class Courses: name = models.CharField(_("Course name"), max_length=256) class School: main_courses = models.ManyToManyField(_("Main Courses"), to="course.Courses", related_name="maincourses", blank=True) enhancement_courses = models.ManyToManyField(_("Enhancement Courses"), to="course.Courses" related_name="enhancementcourses", blank=True) main_courses and enhancement_courses are going to hold a list of Courses. But I need to make sure their values wont be equal. For example if in school_1, main_courses are math, physics then enhancement_courses can't be these values. What is the simplest way in django to do this? -
Error with OpenCV live stream webcam in Django project
So I have a template were I render a view that has a live stream webcam in Django. When I run the server for the first time the camera works fine, but if I go back and then enter again I get this error: cv2.error: OpenCV(4.5.5) /io/opencv/modules/imgcodecs/src/loadsave.cpp:976: error: (-215:Assertion failed) !image.empty() in function 'imencode' I have searched for this issue but I haven't found the exact solution. views.py: @gzip.gzip_page def live(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: pass return render(request, "live.html") class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('live/', views.live, name='live'), ] live.html: <html> <head> <title>Video Live Stream</title> </head> <body> <h1>Video Live Stream</h1> <img src="{% url 'live' %}" /> </body> </html> help is much appreciated -
django.db.utils.ProgrammingError: relation "administration_parks" does not exist
I had a problem, and I really struggled to figure out what was wrong. I made an application with the Django framework. Everything worked fine on my local machine, including the DB. Only, when I put my application on the server, I wanted to migrate the database, but I had this error : Traceback (most recent call last): File "/home/thomas/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "administration_parks" does not exist LINE 1: ...name", "administration_parks"."availability" FROM "administr... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/home/thomas/env/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/thomas/env/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/thomas/env/lib/python3.8/site-packages/django/urls/resolvers.py", line 412, in check … -
Why do certain querysets take longer to serialize in my serializer
I have an API built using Django and Django REST Framework that returns a paginated response to the front-end. By default the page_size is 25, but depending what instances of objects are being passed to the serializer it could either respond fairly quickly or very slowly. The user can select a variety of parameters to make a search on. These parameters are then passed to the backend where the queryset is filtered. This queryset is then paginated, serialized, and returned to the front-end. I understand that the filtering and pagination would take a variable amount of time depending on the parameters that are being filtered on, and the size of the queryset. I'm wondering why it is that the serializer has significantly different performance for different paginated querysets (anywhere from .5 seconds to 20 seconds). My serializer class draws data from a lot of different parts of the database. I've used select_related, and prefetch_related in parts that were applicable, this improved the serializer performance across the board. There are a few SerializerMethodFields that still make queries resulting in N+1 issues, this doesn't seem to be the major issue however. From close inspection the query that takes the longest to run … -
Django Admin raise Integrity Error when I set UniqueConstraint on model
I am developing Library management system and I want to avoid duplicate records, I have the following book model: class Book(models.Model): isbn = models.CharField(max_length=13, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) preview = models.ImageField(upload_to='books/') author = models.ForeignKey(Author, on_delete=models.CASCADE) stock = models.PositiveIntegerField(default=0) assigned = models.PositiveIntegerField(default=0) class Meta: constraints = [ models.UniqueConstraint(Lower('title'), 'author', name="unique_book_with_author" ) ] def __str__(self) -> str: return self.title I want to make sure that a book with same incasesensitive title and author exists only once, Now I want that if user tries to add duplicate record, he get nice error message, this book already exists, but admin raises Integrity error as Follow: My admin class is as follow: @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title', 'author', 'category', 'assigned', 'is_available' ] search_fields = [ 'title', 'author__name__startswith' ] @admin.display(ordering='is_available', boolean=True) def is_available(self, book): return book.stock > book.assigned def get_search_results(self, request, queryset, search_term: str): queryset, use_distinct = super().get_search_results(request, queryset, search_term) queryset = get_int_search_result(queryset, self.model, search_term, 'isbn') return queryset, use_distinct Docs are not helping me, please guide what I do? because when I use unique_together in Meta class (which will be deprecated soon as mentioned by docs), everything works fine and django admin give nice error message, but when I am using … -
How to set-up dynamic select fields in Django admin with Ajax?
I'm using Ajax to create dynamic select fields in my template views, but I now need to set it up to work also in my Admin. I've researched multiple alternatives, one being django-smart-select which I couldn't get to work for some reason. So I'm putting my trust in Ajax and hoping to get this to work in some way. I'm currently overriding the change_form.html which Django uses when a user is changing a form, but when trying to retrieve the response from the request I do when one select field is changed, I get a full HTML document full of irrelevant Django-admin data. Anyone who can help me out with this or suggest another way that I can get it to work? My template.html where things work as expected {% extends '_base.html' %} {% load static %} {% block content %} <body onload="hide_area_field()"> {% block form_title %} <h2>Ny annons - Kontorshund erbjudes</h2> {% endblock form_title %} <form method="post" enctype="multipart/form-data" id="adForm" data-municipalities-url="{% url 'ajax_load_municipalities' %}" data-areas-url="{% url 'ajax_load_areas' %}" novalidate> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Publicera annons</button> </form> </body> {% endblock content %} {% block footer %} {% comment %} Imports for managing Django Autocomplete Light in … -
ValueError: invalid literal for int() with base 10: b'20 07:01:33.203614' In Django 3.0 and python 3.7
After upgrading from Django 1.8 to Django 3.0 Here in Django 1.8 for the same code __unicode__() worked fine and when comes to in Django 3.0 i am getting error Here is my error traceback Traceback (most recent call last): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/harika/lightdegree/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/harika/lightdegree/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/harika/krishna test/dev-1.8/mcam/server/mcam/crm/views.py", line 19569, in autocomplete_items for c in products: File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/query.py", line 276, in __iter__ self._fetch_all() File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1170, in execute_sql return list(result) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1569, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1569, in <lambda> for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/db/utils.py", line 97, in inner return func(*args, **kwargs) File "/usr/lib/python3.7/sqlite3/dbapi2.py", line 64, in convert_date return datetime.date(*map(int, val.split(b"-"))) ValueError: invalid literal for int() with base 10: b'20 07:01:33.203614' Let us consider my views.py as def autocomplete_items(request, flag=None): client = request.user.client q = request.GET.get('term') category = request.GET.get('category', '') job_items = JobItems.objects.filter(client_id=client) if category: job_items = job_items.filter(category_id=category) if flag: job_items = job_items.filter(stock='Variety Master') …