Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I have an image field in a Django Model?
I wanted to have a feature on my website that allows you to click on a link near an image and have that take you to another page which displays the image and a description. I figured that I could do this with a Model that has an image field and a text field for the description, but I don't know how to store an image! Is there a function or such that allows you to have an image field in a Django model? If so, what is it and where do I need to store images relative to the models.py file for it to work? Thanks in advance. -
DRF test multiple image upload
I'm trying to test multiple image upload to my server. Here is the serializer: class ImageSerializer(serializers.ModelSerializer): image = serializers.ListField( child=serializers.ImageField(allow_empty_file=True) ) ImageFactory: def get_image(): image = Image.new("RGB", (2000, 2000)) file = tempfile.NamedTemporaryFile(suffix=".jpg") image.save(file) return file Test: def test_upload_multiple_images(self): self.image = get_image() with open(self.image.name, "rb") as file: payload = { "image": [file, file] } response = self.client.post( reverse("gallery-list", args=[self.item.pk]), data=payload, format="multipart" ) When testing via Postman, images from the array are saved correctly. However when using the test case, I get the following message from the response: {'image': [{'message': 'The submitted file is empty.', 'code': 'empty'}]} Before adding allow_empty_file=True, there were two of those messages being returned. Has anyone got any idea why that would happen? -
Django: how can I cache a template fragment conditionally?
I currently cache a page for unauthenticated users like this: {% with cache_timeout=request.user.is_authenticated|yesno:"0,600" %} {% cache cache_timeout my_page_cache user.is_authenticated LANGUAGE_CODE obj.pk obj.updated %} <p>This content is cached if the user is not authenticated</p> {% endcache %} {% endwith %} This works great, but now I want to change the condition of the with block to request.user == obj.user. How can I rewrite that code? Thanks! -
Define renderer class dynamically in Django view function
How can I define the renderer class inside the Djanog old api_view function depending on some condition? To have something like this: @api_view(['GET']) def can_render_2_things(request): if some_comdition: renderer_classes = [PDFRenderer] else: renderer_classes = [JSONRenderer] -
How to properly manage django production and development files
How can I properly manage my development files and production files with source control like GitHub (private repo). I am new to Django and while publishing my code to production there are many settings which needs to be changed in order to use it in production but the same setting won't work on my development server. I am stuck here Please guide me how manage. I want my files to be source control like any time I can make my development environment on another pc and anytime I can make my production server on any server. how to manage secret keys, passwords on source control (like GitHub private repo) Also please specify how should an Ideal file structure look like -
Able to save data without filling inlines even when required fields are there in django admin
I have 3 models Course, Course Details and Course Deadlines models.py class Course(models.Model): name=models.CharField(max_length=100) info= models.TextField() class CourseDetails(models.Model): course=models.ForeignKey(Course, on_delete= models.DO_NOTHING) info= models.TextField() class CourseDeadlines(models.Model): course=models.ForeignKey(Course, on_delete= models.DO_NOTHING) date= models.DateTimeField() admin.py class CourseDetailsInline(admin.StackedInline): model=CourseDetails extra=0 max_num=1 can_delete= False class CourseDeadlinesInline(admin.StackedInline): model=CourseDeadlines extra=0 max_num=1 can_delete= False class CoursesAdmin(admin.ModelAdmin): inlines=[CourseDetailsInline,CourseDeadlinesInline] admin.site.register(Course,CoursesAdmin) I am able to save the course without having to fill the inline fields even though they are required fields. -
Django with IIS server restart unexpectedly
I currently developing a Django Project which use IIS as web server. When I make some of the ajax request, the server will restart by itself with unknown reason. I have made some log and pretty sure the restart occurs just before Django run the corresponding function in views.py, but I don't know if the restart occurs before or after the server receive request. Does anyone have some idea on this issue? -
How to use namespace in django
I looked at the official Django documentation(https://docs.djangoproject.com/en/3.2/topics/http/urls/#reversing-namespaced-urls) and the error code and wrote the following. How can I write namespaces to work? views.py: from django.urls import path, include app_name = 'home' urlpatterns = [ path('math/', include('math_note.urls', namespace='math-note')) ] templates: <a href="{% url 'home:math-note' %}">math note</a> Error when running runserver: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Question: How can I use the namespace function? -
Save xlsx file in Desktop using Django
I want to save a excel file in Desktop from my apps, the file path is depends on the user that she/he want to download the file.Give me some idea, Thank You. FileNotFoundError at /Registration/Registration/Report [Errno 2] No such file or directory: '/Users/{username}/Desktop/Registration_Report.xlsx' I got the error above if I call the current username login: import os def registration_report(request): username = os.getlogin() ***excel codes here*** wb.save("/Users/{username}/Desktop/Registration_Report.xlsx") ## path to save the xlsx file ## If I put the exact path to desktop working good and I access the downloaded excel file, This is working but what I want is, the path is depend on the user machine where the file to save. def registration_report(request): ***excel codes here*** wb.save("/Users/myusername/Desktop/Registration_Report.xlsx") ***myusername is the exact machine login username that I use*** -
Is there a way to categorize skills for users to choose their skills in a form
Currently, I am working on a project where I need to get the user's skills through a form. I am facing a problem in categorizing the skills. Sample for categorization So please help me to categorize it in the same way the above picture has. The following code is coded by me using Django, models.py, forms.py -
How to get Total price from two different Size
I have 3 models : class Stock(models.Model): amount_size_1 = models.PositiveIntegerField(default=0) amount_size_2 = models.PositiveIntegerField(default=0) product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="product", related_name="pro") price_size_1 = models.FloatField(default=0,null=True) price_size_2 = models.FloatField(default=0,null=True) class OrderItem(models.Model): product = models.ForeignKey(Stock, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = jmodels.jDateField(auto_now=True) date_ordered = jmodels.jDateField(null=True) quantity = models.IntegerField(default=0, verbose_name='quantity') size = models.IntegerField(default=0, verbose_name='size') class Order(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem, related_name='item') date_ordered = jmodels.jDateField(auto_now=True,null=True) created_on_time = models.TimeField(auto_now_add=True,null=True) def get_cart_total(self): return sum([item.quantity*item.product.price_size_1 for item in self.items.all()]) My problem is that in def get_cart_total how filter for each item by their size I have 3 size (1,2,3), size 1 and 3 price is price_size_1 and size 2 is price_size_2 How can I solve this problem? or make if in Bracket? (in class OrderItem.size only get 3 numbers 1,2or3) -
How to solve Exception Value: 'list' object has no attribute 'lower' in django
This the Traceback: Environment: Request Method: GET Request URL: ipaddressHere/admin/ Django Version: 3.2.4 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authentication.apps.AuthenticationConfig', 'rest_framework', 'rest_framework.authtoken'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\utils\deprecation.py", line 116, in __call__ response = self.process_request(request) File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\middleware\common.py", line 48, in process_request host = request.get_host() File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\http\request.py", line 141, in get_host if domain and validate_host(domain, allowed_hosts): File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\http\request.py", line 691, in validate_host return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts) File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\http\request.py", line 691, in <genexpr> return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts) File "C:\Users\siddh\.virtualenvs\backend-8q1GYrV6\lib\site-packages\django\utils\http.py", line 292, in is_same_domain pattern = pattern.lower() Exception Type: AttributeError at /admin/ Exception Value: 'list' object has no attribute 'lower' I dont face this error when I comment ALLOWED_HOSTS so I feel it has to do something with it. Everything was working fine before I did not change anything. This is how my allowed host looks like ALLOWED_HOSTS = [ '127.0.0.1', and other ip adresses in same format ], -
Django linux server image storing
I am developing an application with an image gallery using Django. By the way, shop products also have photos. At the moment, website is been deployed on the linux server. Here is the question: should i upload images to the linux server using ImageField or it is better practise to use separate cloud storage? -
How to Select Multiple Item from a foreign key field in Django
I have a form where I want to display multiple select foreign key field. I want some thing like that here's my Model class jira_Story(models.Model): Jira_ID = models.CharField(max_length=100, blank=True) Jira_Story = models.CharField(max_length=500) Short_Description = models.CharField(max_length=500) Story_Points = models.CharField(max_length=30) Sprint = models.CharField(max_length=200) DX4C_Object = models.CharField(max_length=500) Sandbox = models.ForeignKey(environments, on_delete=models.CASCADE, limit_choices_to={'Mainline': None},blank=True, null=True) Developer_Assigned = models.ForeignKey(developer, on_delete=models.CASCADE,blank=True, null=True) I want Developer_assigned field as like that pic. I want to select multiple developer at time. can someone help me with the solution? -
How to create fake dates for objects with fields `DateTimeField(auto_now=True)`?
why I can't change date_created field value? I created this model class Value(SafeDeleteModel): name = models.CharField(max_length=50, blank=True) date_created = models.DateTimeField(auto_now=True, blank=True, null=True) class Meta: get_latest_by = 'date_created' Then for testing purposes, I need to create fake dates, maybe I need to try the mock method or something but I don't know how to do that. However, here when I try to change the date_created and print it back I find out it is not changed # test.py for i in range(1,4): val = Value.objects.create(column=cal3, field_value=str(is_odd(i))) setattr(val,'date_created', '2021-06-17 06:56:57.966476+00:00') val.save() print(val.date_created) I tried val.date_created = '2021-06-17 06:56:57.966476+00:00' instead of setattr using mock mehtod but I don't know how to emplment it properly -
django update profile image only if user has uploaded it
When the user does not upload an image and saves the form I get the following error. Internal Server Error: /user/profile/update Traceback (most recent call last): File "\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) KeyError: 'img' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "\auth\users\views.py", line 63, in profile_update image = Image.open(request.FILES['img'].file) File "\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'img' [16/Jun/2021 09:39:40] "POST /user/profile/update HTTP/1.1" 500 89309 I want to check the image is null then form does not need to do anything with the image, if the image is uplaoded then do some logic with it - upload it to an external api. def profile_update(request): user = request.user print(user.user_face_img_md5) if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) if form.is_valid(): username = form.cleaned_data.get('username') obj = form.save(commit=False) if request.FILES['img']: image = Image.open(request.FILES['img'].file) if image: print("Updating image..") #deleteImage(obj.user_face_img_md5) #image_md5 = uploadImage(image) else: print("No image uploaded") print(image) obj.user_face_img_md5 = image_md5 obj.save() messages.success( request, f'Account has been updated!') return redirect('profile') return render(request, 'users/profile_update.html', {'form': … -
How do I set a unique constraint for a transformed data in Django?
I have a model with fields name (string) and created_at (datetime) and I want a row with its name to be unique only within the hour it was created. That's how I tried: class Person(models.Model): created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=250) class Meta: unique_together = ('name', 'created_at__hour') I get the error: (models.E012) 'unique_together' refers to the nonexistent field 'created_at__hour'. What is the correct way to reach what I need? As the database I have PostgreSQL v12. -
How do I disallow a button from submitting my form in Django?
I have two buttons in my django site's form, the first one is supposed to only call a javscript function and the second one is supposed to submit the form. <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.title|as_crispy_field }} <br/> {{ form.body|as_crispy_field }} <button class="btn mt-3" onclick="insertText('HELLO')">Insert Text</button> <br/> <button class="btn btn-success mt-3" >Submit!</button> </form> My 'views.py' file contains following code for this page: class Posts(View): def get(self, request, *args, **kwargs): form = PostForm() posts = Post.objects.all().order_by('-publish_date') context = { 'form': form, 'posts': posts } return render(request, 'posts/view_posts.html', context) def post(self, request, *args, **kwargs): form = PostForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.publisher = request.user new_post.save() form = PostForm() return redirect('view-posts') My problem is the 1st button that is supposed to be only calling a javascript function is also making a POST request and submitting the form. Any solution to this problem? -
run cronjob 1 hour after the last run finished
I have a django cron and run it with linux crontab every hour. But I want to change the crontab to run the django cron 1 hour after the last execute finished. How can I do that? It is the crontab: */1 * * * * /usr/bin/python3.8 /django/vira/manage.py runcrons And this is django-cron: from django_cron import CronJobBase, Schedule from . import runner # create a class extending CronJobBase class PushCronJob(CronJobBase): RUN_EVERY_MINS = 10 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = "vira_app.runner" def do(self): runner.run_spider() -
How to get all Image using Multiple Image in Django UpdateView
When I try to update or edit my post my multiple image can't get all save images. But when I save the image without Uploading their all disappear This is my views.py UpdateView class UpdatePostView(LoginRequiredMixin,UserPassesTestMixin, UpdateView): model = Post form_class = PostForm template_name = "dash/blog/post/edit-post.html" def form_valid(self, form): form.instance.author = self.request.user post = self.get_object() # Clear existing images/This is working for post_image in Image.objects.filter(post=post): post_image.delete() images = self.request.FILES.getlist('image') print(images) for i in images: Image.objects.create(post=post, image=i) form.save() return super().form_valid(form) This is the models.py class Post(models.Model): title = models.CharField(max_length=255) content = RichTextField(blank=True,null=True) featured_image = models.ImageField(upload_to="blog_picture", default='blog_picture/post.jpg',null=True, blank=True) tag = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey( Category, on_delete=models.CASCADE,related_name='categories') date_created = models.DateTimeField(auto_now_add=True) date_published = models.DateField(blank=True,null=True,verbose_name="Date Published (yyyy-mm-dd)") previous_post = models.ForeignKey('self',related_name='previous',on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey('self',related_name='next',on_delete=models.SET_NULL, blank=True, null=True) @property def all_categories(self): categories = [] current_category = self.category while current_category is not None: categories.append(current_category) current_category = current_category.parent return categories def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('dashboard:post' ) class Image(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.FileField(upload_to="blog_picture", default='blog_picture/post.jpg',null=True, blank=True) def __str__(self): return self.post.title This is my forms.py where I put image as a multiple image in my class PostForm(forms.ModelForm): image = forms.FileField(required=False, widget=forms.FileInput(attrs={ "class":"form-control", "multiple":True })) class … -
Django If an action is added to the form, the form is not submitted
I have a form in my Django project. I want to when user fills the form and click the send button form will be posted and redirect a URL. I am using action in form for that but when I do this the form is not submitted but it opens the link, and when I delete action, the form is being submitted. I do not know why it is not working? approval_page.html <form method="POST" enctype="multipart/form-data" class="lead_form" id="lead_form" action="{% url 'approvals:approve_pending' pk=approval.pk%}" > <!-- Very Important csrf Token --> {% csrf_token %} {{ form_approval.media }} {{ form_approval|crispy }} <input type="hidden" name="rank_name" value="{{ waiting.rank.rank_name }}" /> <input type="submit" class="btn btn-success btn-xs" value="Approve" > <a href="{% url 'approvals:decline_pending' pk=approval.pk%}"> <button class="btn btn-danger btn-xs" id="approve-btn">Decline</button> </a> </form> views.py def approval_page(request, id): ... form_approval = LeadApprovalForm(request.POST) if request.method == 'POST': if form_approval.is_valid(): print(request.POST.get('approver_name', None)) lead_approval = form_approval.save() lead_approval.user = request.user lead_approval.approval_id = approval lead_approval.rank = request.POST.get('rank_name', None) lead_approval.save() else: form_approval = LeadApprovalForm() context = { ... 'form_approval ': form_approval , ... } return render(request, 'approval_page.html', context) def approve_pending(request, pk): pending_approval = ApprovalProcess.objects.get(pk=pk) customer = pending_approval.doc_id.owner pdf = pending_approval.doc_id priority_number = 0 ... approval_step.delta_time = abs((approval_step.finish_time - approval_step.start_time).days) approval_step.save() ... return redirect('ocr_approve', pending_approval.doc_id.id) urls.py url(r'^ocrs/(?P<id>\d+)/analysis/approve$', views.approval_page, … -
Naming of paths in Django for referencing in html templates
I am a complete newbie at Django. I've looked around for projects on the internet with the hopes of trying to incorporate other django apps into those projects. Right now, what I am trying to do is to add a forum functionality into that particular project by installing Django-Machina. With the installation already done right, I am having trouble putting its URL into the base.html Since Machina is a downloaded app using pip, it doesn't appear in the project as an app but instead in the virtual environment that I am using. In urls.py of the feed app, urlpatterns=[ . . . path('forum/', include(machina_urls, namespace='forum')), . . . ] In base.html of feed/templates/feed/base.html <a class="nav-item nav-link" href="{% url 'feed:forum' %}">Forum</a> As of now I am having an error saying that I am specifying a namespace in include() without providing an app_name is not supported, and I fully understand the error. So how do I go about naming that particular path such that I am able to reference it in base.html ? Thank you very much in advance and please let me know if you need any additional information. I will try my best to provide them. -
docker-compse build -> many "PermissionError: [Errno 13] Permission denied" error's
newbie question, so i hope you bear with me! I am trying to run an instance of a docker container (django project) on my synology nas DS220+. After: docker-compose build I get this error: traceback (most recent call last): File "urllib3/connectionpool.py", line 677, in urlopen File "urllib3/connectionpool.py", line 392, in _make_request File "http/client.py", line 1277, in request File "http/client.py", line 1323, in _send_request File "http/client.py", line 1272, in endheaders File "http/client.py", line 1032, in _send_output File "http/client.py", line 972, in send File "docker/transport/unixconn.py", line 43, in connect PermissionError: [Errno 13] Permission denied During handling of the above exception, another exception occurred: ... [6138] Failed to execute script docker-compose My directory structure is: nas |-docker | |-configurator | | |-accounts | | |-config | | |-pages | | |-static | | |-staticfiles | | |-templates | | |-docker-compose.yml | | |-Dockerfile | | |-manage.py | | |-Pipfile | | |-Pipfile.lock | | |-requirements.txt | |-some_other_project My Dockerfile: FROM python:3.9 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /configurator/ COPY Pipfile Pipfile.lock /configurator/ COPY ./requirements.txt /requirements.txt RUN pip install -r requirements.txt COPY . /configurator/ My docker-compose.yml: version: '3.8' services: web: build: . command: python manage.py runserver 0.0.0.0:8080 volumes: - .:/configurator/ ports: - 8080:8080 … -
How to get token in URL endpoint of Django rest framework token authentication of authenticated user
I want to get token of authenticated user in Django rest framework but unable to add for calling it to React -
How to fill html "option" tag with data from database in Django?
I don't understand why information from database isn't showing in html dropdown list. I have watched many videos and tutorials, but something going wrong. Help me please to figure out what I do wrong. I'm using SQLite. Here is my html template — click And also: models.py from django.db import models class Department(models.Model): class Meta: verbose_name_plural = 'Отделы' department_name = models.CharField(verbose_name='Отдел', max_length=40, editable=True, unique=True) def str(self) -> str: return self.department_name class User(models.Model): class Meta: verbose_name_plural = 'Участники' first_name = models.CharField(verbose_name='Имя', max_length=40) last_name = models.CharField(verbose_name='Фамилия', max_length=40) rfid_mark = models.CharField(verbose_name='RFID', max_length=8, editable=True, unique=True) department = models.ForeignKey(Department, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now=True, editable=False) def str(self) -> str: return self.first_name + ' ' + self.last_name views.py from django.shortcuts import render from .forms import UserForm from .models import Department def create(request): form = UserForm() if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'passage/registration.html', context) def index(request): query_results = Department.objects.all() context = {'query': query_results} return render(request,'passage/registration.html', context)