Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can't save form data
I'm working on a django project and faced a weird problem. I am using `model form` for this. Even though I wrote `form.save()` as you can see it below, new data is not saved. # in views.py class ProductUpdateView(self, request, product_id): def get(self, request, product_id): product = get_object_or_404(Product, id=product_id) name = product.name id = product.id form = ProductEditForm(instance=product) context = { "form": form, "name": name, "id": id, } return render(request, "management/product_detail.html", context) def post(self, request, product_id): form = ProductEditForm(request.POST, instance=request.user) product = get_object_or_404(Product, id=product_id) if form.is_valid(): form.save() messages.success(request, f"'{product.name}' is successfully updated!") return redirect("products_list") else: messages.warning(request, "form is invalid") return redirect("products_list") # in forms.py class ProductEditForm(forms.ModelForm): class Meta: model = Product fields = ["name", "description", "price", "is_available", "category"] def __init__(self, *args, **kwargs): super(ProductEditForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs["class"] = "form-control" Thank you in advance. -
Error In Accessing the Camera in Face Recognition Application in Centos server in django application
I have implemented the Face Recognition Module in Django Application As I am not able to access the camera in the application Error occurred while trying to access the camera VIDEOIO ERROR: V4L: can't open camera by index 0 (cv2.VideoCapture(0)) and It is showing as select timeout while accessing the camera in the Html browser Code which i have Implemented it cam = cv2.videocapture(0) img_counter = 0 DIR = f"folder/foldertwo/folderthree/{dirName}_{dirID}" try: os.mkdir(DIR) print("Directory ", dirName, " Created ") except FileExistsError: print("Directory ", dirName, " already exists") img_counter = len(os.listdir(DIR)) while True: ret, frame = cam.read() if not ret: break cv2.imshow("Video", frame) k = cv2.waitKey(1) if k%256 == 27: print("Escape hit, closing...") break elif k%256 == 32: img_name = f"folder/foldertwo/folderthree/{dirName}_{dirID}/image_{img_counter}.png" cv2.imwrite(img_name, frame) print("{} written!".format(img_name)) img_counter += 1 cam.release() cv2.destroyAllWindows() -
Django server stops on multiple requests
I am using Django server with ORM for my backend. When I am running multiple requests in parallel the Django server stops at execute_from_command_line(sys.argv) in manage.py. I can't get actual exception. If anybody knows how to solve, help me. -
Login authentication for react application
I am using Django session based auth for my single page app. I am using below APIs for handling the login and logout functionality. I have used the axios for getting the response from these APIs. url.py from django.urls import path from . import views urlpatterns = [ path('csrf/', views.get_csrf, name='api-csrf'), path('login/', views.login_view, name='api-login'), path('logout/', views.logout_view, name='api-logout'), path('session/', views.session_view, name='api-session'), path('whoami/', views.whoami_view, name='api-whoami'), ] Now I want to add the login/auth logic in my react app, i.e. if user has session then user should redirect to main page otherwise it should redirected to login page. How can i implement the authentication logic for the same? views.py from django.http import JsonResponse from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView class SessionView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] @staticmethod def get(request, format=None): return JsonResponse({'isAuthenticated': True}) class WhoAmIView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] @staticmethod def get(request, format=None): return JsonResponse({'username': request.user.username}) -
Filter parent objects which have no children object using refetch_related
I have three models as following, with Seller as the grandparent, Genre as the parent and Book as the chidlren: class Seller(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Genre(models.Model): seller= models.ForeignKey(Seller, related_name="genre", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name class Book(models.Model): genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name If I use prefetch_related() to fetch the Seller objects along with their Genre and Book as following in one single databse query: sellers = Seller.objects.prefetch_related('genre__book').filter() However, I would like to filter out Seller objects that have no Book objects related to. What would be the syntax for the filter() in this case? -
Djnago signals how to delete old object if new object created?
I am using django signals for showing notifications. If any post created in my blog then it will notify the blog author and pending for admin approval see the picture: if admin approve the blog post then author will get another new notification. I want to delete old pending notification of post1 if new notification created for post1. see the picture: here is my signals code for create notification: class Blog(models.Model): .....my fields #signals code def blog_notify(sender, instance, *args, **kwargs): blog = instance blog_title = blog.title sender = blog.author if sender == blog.author and blog.is_published == "published": notify = Notifications(blog=blog, sender=sender, user=sender,text_preview = blog_title[:250], notification_type="post approved") notify.save() if sender == blog.author and blog.is_published == "pending": notify = Notifications(blog=blog, sender=sender, user=sender,text_preview = blog_title[:250], notification_type="pending post") notify.save() post_save.connect(Blog.blog_notify, sender=Blog) -
Remote rejected main -> main (pre-receive hook declined)
I'm a beginner with heroku and I require some help. I spent the whole morning trying to solve this issue [remote rejected] main -> main (pre-receive hook declined) but still cant. After i edit something everytime, i will type git add -A git commit -m "Update #" git push origin main After this 3 commands, I check my github and it is all updated. So i type git push heroku main But the output of this is always ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/whispering-wildwood-75050.git' I redo this part like 4 times already following this guide https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment and sometime when I am lucky i managed to get past the [remote rejected] main -> main (pre-receive hook declined) and I type heroku open I get this error DisallowedHost at /. So following the advice by net i add **whispering-wildwood-75050.herokuapp.com' to ALLOWED_HOSTS under settings.py. Then the issue of [remote rejected] main -> main (pre-receive hook declined) comes again after i git add -A git commit -m "Update #" git push origin main git push heroku main Appreciate if anyone can help me on this -
Overwriting Datetime is not working in Postgresql in Django
So what I need to do is to change few rows in a model DateTime field to 40 days in the past, with Django using a PostgreSQL database. Where I choose all products with an even ID and change the date_uploaded value. This is what I am currently doing... from django.core.management.base import BaseCommand from store.models import Product import datetime class Command(BaseCommand): def handle(self, *args, **options): all_products = Product.objects.all() for product in all_products: if product.pk % 2 == 0: product.date_uploaded = product.date_uploaded - datetime.timedelta(40,2,0,0) product.save() print(product.date_uploaded) And for some reason when I try to save the product it works with no errors but the DateTime value is not changed. Is there anything wrong with what I am doing? this is my models.py class Product(models.Model): image1 = models.ImageField(upload_to="product_images", default="https://eblossomsl.s3-us-west-2.amazonaws.com/logo.png") image2 = models.ImageField(upload_to="product_images", blank=True) image3 = models.ImageField(upload_to="product_images", blank=True) image4 = models.ImageField(upload_to="product_images", blank=True) name = models.CharField(max_length=100, unique=True) category = models.CharField(choices=CATEGORY, max_length=20, default="HRT", db_index=True) price = models.PositiveIntegerField() search_query = models.TextField(blank=True, null=True) date_uploaded = models.DateTimeField(auto_now=timezone.now()) quantity_bought = models.PositiveIntegerField(default=0) Any help would be greatly appreciated since I am not sure what I am doing wrong. -
Customizing Django Admin Search
I want to customize my Django Admin Search form. Like this picture, I want to add select box to choose search fields. Is there any built in parameter in Django? or Is there other way to make this possible? enter image description here -
How do you set the default value for Django's 'on_delete=models.SET_DEFAULT'
In the example below, how--and where--do you set the default value? author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT) -
Deploy Django docker image with Jenkins
I would like to deploy the Django Docker image with Jenkins. I already had this pipeline created with the middle docker registry. For this, I have 2 Jenkins tasks Build the image and transfer to registry Pull from registry to desirable server and start image Now, I would like to avoid the docker registry to speed up the deployment. Right now I have something like this, but it DOESN'T work: --- - hosts: "{{ HOSTS|default('docker') }}" remote_user: "{{ USER }}" vars: deploy_port: "{{ DEPLOY_PORT|default(8080) }}" git_branch: "{{ GIT_BRANCH|default('Development') }}" python_settings: "{{ PYTHON_SETTINGS|default('Development') }}" su_user: "{{ SU_USER|default('test') }}" su_email: "{{ SU_EMAIL|default('test@test.si') }}" su_password: "{{ SU_PASSWORD|default('test') }}" app_container_name: "{{ APP_NAME|default('test') }}" tasks: - name: Remove old image docker_image: name: my-project-name-{{ git_branch }} state: absent force: yes - name: build django image docker_image: path: . name: my-project-name-{{ git_branch }} nocache: yes - name: Start django image docker_container: name: "{{ app_container_name }}" image: my-project-name-{{ git_branch }} state: started restart: yes restart_policy: always ports: - "{{ deploy_port }}:80" env: PYTHONUNBUFFERED: 0 DJANGO_ENV_NAME: "{{ python_settings }}" SU_USER: "{{ su_user }}" SU_EMAIL: "{{ su_email }}" SU_PASSWORD: "{{ su_password }}" tty: yes This give me the error in Jenkins raise errors.APIError(e, response, explanation=explanation)\r\ndocker.errors.APIError: 500 Server Error: Internal Server … -
How to align decimal point of price in django template?
I'm trying to display amount of money a user spent in a table. I want the display amount to look neat, but it looks like below https://i.stack.imgur.com/kOpQ3.png I want their dot to be on the black straight line. Thank you in advance. -
How can i make a website that contains a python algorithm
1.The algorithm : So i just did a python algorithm that allows you from an input list of ingredient print out 2 list one contains recipes that you can make with their ingredient the other list print recipes that you can't make and the ingredient that misses to do it.(i wrote all the recipes with their ingredient in the top of the script) 2.The problem : I want to put this into an aesthetic website or an application on web so my friend and everyone can us it and even for me ill be able to run it from my phone for exemple and even for the aesthetic but i don't know how to do it like should i learn django?? or html??please help N.B: sorry if i made some english mistakes also this is my first project in coding so please help me -
Django template variable conditionals don't evaluate properly?
This makes no apparent sense to me. As you can see in the code below, I am pulling customer subscription data from various page context objects in django. As you can see in the attached screenshot, the variables work, and (unless django template variable values are type casted?) the values do in fact match. Based on the if condition, the customer (user object)'s existing subscription should be classed "active" when the page loads, but it isn't? <div class="card-deck"> {% for product in products %} request.user.is_paysubscribed = {{ request.user.is_paysubscribed }}<br /> product.metadata.tier = {{ product.metadata.tier }}<br /> <div class="card mb-4"> {% for price in product.plan_set.all %} <div class="card-body{% if request.user.is_paysubscribed == product.metadata.tier %} active"{% else %}"{% endif %} id="{{ product.name|slugify }}-card" role="button" onclick="planSelect('{{ product.name|slugify }}-card', '{{ product.name }}', '{{ price.human_readable_price }}', '{{ price.id }}')"> <h5 class="card-title text-center"><label for="{{ product.name }}">redacted product name</label></h5> <p class="text-center">{{ price.human_readable_price }}</p> <p class="card-text">{{ product.description }}</p> </div> {% endfor %} </div> {% endfor %} </div> -
Allowing only the specific users or group of users to visit the specific page of the website in Django?
Let us suppose that there is a admin page in my website designed by me for doing some actions on the website. now i want that only few user that belongs to a specific can visit that page. other users should redirected or should have see an error page when they try to go at that page. for karan(admin ) can visit that page but not ram(simple user) you can also refer any link from the django docs thanks! -
How can I return an image generated in pillow in django without saving in db?
def build_image(image_data): template = Image.open("path/to/file/template.jpg") draw = ImageDraw.Draw(template) draw.text("(553,431)", f"{image_data.text}", fill=4324234, font=font) file = InMemoryUploadedFile(template, None, 'receipt.jpg', 'image/jpeg', template.tell, None) return FileResponse(file, as_attachment=True, filename='receipt.jpeg') I need to return the image that was modified, without saving it to the database. The above code gives the following error: A server error occurred. Please contact the administrator. I also tried the following option: rea_response = HttpResponse(template, content_type='image/png') rea_response['Content-Disposition'] = 'attachment; filename={}'.format('result.png') return rea_response But in this case, I get a corrupted file. (This format is not supported). django==3.0.6 -
How can I create a ForeignKey field only shows when author are current user?
How can I create a ForeignKey field only shows when author are current user? I want to create the admin only show the key that the current user create, and the foreignkey is limit by author is current user, too. models.py class costomize_work_type(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,editable=False,null=True) name = models.CharField(max_length = 10 ) def __str__(self): return self.name class Work(models.Model): name = models.ForeignKey(costomize_work_type, on_delete = models.CASCADE,limit_choices_to={'author': current user}) #other choice author = models.ForeignKey(User,on_delete=models.CASCADE,editable=False,null=True) admin.py class costomize_work_typeAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.author = request.user super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super(costomize_work_typeAdmin, self).get_queryset(request) return qs.filter(author=request.user) admin.site.register(costomize_work_type,costomize_work_typeAdmin) class WorkAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.author = request.user super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super(WorkAdmin, self).get_queryset(request) return qs.filter(author=request.user) admin.site.register(Work,WorkAdmin) -
Upload multiple images from a single button
My goal is to have a single button that a user can upload multiple images from. I implemented a bulk image upload feature from this stack posts top reply. It is somewhat working but instead of a single button it has multiple buttons for image upload How would I go about converting this to a single button that uploads multiple images to be uploaded view: def testing(request): ImageFormSet = modelformset_factory(PostImages, form=ImageForm, extra=1) if request.method == 'POST': postForm = PostForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=PostImages.objects.none()) if postForm.is_valid() and formset.is_valid(): testID = postForm.save(commit=False) testID.user = request.user testID.save() for form in formset.cleaned_data: #this helps to not crash if the user #do not upload all the photos if form: image = form['image'] photo = PostImages(post=PostForm, image=image) photo.save() # use django messages framework messages.success(request, "Yeeew, check it out on the home page!") return HttpResponseRedirect("/") else: print(postForm.errors, formset.errors) else: postForm = PostForm() formset = ImageFormSet(queryset=PostImages.objects.none()) return render(request, 'blog/test.html', {'postForm': postForm, 'formset': formset}) template: <form id="postID" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {% for hidden in postForm.hidden_fields %} {{ hidden }} {% endfor %} {% for field in postForm %} {{ field }} <br /> {% endfor %} {{ formset.management_form }} {% for form in formset %} … -
Chaining prefetch_related in reverse Foreign Key queries
This is a follow-up question from this thread. Suppose I have the following 3 models: class Seller(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Genre(models.Model): seller= models.ForeignKey(Seller, related_name="genre", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name class Book(models.Model): genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE) name = models.CharField(max_length=20) def __str__(self): return self.name If I want to fetch specific Seller objects and Genre in one query, I can do this: sellers = Seller.objects.prefetch_related('genre').filter(name__in=['Amazon', 'BarnNoble', Kinokuniya']) Or if I want to fetch specific Genre objects and Book in one query, I can do this: genres= Book.objects.prefetch_related('book').filter(name__in=['Horror', 'Romance', 'Travel']) Is it possible to to chain the two into one single query (albeit a more complex query)? When I tried this: sellers = Seller.objects.prefetch_related('genre').prefetch_related('book').filter(name__in=['Amazon', 'BarnNoble', 'Kinokuniya']) I get the error: Cannot find 'book' on Seller object, 'book' is an invalid parameter to prefetch_related() -
Django management command with dynamic arguments
How would you create a Django management command that has arguments that are dynamic depending on a positional argument? For example, the key value arguments for the command: python manage.py dynamic_command option1 should be different from the arguments for: python manage.py dynamic_command option2 This is useful for cases where the underlying command handle is the same, but parameters could vary depending on the context that the command is run. -
Get the latest UUID created in django model
i want to get the id of the latest entry in a django model, i m using UUID and this query is not working for me it is giving me another id of a fields submitted before that is by some comparaison the biggest. Uploads.objects.latest('id') -
Is it possible to access the value of different tables connected by ForeignKey Django
So I've created a little database relationship for the question: from django.db import models # Create your models here. class Poll(models.Model): title = models.CharField(max_length=255) date_created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) def __str__(self): return self.title class Option(models.Model): title= models.CharField(max_length=50) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) desc = models.CharField(max_length=255) def __str__(self): return self.title class Voter(models.Model): name = models.CharField(max_length = 255) option = models.ForeignKey(Option, on_delete=models.CASCADE) def __str__(self): return f'{self.name} - {self.option}' So I have 2 questions: Is it possible to access the value of Option model's desc field from Voter model's __str__ function ? Is it possible to access the value of Poll model's date_created field from Voter model's __str__ function ? Thank you so much! -
Django view requests for a specific time period from database
I am developing a project with Django. I want to display the requests from the database in a certain time interval, for example datetime.now() - I want to display the requests 2 minutes ago. Is there a filtering code you can suggest for this? -
could not translate host name "postgres" to address: Unknown host
Setting up a Django project but I am getting a warning about setting up postgres as shown in the title, but I am unsure what this means. Full warning message: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres" to address: Unknown host And here is how I define postgres in my settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("DB_NAME", "dbname"), "USER": os.environ.get("DB_USER", "dbuser"), "PASSWORD": os.environ.get("DB_PASSWORD", "dbpassword"), "HOST": os.environ.get("DB_HOST", "postgres"), "PORT": os.environ.get("DB_PORT", "5432"), } } Would it possible for someone to walk me through what is going wrong here? I have no idea. -
Djngo How to get GET parameters in template
I'm working on a django project. I'm wondering how to get GET parameters in template so that I can make corresponding tab active. I tried the code below, but it didn't work. <a href="{% url 'blah'%}" class="list-group-item {% if '?q=' in request.path %}active{% endif %}"> lorem ipsum </a> Thank you in advance.