Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
chartjs datalabels not showing anything with django template
I tried so many time to ask this question but no one was able to help me so I decided to deleted the previous question and reask with taking into considerations the answers that I received. I have this chart created with chartjs, as you can see you can hover over points to see their coordinated or data, I would like to have an option to show them without having to hover. The reason why I want to do this is because I am going to add export to pdf, and it exports whatever it can see on the HTML , and exporting a chart without its values would be unreadable to the end user. Note (I don't know if this matters but I am using django and I did not do any npm installation of datalabels) Another Note : I was told that I have to register the plugin before using it, with Chart.register(ChartDataLabels); but adding it the chart script just causes the chart to disappear. .cann { border: 3px solid darkgrey; padding: 10px; box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); transition: all 0.3s cubic-bezier(.25,.8,.25,1); width: 650px; height: 250px; margin-left: 3em; } <!-- Required meta tags --> … -
Django REST Framework - method patch not allowed with UpdateModelMixin
I would like to update a record in my database with the REST framework. I'm getting an message of method not allowed for anything but "GET". views.py class MetadataViewTest(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): queryset = deployment.objects.all() serializer_class = SerializerTest def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) urls.py urlpatterns = [ path('api/metadata_test/<int:pk>/', views.MetadataViewTest.as_view()) ] serializers.py class SerializerTest(serializers.ModelSerializer): class Meta: model = deployment fields = [field.name for field in deployment._meta.fields] I've tried the request through postman as a PATCH PUT or POST at api/metadata_test/20/ -
Session expired error every 5 min in saleor admin after set JWT_EXPIRE
What I'm trying to achieve I set JWT_EXPIRE='True' in my server, so that the access token will expire every 5 min, but I'm having a problem in the admin panel, every 5 min it closes my session. Steps to reproduce the problem Setup Saleor 2.11.0 in Ubuntu 20.04 server Set environment variable JWT_EXPIRE='True' Hosting as static website the Dashboard on amazon bucket Try to stay login after 5 min What I expected to happen Shouldn't the user stay logged in with a silent authentication after 5 minutes? Screenshots Current problem Configured environment variables Http request and response from inspector In screenshot I put the response of the last graphql request. Console output This happens after trying to enter one of the administrator tabs, in this case the product tab, after 5 minutes. System information Saleor version: [ ] dev (current master) [ ] 3.0 [x] 2.11 [ ] 2.10 Operating system: [ ] Windows [x] Linux [ ] MacOS [ ] Other Browser: [ ] Safari [x] Chrome -
How to render Django UTC time in local time
I have USE_TZ = True enabled in my settings.py file, so dateTime values are stored as UTC. When I want to display these dates/times on a template, they will be displayed in whatever timezone I have set in setings.py with TIME_ZONE = 'America/Toronto'. But what if my users are in different timezones and I want it to automatically change the time based on the users timezone? I found that using javascript I can do : new Date(djangoDate)).toLocaleString() will format the date and time to my timezone, regardless of what I have in TIME_ZONE = 'America/Toronto' But is there a way to do this in python/Django? Everything I have tried, like {% load tz %} relies on TIME_ZONE = 'America/Toronto'. in settings.py. I have also tried: timezone.activate(pytz.timezone('America/Winnipeg')) in my view, which seems to display the dates as intended, but found that this will actually change the UTC value in the database when using forms to update dateTime data, which is behavior I do not want. I want to store in UTC, and render/display in local time, automatically without the user having to tell the application what timezone they are in. Is this possible? -
Issue while trying to add a new object with depth = 1 in my serializer
I'm working on a small project using Django / Rest Framework. I have two models Contacts and Category, related using a foreign key everything works fine but when I do depth = 1 in my serializer I get an error 'IntegrityError: (1048, "Column 'category_id' cannot be null")' # foreignkey but when I remove depth = 1 from my serializer it works fine with no errors -
No Python at 'C:\Users\rodne\Desktop\Py 382\python.exe'
Im trying to run my django application. Im not sure what I did to cause it not to work but now when I use the command "python manage.py runserver" in the correct directory cmd gives me the error No Python at 'C:\Users\rodne\Desktop\Py 382\python.exe' can anyone help me understand what I did wrong? -
How to copy staging database to Heroku review app
A similar thread to this one already exists (see link), but I do think that my case is a bit different - my main issue is that heroku.yml's release section doesn't play nicely with app.json's postdeploy script. heroku.yml: ... release: command: - python manage.py migrate image: web app.json: { ... "environments": { "review": { "addons": [ "heroku-postgresql:hobby-dev", ], "scripts": { "postdeploy": "pg_dump $STAGING_DATABASE_URL | psql $DATABASE_URL && python manage.py migrate" } } } } During a deploy, the release from heroku.yml gets executed before the postdeploy script, which introduces a bunch on conflicts when psql is called because the tables already exist. Does anybody know how to handle this? release shouldn't be ignored as it's run on every new release, whereas postdeploy is run only once. But at the time that postdeploy is being run, the database should be empty for psql to succeed without errors. -
Haar Cascades Eye Detection Does Not Work On Python Django Webpage?
I try to display live stream webcam on webpage using Django with OpenCV eye detection. from imutils.video import VideoStream import imutils import cv2,os,urllib.request import numpy as np from django.conf import settings eyes_detection = cv2.CascadeClassifier('haar/haarcascade_eye.xml') class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) eyes_detected = eyes_detection.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) for (x, y, w, h) in eyes_detected: cv2.rectangle(image, pt1=(x, y), pt2=(x + w, y + h), color=(0,255,0), thickness=2) frame_flip = cv2.flip(image,1) ret, jpeg = cv2.imencode('.jpg', frame_flip) return jpeg.tobytes() The video stream will not be displayed with the code above, however, the video can be displayed if I remove line 20-23(gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY). How can I display the video stream with eye detection on the webpage? Below is my views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.http.response import StreamingHttpResponse from main.tryhaar import VideoCamera import cv2 def gen(tryhaar): while True: frame = tryhaar.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') -
ValueError: Unable to configure handler 'file': [Errno 2] No such file or directory: while using cross-platform scripts
I am using import os to create an absolute path, as suggested here, because relative paths are not allowed, see here. But it's still being logged as an error. Here I import the os and use a base_dir: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) then I create directories: LOGGING_ROOT = os.path.join(CROWDFUNDING_ROOT, 'logs') ERROR_LOGS = os.path.join(LOGGING_ROOT, 'errors') INFOS_LOGS = os.path.join(LOGGING_ROOT, 'infos') DEBUG_LOGS = os.path.join(LOGGING_ROOT, 'debugs') per logger type. But I am still getting this error on EC2 on ubuntu. Now I can't do a makemigrations because of this. I don't know what to do, I even used sudo su before I went into the env. -
why can't upload photos in django?
When I try to upload a picture from my form, everything processes, but the image is not being saved. I checked everything on the internet but did not find any solution. In the Html file I am writing Does anyone know why this is happening? Thanks ahead of time! forms.py: class NewPostForm(forms.ModelForm): picture = forms.ImageField(required=True) caption = forms.CharField(widget=forms.Textarea(attrs={'class': 'input is-medium'}), required=True) tags = forms.CharField(widget=forms.TextInput(attrs={'class': 'input is-medium'}), required=True) class Meta: model = Post fields = ('picture', 'caption', 'tags') class Post(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable=False) picture = models.ImageField(upload_to = user_directory_path, null=True) caption = models.TextField(max_length=1500, verbose_name='caption') posted = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, related_name='tags') user = models.ForeignKey(User, on_delete=models.CASCADE) #likes = models.IntegerField() def get_absolute_url(self): return reverse('postdetails', args=[str(self.id)]) views.py: @login_required def NewPost(request): user = request.user.id tags_objs = [] if request.method == 'POST': form = NewPostForm(request.POST, request.FILES) if form.is_valid(): picture = form.cleaned_data.get('picture') #picture = form.cleaned_data.get('picture') caption = form.cleaned_data.get('caption') tags_form = form.cleaned_data.get('tags') tags_list = list(tags_form.split(',')) for tag in tags_list: t, created = Tag.objects.get_or_create(title=tag) tags_objs.append(t) p, created = Post.objects.get_or_create(caption=caption, user_id=user) p.tags.set(tags_objs) p.save() return redirect('home') else: form = NewPostForm() context = { 'form':form, } return render(request, 'newpost.html', context) -
How to apply local time to Django form field
I have USE_TZ = True in my settings.py file, so (from my understanding) this causes dates to be stored in my database as UTC time. So to store a date automatically in a view I can do: from django.utils import timezone now = timezone.now() newGlucose = glucose(glucoseVal=currentGlucose,Dtime = now) #Dtime is a dateTime modelfield newGlucose.save() #saves to the DB as UTC (0.00 offset) And when I want to display this as local time on a template I can do: from django.utils.timezone import localtime glucoses = glucose.objects.filter() date = (glucoses[x].Dtime) #<----grab stored time from DB (#Dtime is a dateTime modelfield) date = localtime(date) #<-----convert to locatime for display on template This seems to work well, I don't know how Django is getting the correct timezone (from browser?) but it works. Now, How can I use this same methodology for a Django form with dropdown boxes for the dateTime? By default the HTML dateTime dropdown is in whatever timezone the current timezone is set as in the settings.py file, which obviously isn't helpful when my users are in different time zones. The only thing I can get to work is by creating a timezone model field for each user, then having the … -
how to get data from django rest framework
basically most requests are using [id] get : /[:id] post : /[:id] delete : /[:id] but if i want specific data by searching db example model "Warrior" race : string (maori, barbarian, valkiri... ) weapon : int (associated with Weapon(model)) health : int model "Clan" name : string warriors : int now want to search all clans that have maori how you implement with django rest framework? -
Saving Matplotlib figure to Django models.ImageField Instance
In Django I have a models.ImageField that takes in the user image & should output the modified image to the Model-Post instance. It instead uploads the original image to the model instance (saves in the 'media/Files folder) & outputs the converted image into the root directory, which is not accessible on the live server. Wondering how I could either replace the user-uploaded image with the converted image or add the matplotlib image to the Post instance. Any help would be awesome, as I've spent days trying to figure this out. -
How can I pring search results?
Since I'm new to fpdf I need some assistance with my dilemma: I have a view, that doing a search on website, and for now I need to print my search results using fpdf( I know about ctrl+p printing, I have pagination, so It didn`t work ). Could someone help me with the steps I have to take? This is my search view class SearchResidentView(AbstractSearchView): template_name = 'resident/search_resident.html' search_form = SearchResidentForm def get_filter_func(self): return resident_search_filter def get_queryset(self) -> 'QuerySet[CitizenshipRequest]': data = self.request.GET if any(data.values()): make_user_action_log(f'Resident search. Search data: {pretty_dict(data)}', self.request.user) filtered_qs: QuerySet[CitizenshipRequest] = super().get_queryset().annotate( dep_code=F('dep_add__code') ).only( 'last_name', 'first_name', 'middle_name', 'date_birth_str' ) return filtered_qs -
Django can't deploy the static files on Heroku if my folder name is assets instead of static
I followed a lot of questions I have searched and applied, but nothing worked. I made a lot of attempts. Here are the questions: Django can't find the static files Can't deploy Django + Heroku Heroku - Handling static files in Django app Django static files on heroku STATIC_ROOT setting in Django Heroku django app createsuperuser Observations: I know I should change STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') to STATIC_ROOT = os.path.join(BASE_DIR, 'assets'), but it did not work either. I know that I should run python manage.py collectstatic that Heroku deployed correctly the staticfiles folder and it rendered well, but it increased the storage size, with the assets folder. I want only to keep the assets folder. The tree looks like, and observe that I have a folder called assets and do not have the folder static because of assets: gusbemacbe.co.nz ├── assets │ ├── css │ ├── fonts │ ├── images │ ├── js │ ├── json │ └── yaml ├── commands ├── db.sqlite3 ├── gusbemacbe │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── home │ ├── admin.py │ ├── apps.py │ ├── tests.py │ └── views.py ├── manage.py ├── Procfile ├── requirements.txt ├── runtime.txt ├── … -
How to run a code just before django restarts?
Here is the case. I start a telegram bot(using pyrogram framework) inside django and everytime that I modify a file and save it or django just restarts by any reason, I have to shut pyrogram down right before django starts again. If I do not shut down pyrogram right before server restart process, it gets stuck after printing a sentence like: <modified_file_address> changed, reloading. And after this line, nothing happens and django will not start itself again and I just found source of the problem. Pyrogram(v0.18.0 - synchronous version) is causing it because of multithreading lock keys.(a little bit complicated to describe and not related to the question) If I can shutdown pyrogram bot right before running the django server again(literally right before or after printing <modified_file_address> changed, reloading. message), I can fix it. After searching inside the django source code, this is the function that actually prints that message. # inside django.utils def trigger_reload(filename): logger.info('%s changed, reloading.', filename) sys.exit(3) And now this is my question: Is There Any Way To Overwrite trigger_reload Function Or Customize It Somehow? And if no: Is There Any Way To Run A Function Right Before trigger_reload Function? And if no again: Is It Possible … -
I am trying to install psycopg2-binary in windows and getting warning
I am trying to install psycopg2-binary in windows I get this warning. how can I solve this problem ?? PS C:\Users\zakoo> pip install psycopg2-binary WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) Requirement already satisfied: psycopg2-binary in c:\python39\lib\site-packages (2.8.6) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) when I run docker-compose up I get this error. web_1 | backend = load_backend(db['ENGINE']) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 111, in load_backend web_1 | return import_module('%s.base' % backend_name) web_1 | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module web_1 | return _bootstrap._gcd_import(name[level:], package, level) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 29, in <module> web_1 | raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) web_1 | django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' -
Redis performance in Django is very slow
A Django webapp reads a redis database and displays the data in a Plotly plot. When the redis database has a small number of rows (less than 20k), queries are very fast (less than a second). As the number of rows grows over 50k, queries slow dramatically (8 to 15 seconds). Threads also stumble over each and don't complete in sync. This redis database uses a timestamp as a key. Each value is a string in json format. Like this: key: 1621367811.769709000 value: {"timestampx": "1621367811.769709000", "length": "96", "dscp": "0", "srcip": "172.16.1.2", "destip": "172.17.4.2"} My code queries the database. It creates a dictionary where each key is one second. Each value is the total number of megabits transmitted in that second. Code snippet below: r = redis.StrictRedis(**redis_config) keys = r.keys(pattern="*") keys.sort() start = datetime.now() #keys = keys[0:1000] #For troubleshooting vals = r.mget(keys) end = datetime.now() print("There are " + str(threading.active_count()) + " active threads") print("The mget command took " + str(end - start) ) print("*******************************") """ Code to make a Pyplot scatter plot where the x axis is bps.keys() and the y axis is bps.values() """ Initial output looks something like this: There are 26966 keys in the database. There are … -
Django posrtgerql wrong DateTime
I have DateTimeField at my postgres db. And for ecample I have time 5/12/2021 4:00 PM django will save it as 5/13/2021 01:00+03:00 How can i resolve it? -
how can I fix Django cannot unpack non-iterable int object?
I am kind of a beginner and I'm doing an ecommerce web-site now and in views I have get_object_404 and parameters to go with it but I keep getting cannot unpack non-iterable int object with an id parameter. I searched the topic and mostly found same problem with pk and it didn't work with id(or maybe I couldn't make it work who knows). here's the code: views.py: from django.shortcuts import render, get_object_or_404 from .models import * from cart.forms import CartAddProductForm def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) context = { 'categories': categories, 'category': category, 'products': products, } return render(request, 'onlineshop/product/list.html', context) def product_detail(request, id, slug): product = get_object_or_404(Product, id, slug=slug) cart_product_form = CartAddProductForm() context = { 'product': product, 'cart_product_form':cart_product_form, } return render(request, 'onlineshop/product/detail.html') urls.py: from django.urls import path from . import views app_name = 'onlineshop' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail') ] models.py: from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('onlineshop:product_list_by_category', … -
Only allow unique email hosts while ignoring subdomains
I want to allow only unique user email addresses from a single host with the subdomain part ignored, no matter if it's submitted or not. I'm pretty sure my code is correct because all parameters are set as explained in the documentation and the regex pattern validates but it doesn't seem to work. email_pattern = r'^[^@]+@([^\.@]+\.)?google\.com$' class User(Model): class Meta: constraints = [ CheckConstraint(check=Q(email__iregex=email_pattern), name='check_google'), UniqueConstraint(fields=['email'], condition=Q(email__iregex=email_pattern), name='unique_user'), ] email = EmailField() My email_pattern should allow google.com and any *.google.com as email host. The first constraint checks if the email address has only the allowed hosts. The second constraint should check if any user with an email address host (google.com or *.google.com) already exists and therefor raise an database error if found. Example email addresses: john.doe@google.com john.doe@sub.google.com john.doe@sub2.google.com Any of the emails above be valid but only allowed for a single user. Currently I can create 3 users with 3 different emails... Is there something I'm missing out? -
Django: "Object has not attribute get" error in forms.Form
I am trying to create a forms.Form that loads an existing Trade record and allows users to update it. I believe the usual way to do this would be to use a forms.ModelForm, but ModelForms do not work with the widget I am using (django-autocomplete). When I load the url /update-buy/263/, it calls the views.update_buy function (shown below). I am getting the error 'ManyToOneRel' object has no attribute 'attname'. Form: class BuyUpdateForm(LoginRequiredMixin, forms.Form): desired_game = forms.ModelChoiceField( queryset=Game.objects.all(), to_field_name='desired_game', #todo widget=autocomplete.ModelSelect2( url='game-autocomplete', attrs={ 'data-minimum-input-length': 2, }, ) ) buy_price = forms.IntegerField() def __init__(self, data, *args, **kwargs): super(BuyUpdateForm, self).__init__(data, *args, **kwargs) if data is not None: self.fields['buy_price'].label = "Max. Buy Price" self.fields['buy_price'].initial = data['buy_price'] self.fields['desired_game'].initial = data['desired_game'] views.update_buy(method called when user loads the above url) @login_required def update_buy(request, pk): offer = Trade.objects.filter(id=pk).first() print('offer: ' + str(offer)) if request.method == 'POST': trade_form = BuyUpdateForm(request.POST, instance=offer) if trade_form.is_valid(): trade_form.save() messages.success(request, f'Your trade has been updated') return redirect('update-offer/' + str(pk)) else: #GET request data = {'desired_game': offer.desired_game, 'buy_price': offer.buy_price} trade_form = BuyUpdateForm(data) return render(request, 'blog/buy_form.html', {'form': trade_form, 'title': 'Update Trade Form'} ) relevant fields from the Trade model: class Trade(models.Model): name = models.TextField() # Unrestricted text desired_game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='desired_game', db_column='desired_game', null=True, blank=True) buy_price … -
Django get related object in one-to-one relationship without knowing the related model
How do I get the related object of a model in this case: class ModelA(models.Model): pass class ModelB(models.Model): a = models.OneToOneField(ModelA, related_name='b_object', on_delete=models.CASCADE) class ModelC(models.Model): a = models.OneToOneField(ModelA, related_name='c_object', on_delete=models.CASCADE) I know that if I do: ModelA.b_object # returns related b object ModelA.c_object # returns related c object But since this is a one to one relationship, a particular instance of ModelA will only be related to a single instance of one of those models, so: Is there a general way to get the related object without knowing if the related object is from one model or the other? Something like: ModelA.get_related_object Does Django provide this functionality? Should I build a custom method for this and how? Use case example (for clarity): in a DetailView template for ModelA, get the related object for that instance. -
How to fix relation does not exist -error when using class meta in model?
I have this class in my models.py: class Person(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) birthday = models.DateField(null=True) gender = models.CharField(max_length=20) height = models.CharField(max_length=3) id = models.CharField(blank=False, max_length=100) weight = models.CharField(max_length=3) class Meta: managed = False db_table = 'person' def __str__(self): return self.id Everytime I run migrate -command I get this error: psycopg2.errors.UndefinedTable: relation "person" does not exist. I've already dropped the db and destroyed the migration file but the error remains. How can I fix this and why this happens? -
OSError: [WinError 193] %1 is not a valid Win32 application. By reading captcha with using tr repository
I am using tr --> https://github.com/myhub/tr (this repository to read captcha). I am getting an errorr WinError 193 %1 is not a valid Win32 application. I have installed tr repository in my env as per the instruction mentioned in this repository.