Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model auto update status when the medicine is expired
How to Auto update the status when the medicine is expired? for example, I created medicine record and set the expirationdate to july 2022, if the current date is greater than the expirationdate it will update the status of medicine to "Expired", How do I do that? class Medicine(models.Model): medstatus = [ ("Expired", "Expired"), ("Active", "Active") ] description = models.CharField(max_length=50, null=True) expirationDate = models.DateField(null=True) status = models.CharField(max_length=50, choices=medstatus, null=True) -
I change the error message, but it doesn't change
I change the error message in the model, but it doesn't change. I can't understand why this approach doesn't work, because it works for other fields it's my model class CustomUser(AbstractUser): username = models.CharField( max_length=15, unique=True, validators=[UnicodeUsernameValidator()], error_messages={ "unique": "Test login", }) group = models.OneToOneField('Group', unique=True, on_delete=models.CASCADE, error_messages={ "unique": "Test group" }) email = models.EmailField(models.EmailField.description, unique=True, validators=[email_validator], error_messages={ "unique": "Test email", }) def __str__(self): return self.username and it's my Group Model class Group(models.Model): name = models.CharField(max_length=20, unique=True) faculty = models.ForeignKey(Faculty, on_delete=models.CASCADE) def __str__(self): return self.name When testing in postman, I get this: { "username": [ "Test login" ], "group": [ "This field must be unique." ], "email": [ "Test email" ] } Thank you in advance -
Create User in django using Rest Framework
i've seen people using different ways to create user in django Rest framework. i tried & none of them is working for me. sometimes it says Key error: Groups or something else. so i tried this without having a is_valid & it works like a charm. is this a safe way to use to create user or if not why & how should i create User in views? #my views.py @api_view(['GET','POST']) def getUserData(request): if request.method == 'POST': user = User.objects.create_user( username=request.data['username'], password=request.data['password']) serializer = userSerializer(user) return Response(serializer.data) -
Access value of Django widget attribute
I have Django Form Field: dob = forms.DateField( required=True, widget=NumberInput( attrs={ "type": "text", "class": "datepicker", "autocomplete": "off", "placeholder": "DD/MM/YYYY", } ), ) Now I need to access the "placeholder" value. I use datepicker to change the format: $('.datepicker').datepicker({ format: 'mm-dd-yyyy',# **here I need to replace it with Django widget attribute.** }); How can I get the value of the placeholder so I can do something like that: $('.datepicker').datepicker({ format: {{django.placeholder | safe}}, }); -
django import tags error Line number: 1 - resource objects need to have a primary key value before you can access their tags
I am using django taggit in my models and trying to import data. But getting errors. Given below. Line number: 1 - resource objects need to have a primary key value before you can access their tags. models.py: class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) varient=models.CharField(max_length=100, default="") Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(default="", unique=True, blank=True) Tags = TaggableManager(blank=True) -
Django trigger add on models
In adminsite, I want if the user create an account on Student table, it will also add to the dashboard table, how can i do that? class Dashboard(models.Model): fullname = models.CharField(max_length=50,blank=True, null=True) status = models.CharField(max_length=50,blank=True, null=True) dateCreated = models.DateTimeField(default=datetime.now()) class Student(models.Model): Gender = [ ('Male', 'Male'), ('Female', 'Female') ] fullname = models.CharField(max_length=50, null=True) status = models.CharField(max_length=500, null=True, default='Student') contact_number = models.IntegerField(max_length=50, null=True) age = models.IntegerField( null=True) gender = models.CharField(max_length=50, choices=Gender, null=True) birthdate = models.DateField(max_length=50, null=True) class Meta: verbose_name_plural = "LIST OF STUDENTS" -
How do I load local directory into path in urls.py
I saved my homepage.html file in my laptop see this image D:\Python\WebDjango\BaseCoffeehouse\coffeehouse\templates. Then in urls.py (open in VSCode), I added the path as below : path('D:/Python/WebDjango/BaseCoffeehouse/coffeehouse/templates', TemplateView.as_view(template_name='homepage.html'), name='homepage'), When I run the server (python manage.py runserver), I got an error message "Page not foung 404" in the default port 8000. So, how should I do it to open my homepage.html file? -
Why my images are missing when deploying django and postgresql on heroku?
I create a webapp with Django for the backend and React for the frontend. I deploy the app on heroku and I use the heroku-postgres as the database, after deployin the app everything works perfectly (superuser, models.py etc...). Now I connect to the superuser account and try to add data, all data is displayed on the application frontend except the images. Note that I have a static folder and also I have run python manage.py collectstatic before deploying the app on Heroku. What can I do to make the images displayed every time I add them? -
Django Mailgun API returning 401 forbidden
I've installed Django any mail and am I trying to use mail gun with it for password resets. I've added any mail to my installed apps and tried to use mail gun as an API or smtp service. Both return back 401 forbidden For using mail guns API here's my code: EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" ANYMAIL_MAILGUN_API_KEY = config("MAIL_GUN_DOMAIN_API") For MAIL_GUN_DOMAIN_API I tried using my accounts private key and I tried creating a domain and using the domains sending key. Both returned the same response. for smtp : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mailgun.org' EMAIL_PORT = 465 EMAIL_HOST_USER = config('MAIL_GUN_USERNAME') EMAIL_HOST_PASSWORD = config('MAIL_GUN_SMTP_PASSWORD') EMAIL_USE_TLS = True for MAIL_GUN_USERNAME I used my domains login for MAIL_GUN_SMTP_PASSWORD I used my domains password I tried all of mailguns different ports and switching between tls and ssl none of this worked. Any ideas what I'm doing wrong? -
Django elastic beantstalk createsuperuser issues
I have a django project which I have managed to deploy to elastic beanstalk server but have spent the last two days trying to create super user but to no avail. I have followed different guides and answers from this site but for the life of me I just cannot get this working. I have no problems doing this locally and the other container commands i.e migrations work fine when deploying via .ebextensions/django.config, but when I added the create_superuser container commands it fails. Please see the following tree structure of my project along with the relevent files used to run this step: wfi_workflow.ebextensions\django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: wfi_workflow.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "wfi_workflow.settings.prod" aws:elasticbeanstalk:environment:proxy:staticfiles: "/static": "static/" packages: yum: python3-devel: [] mariadb-devel: [] container_commands: 01_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic --noinput" 02_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate --noinput" leader_only: true 03_create_superuser: command: "source /var/app/venv/*/bin/activate && python3 manage.py mysuperuser" leader_only: true wfi_workflow\apps\account\management\commands\mysuperuser.py import os from django.core.management.base import BaseCommand from apps.account.models import User class Command(BaseCommand): def handle(self, *args, **options): if not User.objects.filter(username='test').exists(): User.objects.create_superuser('test', 'test@tesst.com', 'test1234') I'd be grateful if someone could help me resolve this issue going forward or if i'm missing anything. Thanks -
django-tenants global device table mapping to tenants
We are using django-tenants to provide a multi tenant solution for an iot platform and I'm having an issue figuring out how to map some global data to tenant specific tables. Basically we have iot devices that talk to a node.js server using a proprietary protocol over tcp, that server then makes rest api requests to a Django webserver to update the database with device measurements. The node server does not know anything about which device belongs to which customer so it needs to have a rest api that is global and then the webserver backend will need to map that device to a specific tenant but we cannot let tenants view each other's data so I'm not sure how we accomplish this as it seems apis are either tenant specific or global (public). -
SSL error: decryption failed or bad record mac when using rq worker in postgres docker image
I'm trying to run some tests in a docker image with manually installed postgres and some other software. I put everything inside one image because I'm trying to run my tests in Teamcity and Teamcity only accepts one image. Following is postgres related part in my Dockerfile: # install postgresql RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list && \ wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - && \ apt-get update && \ apt-get install -y postgresql-12 postgresql-contrib-12 # set up postgresql USER postgres RUN /etc/init.d/postgresql start && \ psql --command "CREATE USER test_user WITH PASSWORD 'test';" && \ psql --command "CREATE DATABASE test_db WITH OWNER = test_user;" && \ psql --command "ALTER USER test_user CREATEDB;" When I try to run tests inside the container, I get following error(I removed some private info): 2022-08-19 20:54:16,318 INFO worker(551): Worker rq:worker:94ec9b41d06942ae8d44a422681bf47f: started, version 1.8.1 2022-08-19 20:54:16,318 INFO worker(521): Subscribing to channel rq:pubsub:94ec9b41d06942ae8d44a422681bf47f 2022-08-19 20:54:16,320 INFO worker(555): *** Listening on default... 2022-08-19 20:54:16,321 INFO worker(1098): Cleaning registries for queue: default 022-08-19 20:54:16,607 INFO worker(1035): default: Job OK (f697a59f-af0f-45aa-84b4-44eede247c51) 2022-08-19 20:54:16,607 INFO worker(1045): Result is kept for 500 seconds 2022-08-19 20:54:16,619 INFO worker(590): Worker rq:worker:94ec9b41d06942ae8d44a422681bf47f: done, quitting 2022-08-19 20:54:16,620 INFO worker(529): … -
django rest framework Viewset for single item, not list
I am having a problem with my DRF API. I want to provide a read only endpoint that takes a single id from a object(document) in the DB and runs a script to perform an check and gives back the result. It works fine when I call the API with //api/documentcheck/1/ where 1 is the pk of the document in the DB. The problem is that if I just call the base URL //api/documentcheck/ it tries to give back the results of all documents in the database and times out because it takes ages. I am looking for a way to remove the list view and force users to provide the ID for a single document to check. This is my serializer class class DocumentCheckSerializer(serializers.Serializer): '''Serializer for document check''' class Meta: model = Document fields = '__all__' def to_representation(self, value): return process_document(value) This is my view: class DocumentCheck(viewsets.ReadOnlyModelViewSet): """Check a single document""" authentication_classes = ( TokenAuthentication, SessionAuthentication, BasicAuthentication, ) permission_classes = [IsAuthenticated] queryset = Document.objects.all() serializer_class = serializers.DocumentCheckSerializer and my router entry router.register("documentcheck", views.DocumentCheck, basename="documentcheck") -
I'm tyring to make an API following instructions on CodewithMosh
I'm learning python on a website called codewithmosh. I'm at the point where I'm doing a project with Django but every time I try to run my server (“python3 manage.py runserver”) to launch the site with a new API I made, It gives me this error message: "ImportError: cannot import name ‘_sanitize_token’ from ‘django.middleware.csrf’ (/Users/alecsmith/.local/share/virtualenvs/vidly-mJrVeZC4/lib/python3.10/site-packages/django/middleware/csrf.py)" I guess you would have to see my whole folder to understand what the issue could be, but if someone could give me some basic advance that would be appreciated. I re-followed the instruction 3 times and I still get that message. -
which pip package creates psycopg2 dependency?
This is what i mean, i am trying to install all the packages in my requirements.txt (django/python), i did not specify some packages like asgiref, psycopg2, urllib etc, but it just starts downloading or installing them too, then i thought: there must be some packages that are also downloading these other asgiref, psycopg2, urllib etc as dependencies. Does anyone know what package that might be from this lists? requirements.txt boto3==1.20.26 botocore==1.23.54 dj-database-url==0.5.0 Django==3.2.7 django-auto-logout==0.5.0 django-ckeditor==6.0.0 django-crispy-forms==1.12.0 django-dotenv==1.4.2 django-environ==0.9.0 django-heroku==0.3.1 django-jazzmin==2.4.8 django-plaintext-password==0.1.0 django-static-fontawesome==5.14.0.0 gunicorn==20.0.4 Pillow==9.1.0 psycopg2-binary requests==2.27.1 requests-oauthlib==1.3.1 -
Make Django admin object page show less?
I am currently trying to have the item page in the django admin (ie, /admin/dictionary/word/153/change) show less, I am just unsure how to do this. Given any random word can have say 10000 upvotes, it takes a while to actually make it to the page when it loads. So don't want it to show the votes? This is my admin.py and my models. from django.contrib import admin from diccionario.models import Palabra, Tag from django.utils.safestring import mark_safe class TagInline(admin.TabularInline): model = Tag def has_change_permission(self, request, obj=None): return False def has_add_permission(self, request, obj=None): return False class PalabraAdmin(admin.ModelAdmin): list_display = ( 'nombre', 'get_post_action', 'definicion', 'ejemplo', 'gramatica', 'get_sinonimos', 'get_antonimos', 'pais', 'creado', 'get_user_username', 'aprobada', 'anonimo' ) list_filter = ( 'creado', ) inlines = [TagInline] def get_sinonimos(self, obj): return ', '.join([item.nombre for item in obj.tag_set.filter(tag_type='Sinónimo')]) def get_antonimos(self, obj): return ', '.join([item.nombre for item in obj.tag_set.filter(tag_type='Antónimo')]) def get_user_username(self, obj): if obj.user: return obj.user.username if obj.user.username else obj.user.email def get_post_action(self, obj): return mark_safe('<a class="btn btn-primary" href="/api/admin/aprobar/%s">Aprove</a>' '<div style="margin: 5px 0"></div>' '<a class="btn btn-danger" href="/api/admin/borrar/%s">Borrar</a>' '<div style="margin: 5px 0"></div>' % ( obj.id, obj.id, )) get_sinonimos.short_description = 'Sinónimos' get_antonimos.short_description = 'Antónimos' get_user_username.short_description = 'username' get_post_action.short_description = 'action' admin.site.register(Palabra, PalabraAdmin) And here is the models.py import re from django.db import models … -
How to know when an item in cache expires in django
I'm currently building an order and checkout system for an application in django. I need to know when an order expires in a cache to trigger a code that returns items back to the inventory,up till now i haven't made progress in knowing how to do this in django. I just need a way to trigger a code after item expires in cache similar to signals for db save and delete. -
Django Email sending SMTP Error, cant send a mail
I am trying to send email within my Django project: # settings.py EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True def notify_user(email_address, subject='Subject', message='Some message!') -> None: send_mail( subject, message, settings.EMAIL_HOST_USER, [email_address], fail_silently=False ) As I know I need to disable this option (Gmail Security), but Gmail don't let me do it. As a result I got this error: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f14-20020a056512360e00b00492bbf7db8asm320697lfs.85 - gsmtp') What can I do? How to disable that option? -
Python function to get sytem mac address
I am developing an API using Django rest framework. I need a user's mac address to be in the list of an organization's mac addresses before he is authorized to access the organization's data. But the challenge is that this code returns different mac addresses when the code is hosted and when I am running it on my local machine. I don't know what I am getting wrong. and I really don't know much about networks too. Below is the code class MacAddressPermission: @staticmethod def authenticated(): mac_address = gma() mac_address = mac_address.upper() print("MAC ADDRESS: ", mac_address) return mac_address``` -
Django assigning model FloatField coordinate points to marker coordinates using Mapbox
For my project I have a model that had two FloatFields called lat and lng for coordinate value which I would like to display on an interactive map. Just starting with Django and API's so still very new to a lot of this. animal = models.CharField(max_length=32, choices=ANIMALS, default=BISON) image = models.ImageField(upload_to='images', null=True, blank=True) description = models.TextField(null=True, blank=True) lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) def __str__(self): return self.animal I am not sure how to access these values from my views page so that I am able to use them as {{ Django variables }} within my html template. My views: def homePage(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = PostForm() context = {'form': form} return render(request, 'home.html', context) I want to use a {% for n in posts %} {% endfor %} loop to loop through all the posts in my database add new markers the the map via: var marker = new mapboxgl.Marker() .setLngLat([-110.5885, 44.4280]) .addTo(map); However, these .setLngLat([-110.5885, 44.4280]) values need to be the ones specified from the posts. -
Django isn't authenticating user already logged in through web app frontend using keycloak
I am building an application that uses django as a backend for data processing and management calls served to a Vue3 SPA. I am using Keycloak for authentication and using keycloak-js and mozilla-django-oidc to handle authentication for each. Each work separately fine, I can navigate to the django app, login and see the data behind protected views (and get redirected properly if I a not logged in). Likewise I can login to the frontend and get a token and associated data. I can even login to the django app, then navigate to the frontend and calls are made with the correct session information and it all works fine. The challenge is when I just login to the frontend and make a call to the django app it doesn't recognize it as being an authenticated user request - I am guessing it has something to do with not creating a django session, but am honestly a bit lost at this point. Is there a way to ingest the token information and have django authenticate the user and start a session when the call is made from the frontend? -
How to use react-image-crop with python-django backend cropping?
I am trying to use Python Pillow to crop the images with react-image-crop and it seems to be working fine, but I can not figure out how to set the scale (zooming) to be working with the backend. Any help would be greatly appreciated! Frontend- (React) const scaleX = imgRef.current.naturalWidth / imgRef.current.width const scaleY = imgRef.current.naturalHeight / imgRef.current.height const pixelRatio = 1 const cropX = crop.x * scaleX const cropY = crop.y * scaleY const width = Math.floor(crop.width * scaleX * pixelRatio) const height = Math.floor(crop.height * scaleY * pixelRatio) const formData = new FormData() formData.append('crop_x', cropX) formData.append('crop_y', cropY) formData.append('crop_height', height) formData.append('crop_width', width) formData.append("image", localImage) const response = await axios.post('/image/upload/', formData) Backend - (Django) from PIL import Image temp_image = Image.open(form.image) left_x = float(form.get('crop_x')) top_y = float(form.get('crop_y')) right_x = left_x + float(form.get('crop_width')) bottom_y = top_y + float(form.get('crop_height')) thumbnail_image = temp_image.crop((left_x, top_y, right_x, bottom_y)) -
Query parameter doesn't match any record returns "Select a valid choice. That choice is not one of the available choices." instead of empty array
I'm using DjangoFilterBackend to handle query parameters on a ModelViewSet. My expectation would be that if nothing in the table matches one of the query params, that it would just return an empty array. Instead it returns: { "document_guid": [ "Select a valid choice. That choice is not one of the available choices." ] } Which just seems like an odd response to me so I'm wondering: how can I change this behavior? Would much rather just have the following indicating nothing matched: [] I'm aware of this similar question, but I'm already doing what they suggested: https://stackoverflow.com/a/62219220/3123109 Here's the URI where there are no records that match document_guid (but there are some that match user_guid): localhost/api/d2u/?user_guid=55d57235-79b0-ec11-9840-000d3a5a343c&document_guid=df4c9c11-49dd-ec11-a7b6-000d3a3667a1 Here's the related code: # views.py class Document2UserSyncViewSet(viewsets.ModelViewSet): filter_backends = [DjangoFilterBackend] filter_fields = [ 'id', 'document_guid', 'user_guid' ] permission_classes = [PowerAutomatePermissions] queryset = Document2User.objects.all().order_by('id') serializer_class = Document2UserSerializer # serializer.py class Document2UserSerializer(serializers.ModelSerializer): """Serializer for the d2u model. Returns all fields. """ class Meta: model = Document2User fields = '__all__' # models.py class Document2User(models.Model): document_guid = models.ForeignKey( Documents, to_field='guid', on_delete=models.CASCADE, db_column='document_guid' ) user_guid = models.ForeignKey( CRMFields, to_field='guid', on_delete=models.CASCADE, db_column='user_guid' ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'document_to_user' unique_together = [['user_guid', 'document_guid']] -
Load data from model in view.py Django
I just started with Django and Python and I still don't understand it very well. Would it be possible to access all the information stored in Persons, showing also orderstext and archivename, I can't manage to do it :( my idea is to get all the information and save it as JSON, but I'm not getting the info from orderstext and archivename, it would be great if someone could show me the right way. models.py from django.db import models class Order(models.Model): order_id = models.PositiveIntegerField(blank=True, null=True) orderstext = models.CharField(max_length=250, blank=True, null=True, ) order_start = models.DateTimeField(blank=True, null=True) order_end = models.DateTimeField(blank=True, null=True) @property def default(self): return self.orderstext class Meta: managed = False db_table = 'order' class Archives(models.Model): archive_id = models.AutoField(primary_key=True, null=False) archivename = models.CharField(max_length=50, unique=True, blank=True, null=True) deleted = models.IntegerField(blank=True, null=True) def __str__(self): return self.archivename @property def default(self): return self.archivename class Meta: managed = False db_table = 'archives' class Clients(models.Model): name = models.CharField(max_length=20, verbose_name="Name") lastname = models.CharField(max_length=50, blank=True, null=True, verbose_name="Lastname") archives = models.ForeignKey('Archives', db_column='archive_id', on_delete=models.CASCADE, null=True, verbose_name="Archives") order = models.ForeignKey('Order', db_column='order_id', on_delete=models.CASCADE, null=True, verbose_name="Order") coments = models.CharField(max_length=250, blank=True, null=True, verbose_name="Coments") class Meta: managed = False db_table = 'clients' views.py from django.http import JsonResponse from .models import Clients def data_json: info = list(Clients.objects.all().values()) response … -
Can't find the Django Docs that list DetailView attributes
Working through the Django tutorial and on the Detail and List class-based views portion. When I go to the docs for the DetailView, it doesn't really list any of the attributes I can use or the tutorial uses. Any chance someone has a link to the page where I can read up on attributes like: -Model -Context_object_name -template_name -etc... I just like to understand what Im doing a bit more than the tutorial explains, just cant seem to find the proper docs when googling :(