Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Suggestion of a framework for an amateur Python developer
I'm developing a Music database solution to help Dance teachers (Biodanza) share their music collections. The collections are stored in SQL database and I use Python to import new music collections. This is a semi-automated iterative process unlikely to ever be fully automated. So Python is really the way to go. I now need a front end to surface this database to users to allow them to select songs and build new playlists to share with other teachers. I spoke to an IT pro colleague who told me to learn ReactJS, but when I looked into it, I realized it's Javascript based, which I'm not very versed on, and I also will need to learn NodeJS. While meddling with Python, I came across Flask and Django as possible alternatives. The literature AFAIK tells me I would need to develop from base if I use Flask, while Django things are more out of the box. What I need is a pretty simple CRUD application, that let users select songs based on filters such as genre, dance types and few keywords in the field. My main issue is I have about 30 hrs available in total to learn a framework and develop … -
Django - How to get all related objects in ManyToMany relation
I have a Task model with self referencing. Every task can have multiple tasks as precondition tasks. class Task(models.Model): title = models.CharField(max_length=64) precondition_tasks = models.ManyToManyField(to='self', symmetrical=False) I need a query to get all related tasks. eg: a is pre_task of b and b is pre_task of c I want if I get a, I also receive b and c because a is pre_task of b, and also b is pre_task of c. I can do this by for loop and a recursive function. But i know this is terrible. I need to do this and get all related objects by query, not for loop or something like that in Python. -
primary key for users
primary key is created automatically for every row in table right, but for users isnt it better to use their username as primary key? or defaults better? or for posts like a music post or a picture shouldn't we use its name as primary key? if yes how should i change urls ? i mean this is my urlspath('genre_list/<int:pk>/',views.GenreDetailView.as_view(),name='genre_detail'),and path is int shoul i just remove int and let it be like <pk> or text primary key has another way? -
How to expire user token if particular field value is updated in User model in Django?
I'm trying to make a signal to expire the user token if a field value is updated in the User model. This is the signal I've written. But for some reason, instance.is_corporate_profile_admin is giving older data and not the data which is recently saved or sent from the request when the API was hit. apps.py class UserConfig(AppConfig): name = 'user' def ready(self): from . import signals request_finished.connect(signals.task_token_expire) signals.py def expire_user_knox_token(user_id : int, time : object) -> bool: from knox.models. import AuthToken try: _ = AuthToken.objects.filter(user_id=user_id).update(expiry=time) return True except: return False @receiver(post_save, sender=UserDetail) def task_token_expire(sender, instance, **kwargs): if instance and instance.id: from django.db import transaction with transaction.atomic(): from datetime import datetime logout_time = datetime.now() # If is_cp_admin value changed or if no user entry in UserDetailOlderValues then only token expire. try: older_is_cp_admin_value = UserDetailOlderValues.objects.filter(user=instance).order_by('-id').first().is_corporate_profile_admin print('older_is_cp_admin_value------------->', older_is_cp_admin_value) print('new value------------->', instance.is_corporate_profile_admin) # ! THIS VALUE IS NOT THE LATEST VALUE WHICH IS SENT IN THE REQUEST if instance.is_corporate_profile_admin != older_is_cp_admin_value: expire_user_knox_token(user_id=instance.id, time=logout_time) _obj, _created = UserDetailOlderValues.objects.filter(user=instance).update(is_corporate_profile_admin=instance.is_corporate_profile_admin, last_token_expired_at=logout_time) except: expire_user_knox_token(user_id=instance.id, time=logout_time) _obj, _created = UserDetailOlderValues.objects.update_or_create(user=instance, is_corporate_profile_admin=instance.is_corporate_profile_admin, last_token_expired_at=logout_time) I tried using pre_save before post_save, to hold previous data but both pre_save and post_save are fetching same older data. So, I created another model to save … -
Django Slugify with blank object field printing "none" in url
class Entry(models.Model): name = ... city = ... zip_code = ... def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(f"{self.name}-{self.city}-{self.zip_code}") return super().save(*args, **kwargs) Url is being returned as www.example.com/name-city-zip_code. If an object has is missing a city, then url is returning: www.example.com/name-none-zip_code How can I add an if statement in the F string in order to only display an object field if it is not None? I tried the following but did not work: self.slug = slugify(f"{self.name}-{self.city}-{self.zip_code}").replace("none",""). self.slug = slugify(f"{self.name}-{self.city}{% if self.zip_code %}-{self.zip_code}{% endif %}"). self.slug = slugify(f"{self.name}-{self.city}if self.zip_code:-{self.zip_code}"). self.slug = slugify(f"{self.name}-{self.city}if self.zip_code-{self.zip_code}"). -
Using cloudprnt with python with mc-print3
Does anyone know how to use cloudprnt with mc-print3? Unfortunately, StarTSP's support wasn't able to help or provide any tutorials. -
Is there a reason why this django form isn't valid?
my form is only valid when i just use {{ post_form }} without specifying the field, i know this because when i tried it i was able to save it to the data base, so i think i'm doing something wrong in my template. by the way none of these fields are required so i believe they should be able to go empty in the data base... right? this is the html form: <section id="newpost-form"> <form action="{% url 'newpost' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label for="id_title">Title</label> {{ post_form.title }} <label for="id_image">Thumbnail</label> {{ post_form.image }} {{ post_form.content }} {{ post_form.media }} // this one is for a ckeditor rich text area called content <button type="submit" class="btn">Create</button> </form> </section> this is forms.py class NewPost(forms.ModelForm): class Meta: model = Post fields = ['image', 'title', 'content', 'status', 'author',] and my views.py in case it is relevant: if request.method == 'POST': post_form = NewPost(request.POST, request.FILES) if post_form.is_valid(): ... -
Getting 'role ___ does not exist' when running Django makemigrations
I am attempting to connect a Django app to a local database, per the instructions here. My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'service': 'my_service', 'passfile': '.my_pgpass', }, } } My .pg_service.conf: [my_service] host=localhost user=firstlast dbname=my_db port=5432 My .my_pgpass: localhost:5432:my_db:firstlast:password I've defined a new Model, and when I run python manage.py makemigrations myapp I get the following error: /path/to/myproject/venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: role "first" does not exist warnings.warn( No changes detected in app 'myapp' Note that the role in the error is different than the user defined in .pg_service.conf and .my_pgpass. Why is the user wrong? Why am I unable to connect to the database? Thanks in advance for the help. Apologies if there is something obvious I am missing. -
How do I get a CSRF token for Django's auth contrib views if my frontend app is not served by Django?
I'm using Django 3.1.1 with Django's auth contrib module for managing users. I'm not using Django templates, but rather creating a Django API application to respond to requests from my React frontend. I have this in my settings.py file MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'directory.middleware.extend_token_response.ExtendTokenResponse' ] #CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'dev.mywebsite.com', 'prod.mywebsite.com', 'map.mywebsite.com'] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://localhost:3001', 'http://127.0.0.1:3000', 'http://127.0.0.1:3001' ] CORS_EXPOSE_HEADERS = [ 'Refresh-Token', 'Content-Type', 'Authorization', 'X-CSRFToken' ] CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ['localhost', '127.0.0.1'] I have this set up in my views.py file class ResetPasswordView(SuccessMessageMixin, PasswordResetView): email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') def post(self, request, *args, **kwargs): print("request data %s" % request.data) email = request.data.get('email') try: if User.objects.get(email=email).active: print("email: %s " % email) return super(ResetPasswordView, self).post(request, *args, **kwargs) except: # this for if the email is not in the db of the system return super(ResetPasswordView, … -
streaming data/variables to templete using django
I have a method that returns float variables and I m streaming it to an HTML template using StreamingHttpResponse in Django, to catch the variable I found a way to use XMLHttpRequest in ajax as shown in the code below: #method to return speed as a list of three float values def gen_speed(video_feed): while True: speed, frame, gray, output = video_feed.get_frames() yield speed def speed_stream(request): try: pathVideo = r"static\app_resources\videos\rl4_pb8-7.mp4" cam = model.video_feed(pathVideo) stream = model.gen_speed(cam) response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream') #response['Cache-Control'] = 'no-cache' return response except: pass this is code is in my HTML : <script> url = '{% url "test_stream" %}'; let xmlhttp = new XMLHttpRequest(); xmlhttp.open("get", url, true); xmlhttp.send(); function handleEvent(e) { console.log(e.target.responseText); } xmlhttp.addEventListener('progress',handleEvent); } <script> the results are like this : as you see the streaming is working but the problem is that I don't know how to handle the values in the template, the values that XMLHttpRequest catches are not separated. what I want is a way to catch this dictionary and access to it so that I can give each value to a streaming chart each time. -
TypeError: object of type 'NoneType' has no len()
I tried this code with the library django-zxcvbn-password when i do it without using this library everything work but when i use this library it seems like when i write a weak password the password field doesn't receive it and that lead to a NoneType Object because password is empty, and i don't know why but when i try it with a good password everything works perfectly. I use this library for security purpose. class SignUpForm(forms.Form) """password_regex = RegexValidator( regex=r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$', message="Password must be at least 8 characters in length and contain at least one uppercase letter, " "one lowercase letter, and one digit. " )""" name_regex = RegexValidator( regex=r'^[A-Z][a-z]{2,149}$', message="Names must begin with an uppercase letter followed by lowercase letters." ) username_regex = RegexValidator( regex=r'^[a-zA-Z][a-zA-Z0-9]{5,149}$', message="Username must begin with a letter followed by letters or digits and have a length of at least 6 " "characters and a maximum of 150 characters. " ) username = forms.CharField(validators=[username_regex], min_length=5, max_length=150) email = forms.EmailField(validators=[EmailValidator], error_messages={'invalid': 'Please enter a valid email address.'}) first_name = forms.CharField(validators=[name_regex], min_length=2, max_length=150) last_name = forms.CharField(validators=[name_regex], min_length=2, max_length=150) password = PasswordField() confirm_password = PasswordConfirmationField(confirm_with='password') #password = forms.CharField(widget=forms.PasswordInput, validators=[password_regex], min_length=8) #confirm_password = forms.CharField(widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() password = … -
MultipleObjectsReturned at /api/protein/A0A016S8J7
I'm trying to combine 2 columns from 2 csv files. The first file have multiple rows with the same entry. The second file has rows with entries that the first file did not have. col1 ---- a a b b c d col2 ---- a b d e f colCombined ---- a b c d e f This is the python script I wrote that suppose to merge together the 2 columns: proteinIds = set() with open(assignment_data_set) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: proteinIds.add(row[0]) with open(proteinSequence_data) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: proteinIds.add(row[0]) proteinIds_rows = {} for item in proteinIds: row = ProteinId.objects.create(protein_id=item) row.save() proteinIds_rows[item] = row I used a python set, so it's not supposed to have duplicates. This is my model for the proteinIds: class ProteinId(models.Model): protein_id = models.CharField(max_length=10, null=False, blank=False, primary_key=True) def __str__(self): return self.protein_id However, when i try to retrieve a proteinid, I still get an error: MultipleObjectsReturned at /api/protein/A0A016S8J7 get() returned more than one Protein -- it returned 2! What am I doing wrong? -
how to solve origin 'http://127.0.0.1:9000' has been blocked by CORS policy
Access to font at 'https://fra1.digitaloceanspaces.com/ewan-space/ewan/static/admin/fonts/Roboto-Light-webfont.woff' from origin 'http://127.0.0.1:9000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. i see tihis erorr in django admin when i collect my static in digitalochenspace , and it's work fine in when collect static in localhost, this is my code settings #installed apps "corsheaders", MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware",] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL=True django 3.2 python 3.8 how to solve this problem ? -
How to cycle through images on Django website
I have built a photo gallery and I when an image is opened I would like to add to buttons ( Previous & Next) Which will cycle through my images based on their id/pk. Models.py class PostImage(models.Model): image = models.ImageField(null=False, blank=False, upload_to="images", default="default.png") image_title = models.CharField(max_length=100, null=False, blank=False, default="") def __str__(self): return self.image_title class Meta: verbose_name_plural = 'PostImage' Views.py def galleryPage(request): images = PostImage.objects.all() context = {'images':images} return render(request, 'gallery.html', context) def viewImage(request, pk): photo = PostImage.objects.get(id=pk) return render(request, 'viewimage.html', {'photo': photo}) HTML <div class="image-container"> <div class="image-post"> <a href="{% url 'gallery' %}" ><img class="photo-img" src="{{photo.image.url}}" /></a> <h2 class="photo-title">{{photo.image_title}}</h2> <p class="contact"> Interested in purchasing this as a print? Contact me for more information regarding price and sizes. </p> <a href="{% url 'contact' %}" class="btn btn-secondary" type="button" >Contact</a > </div> </div> </body> </html> -
why am i getting the error ManyRelatedManager' object has no attribute 'publications' in django rest framework
i have a many to many relationship between a model called topic and publication , when i'm trying yo serializing data related to the publication model i get the error below enter image description here here is my model : class Publication(models.Model): title = models.CharField(max_length=30) content = models.CharField(max_length=1000) image = models.ImageField(upload_to='blog_images/') class Topic(models.Model) : name = models.CharField(max_length=40) publications = models.ManyToManyField( Publication, related_name='topic' ) def __str__(self) : return self.name here are my serializers : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username' , 'profile_pic'] class CommentSerializer(serializers.ModelSerializer): sender =UserSerializer(many=False) class Meta : model = Comment fields = ['sender'] class TopicSerializer(serializers.ModelSerializer): class Meta : model = Topic fields = '__all__' class PublicationSerializer(serializers.ModelSerializer): topic = TopicSerializer(many=False) publication_comments = CommentSerializer(many=False) class Meta : model = Publication fields = '__all__' and here are my views : @decorators.api_view(['GET']) def get_publications(request,pk=None): if pk : instance = Publication.objects.get(pk=pk) return response.Response( PublicationSerializer(instance , many=None).data) topic = request.query_params.get('topic') if request.query_params.get('topic') else '' title = request.query_params.get('title') if request.query_params.get('title') else '' qs = Publication.objects.all() data = PublicationSerializer(qs, many =True).data return response.Response(data , status=200) i tried to return a filtered queryset -
Edit blog post on Django but not make it visible until finished
The question is basically in title. I was wondering if there is a way for a user to edit a blog post in Django admin but not make it visible to the public until finalized? -
Converting base64 to video
i posted file by api in js of type string as shown in picture so i need to convert str base64 to video file when converting in python the generated file as shown in screenshot its lieke text the lesson_vid = request.POST.get('lesson_video') print(type(lesson_vid)) output is : <class 'str'> the question is how to save mp4 video from str base64 -
How to load image from Django content field in Next.js?
Hello everyone and Happy New Year! Please tell me, I have data coming from the Django API, there is a TextField field, it uses the markdown editor. Loading the text, I get everything except the image. The reason it won't load is the wrong link because it looks like this: media/uploads/image.jpg Next.js, in turn, tries to add an address to it, did this: localhost:3000/media/uploads/image.jpg, but localhost:8000/media/uploads/image.jpg will be correct, how to make an absolute link? There are no problems with the preview, everything can be configured there. -
Django - create code blocks in html templates
I would like to create a web page that will display data I have in a table inside a code block just the way it is here, even with a copy function. I can already display the data on the page, I just like to have it formatted in a pretty box, maybe even with syntax highlights, I looked at Pygments but I can't get it to work. Below is a sample code block that I would like to re-create in my Django app. Please don't pay attention to the actual code, this is only a sample. I would appreciate if you could please let me know in detail how to implement this. # Python Program to find the area of triangle a = 5 b = 6 c = 7 # Uncomment below to take inputs from the user # a = float(input('Enter first side: ')) # b = float(input('Enter second side: ')) # c = float(input('Enter third side: ')) # calculate the semi-perimeter s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area) -
DRY: how to get a basic React/Apollo web app and python GraphQL backend API going with minimal duplication?
I'm an experienced SWE but sort of new to modern web development. I'd like to build a demo/prototype website for a startup idea with minimal time. I'd like to have the frontend tied to a backend DB store up front so it's fully functional. I'd like advice on the best stack to use. I'd like a python backend, and I'm planning on React for the frontend, with GraphQL (unless this is a dumb idea for a prototype... I'd like to learn about it though.) I feel like there is a ton of redundancy in terms of data object models. I can make a GraphQL schema (I was thinking of using ariadne + FastAPI) but then I still need to build DB tables, or create an object model e.g. in Django. And then of course there is all the React code to make forms to edit stuff. My app will require a significant amount of data entry on the website to set up users and lots of metadata. I built a ton of forms etc in React, backed by Apollo client. Any suggestions -- am I on the right track or is there a quicker way to a prototype? Are there … -
Django forms - limiting options from fields based on the answer of another field
I have a Django form the receives entries from the users with information on a surgical procedure. Each Procedure will have only one (surgical) Technique and only one Diagnosis. Each Technique may be related to a limited number of Diagnosis, and each Diagnosis may be used on different Techniques. I want to limit which Diagnosis appear of the form based on which Technique the user selected previously on the form. I tried using smart_selects ChainedManyToMany field with relative success, but it enable multiple Diagnosis to be selected, I only want to have one. I`m also using DAL for autocompleting the Technique (over 1,6k options) as the user types. My models: # The "Technique" model class Sigtap(models.Model): codigo = models.CharField(max_length=10) descricao = models.CharField(max_length=175, default='') # The "Diagnosis" model class Cid10(models.Model): codigo = models.CharField(max_length=4) descricao = models.CharField(max_length=270, default='') sigtap_compativel = models.ManyToManyField(Sigtap, blank=True) # The "Surgical Procedure" model class Cirurgia(models.Model): paciente = models.PositiveIntegerField(verbose_name='Número do prontuário') data = models.DateField(verbose_name='Data de realização') procedimento = models.ForeignKey(Sigtap, on_delete=models.CASCADE, verbose_name='Código do procedimento (SIGTAP)') cid = ChainedManyToManyField( Cid10, horizontal=True, chained_field='procedimento', chained_model_field='sigtap_compativel', auto_choose=True, verbose_name='CID-10') My forms: class CirurgiaModelForm(forms.ModelForm): class Meta: model = Cirurgia fields = ['paciente', 'data', 'procedimento', 'cid'] widgets = { 'procedimento': autocomplete.ModelSelect2(url='sigtap-autocomplete'), } Maybe a better approach to … -
Not getting the data on request from ajax on Django API
I've this button, on click i'm calling a function that would disappear once clicked and would send the data to django api. <button type="button" class="btn btn-success" id="Approved" onclick="approveFunction()">Approve</button> <script> var button1 = document.getElementById("Approved"); function approveFunction() { button1.style.display = "none"; console.log('hello') approved = 'Approved' $(document).ready(function () { $.ajax({ url: "/stitch/admin/approvals/detail/status", dataType: "html", data: { 'Approved': approved }, success: function (response) { console.log('hiiiiiiiiiii') } }); }); } </script> This is the url and api i've created(don't worry about stitch in the ajax url, it's supposed to be like that) url(r"^admin/approvals/detail/$", ApprovalDetail.as_view()), class ApprovalDetail(TemplateView): template_name = "admin/approval_detail.html" def get(self, request, *args, **kwargs): id = request.GET.get('id') approval_detail = Approval.objects.filter(id=id) approval_status = request.GET.get('Approved') rejection_status = request.GET.get('Rejected') if approval_status: print('Approved') # Approval.objects.filter().update(status='Approved') if rejection_status: print ('Rejected') # Approval.objects.filter().update(status='Rejected') if approval_status is None and rejection_status is None: print('Unapproved') return render(request, self.template_name,{'approval_detail':approval_detail}) Btw this is the same api i'm using to render the html page in which i'm showing the button and want to send the ajax data to. I'm doubting if even this is possible. Tried to send the data to the api, but not getting it. -
Anyway to join this query and make one query in django filter
post_search_comments= PostInLanguages.objects.filter(comment_data__is_post_comment=True).annotate(c=Count('comment_data', distinct=True)).filter(c__gte=0) post_search_likes = PostInLanguages.objects.annotate(l=Count('like_model', distinct=True)).filter(l__gte = 1) I need to make one query from these above queries. Needed post objects which has minimum likes and minimum comments. For now im using intersection intersection = post_search_comments & post_search_likes print(intersection) paginator = CustomPageNumberPagination() page = paginator.paginate_queryset(post_search_comments, request) serializer = PostInLanguagesSerializer(page, many=True) response = paginator.get_paginated_response(serializer.data) return response -
VsCode can't resolve Django Imports
I just woke up and shockingly VsCode can't resolve imports in all my Django projects. Some were using venv and some pipenv, but they have all stopped resolving imports. I have tried the answers which all seem to say I should select the python.exe from the Script folder of the respective projects virtual environment`. But as you can see below, that ain't working. Any pointers? -
When trying to update an instance of related models I get the Ids on the template instead of the names, using {{form}}
URLS.py urlpatterns = [ path('stock/update/<int:pk>/', views.StockUpdateView, name='stock-update'), VIEWS.py def StockUpdateView(request, pk): stock = Stock.objects.get(id=pk) form = StockForm(instance=stock) if request.method == 'POST': form = StockForm(request.POST, instance=stock) if form.is_valid(): form.save() return redirect('/inventory/stock') context = {"form": form} return render(request, 'inventory/update-stock.html', context) TEMPLATE.html <form action="" method="POST" class="row g-3"> <div class="col-auto"> <h6>Stock update form:</h6> {% csrf_token %} {% for field in form %} <div class="form-control"> {{field}} </div> {% endfor %} I have changed from using the {{ form }} tag to looping over the fields trying to get the name of the related table instead of the IDs.