Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirection after submit not working after adding extra code on top. Probably a priority problem
I have a script that redirects the user to the previous page_id after submit: a user would connect to page page_A Would click on product_1, Be redirected to product_1 page, Leave a review and upon clicking submit be redirected to page_id This has been working fine for a while. I decided to implement djang-hitcount in a function base view (used the code here how to use Django Hitcount in a function based view rather than a class?), as I wanted to see how many unique IP addressed where connecting. Since then the comment submission code is not working anymore. As an example: If User land on Page_A the URL would show this: http://localhost:8000/Page/A When clickin on product_1, the url would then display the following:http://localhost:8000/product/1?next=/Page/A When submitting a review the user would be redirected to : http://localhost:8000/Page/1 However now, the user is redirected to http://localhost:8000/Page/1 which obvioulsy does not exist - it should be Page A, but instead attributes the product_id to the page_id. I suspect it's because the new django-hitcount code has taken over some of the initial logic. Maybe some indention problem? Here it goes: Views.py def show_event(request, event_id): submitted = False form = 'ReviewForm' formonpage = 'ReviewForm' ###<-- … -
Django and Flutter configuration
How do i configure Django and Flutter for local development and how do i configure them for the deployment in a server? (Flutter as a frontend web project). I have tried to add static files directories in settings file. But I'm not sure what value do i give to this variable. Do i assign os.path.join(BASE_DIR, 'flutter_project/build/web/assets') to static files directories or do i have to assign something else? Now that you’re ready to post your question, read through it from start to finish. Does it make sense? -
AttributeError: module 'signal' has no attribute 'SIGHUP'
I am trying to integrate mod_wsgi into my django project on Windows 10. While I was able to install mod_wsgi into my virtual environment, I am running into errors while trying the command python manage.py runmodwsgi. (venv) PS D:\Tutorials\Python\Projects\ADSS> python manage.py runmodwsgi Successfully ran command. Server URL : http://localhost:8000/ Server Root : C:/Users/admin/AppData/Local/Temp/mod_wsgi-localhost-8000-admin Server Conf : C:/Users/admin/AppData/Local/Temp/mod_wsgi-localhost-8000-admin/httpd.conf Error Log File : C:/Users/admin/AppData/Local/Temp/mod_wsgi-localhost-8000-admin/error_log (warn) Operating Mode : daemon Request Capacity : 5 (1 process * 5 threads) Request Timeout : 60 (seconds) Startup Timeout : 15 (seconds) Queue Backlog : 100 (connections) Queue Timeout : 45 (seconds) Server Capacity : 20 (event/worker), 20 (prefork) Server Backlog : 500 (connections) Locale Setting : en_US.cp1252 Traceback (most recent call last): File "D:\Tutorials\Python\Projects\ADSS\manage.py", line 25, in <module> execute_from_command_line(sys.argv) File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "D:\Tutorials\Python\Projects\ADSS\venv\lib\site-packages\mod_wsgi\server\management\commands\runmodwsgi.py", line 162, in handle signal.signal(signal.SIGHUP, handler) AttributeError: module 'signal' has no attribute 'SIGHUP' Google seems to suggest that signal.SIGHUP, signal.SIGUSR1 and signal.SIGWINCH as being used by my mod_wsgi installation aren't supported on Windows. So I tried the following two methods in .\venv\Lib\site-packages\mod_wsgi\server\management\commands\runmodwsgi.py: … -
Request Pending After A DELETE request
I am working with Reactjs and I am having and issue while sending request, Last week everthing was working perfectly and then I started to face that request issue. When I send GET, PUT, POST request everything works fine with no problems, when I send a DELETE request it gets sent and I recieve a response with status 204, but any type of request I send after it, it stucks in a pending state forever. I tired different Projets same issue, different PC same issue. When I access my dev server from another PC everythings works perfectly no problems, seem like the problem happens only when I send request from the same machine where the dev server is strated. I pulled an old version of the code where I was sure everything were fine and I got same issue, I tried to empty cache, different browsers, I event emptied my whole disk and installed windows again. I tried the DELETE request with Postman and it stucked in pending state. I tried different backends same problem. The Back-end is with Django, I Don't have access the back-end code but I tried same proccess with Postman and there was no issue. api … -
Fetching users data based on username input in urls
I am little bit new to django and was working on my first instagram clone project all by myself. I got confused in a place where I needed to fetch user data based on 127.0.0.1:8000/username and I found a useful but useless answer(for me) from medium(.com) .The author was using class based view. In class based view, I didnot get any documentation to use multiple models as much as I searched so i had to do it with function based view as I have not learned class based view yet.I had to use post model, profile model and User model to get data for profile page. This is the code that somehow worked but should I use this view? from django.contrib.auth.models import User from .models import Profile #profile view def profile_data(request, username): mydata = User.objects.get(username=username) myprofile = Profile.objects.filter(user=mydata) mycontext ={'profile': myprofile} return render(request,'firstapp/profile.html', context=mycontext) #in urls.py, from firstapp import views path('<str:username>/', views.profile_data , name='profile'), #in models.py, from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,unique=True) fullname = models.CharField(max_length=100) def __str__(self): return self.fullname In firstapp/profile.html, <a href="#" class="text-3xl mt-5 text-center">{{user.profile.fullname}} But I got confused on how to attatch my Profile model in it. So I created this, my own function-based … -
How do I import multiple views for urls.py?
I need to import views from horoscopes and dates. but when importing them into urls.py there is a conflict because of which only one views is perceived. so that's the question, how do I import multiple views? ` from django.contrib import admin from django.urls import path import horoscopes import dates urlpatterns = [ path('admin/', admin.site.urls), path('horoscopes/leon', horoscopes.views.monday), path('dates/monday', dates.views.monday), ] ` I've tried both and: ` import horoscopes import dates urlpatterns = [ path('admin/', admin.site.urls), path('horoscopes/leon', horoscopes.views.monday), path('dates/monday', dates.views.monday), ` as well as: ` from django.contrib import admin from django.urls import path from horoscopes import views as horoscopes_views from dates import views as dates_views urlpatterns = [ path('admin/', admin.site.urls), path('horoscopes/leon', views.leon), path('dates/monday', views.monday), ] ` both options ignore one of the views -
Get data from django user model
This is my model: from django.contrib.auth.models import User class User_Model(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) nickname = models.CharField(User.username, max_length=2000, null=True) def __str__(self): return f"{self.user}" I would like to save into nickname in this model value of "username" from User model. I want to use it later in vievs.py to send them as context class Users(ListView): model = User_Model context_object_name = "users" paginate_by = 10 template_name = "Messenger/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs_json"] = json.dumps(list(User_Model.objects.values('nickname'))) return context Generally i try to do stuff like here but i want to list nicknames: https://www.youtube.com/watch?v=jqSl36xR9Ys I tried to get those from one to one field but i think i done this wrong way -
Page not found 404 django
Can anyone help me with this please? When I try to access i get the following error: Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in backend.urls, Django tried these URL patterns, in this order: admin/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. urls.py from django.contrib import admin from django.urls import path, include from Notes.views import NotesViewset from rest_framework.routers import DefaultRouter router=DefaultRouter() router.register('/posts',NotesViewset) urlpatterns = [ path('admin/', admin.site.urls), path(' ', include(router.urls)) ] views.py from django.shortcuts import render from .models import Note from rest_framework import viewsets from .serializers import NoteSerializer class NotesViewset(viewsets.ModelViewSet): serializer=NoteSerializer queryset=Note.objects.all() admin.py from django.contrib import admin I'm new to programming and I hope someone can help me. Thanks -
How to resolve a 502 Bad Gateway when deploying Django App on Azure with Gunicorn and Nginx
I've been trying to deploy a Django app on Azure for about a week. My instructor followed the exact same setup I used and he was able deploy the same app to Azure. I've followed several tutorials, this one from Digital Ocean in particular, and I always get the same result. When I go the the IP address I get a 502 Bad Gateway. The only change I make from the tutorial is opening up ports 8000 and 80. I do that through Azure's Networking settings. I've tried all of the troubleshooting recommendations at the end of that tutorial. I've restarted Gunicorn, Nginx, and even the VM. On Azure I have a Standard B1s VM running Ubuntu 22.04. I do not have a custom domain, just the static IP assigned by Azure. I can deploy the app on the development server just fine. If I bind 0.0.0.0:8000 to gunicorn that also will display the site (minus styling). Gunicorn starts and runs. When I check the status after starting the service it shows the active green dot. Immediately after trying to access the site via the IP address, if I check Gunicorn status again it reads: gunicorn.socket: Failed with result 'service-start-limit-hit' … -
How to format template with django?
I have a django application. And I try to format some data. So I have this method: def show_extracted_data_from_file(self, file_content): self.extractingText.extract_text_from_image(file_content) regexes = [ self.verdi_total_number_fruit_regex(), self.verdi_fruit_name_regex(), self.verdi_total_fruit_cost_regex(), ] matches = [self.findallfruit(regex) for regex in regexes] return tabulate( zip_longest(*matches), # type: ignore headers=[ "aantal fruit", "naam fruit", "kosten fruit", ], ) that produces this result: 6 W a t e r m e l o e n e n 4 6 , 2 0 7 5 W a t e r m e l o e n e n 5 7 7 , 5 0 9 W a t e r m e l o e n e n 6 9 , 3 0 but as you can see it is one horizontal output. But I want every item under each other. that it will looks like: 6 Watermeloenen 577,50 75 Watermeloenen 69,30 9 watermeloenen 46,20 and the template: <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ pdf_form.as_p }} </div> <div class="form-outline"> <div class="form-group"> <div class="wishlist"> <table> <tr> {% for cell in content %} <td>{{ cell }}</td> {% endfor %} </tr> </table> </div> </div> </div> </div> … -
Django ModelForms using get_or_create
I am using ModelForms to create and render my form, and it is working fine. I however want to use get_or_create method instead of using if form.is_valid(): method but i do not know ho to how to use it with ModelForms. views.py def books(request): genres_names = Genre.objects.all() if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") genres_name = request.POST.get("genres") genres, created = Genre.objects.get_or_create(name=genres_name) try: if form.is_valid(): genre = form.save(commit=False) genre.save() if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create(genre=genre, book_title=name, book=f) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form":form, "genres_names":genres_names}) models.py class Genre(models.Model): genres = models.CharField(max_length=255, default="") class Meta: verbose_name_plural = "Genre" def __str__(self): return self.genres class Books(models.Model): """ This is for models.py """ book_title = models.CharField(max_length=255, default="", primary_key=True) book = models.FileField(default="", upload_to="books", validators=[validate_book_extension], verbose_name="books") genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="") class Meta: verbose_name_plural = "Books" def __str__(self): return self.book_title forms.py class BookInfo(forms.ModelForm): class Meta: model = Genre fields = ["genres",] widgets = { "genres":forms.TextInput(attrs={"list":"genres"}) } class BookFile(BookInfo): book = forms.FileField(widget = forms.ClearableFileInput(attrs={"multiple":True})) class Meta(BookInfo.Meta): fields = BookInfo.Meta.fields + ["book",] my template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" … -
ModuleNotFoundError: No module named 'sandbox': Docker Build failed with error code [1]
I'm building a django oscar commerce v 3.2 project(https://github.com/django-oscar/django-oscar) on ubuntu 20.04 on GCP with a virtual environment using python 3.8.14 and getting the following error when i run the docker build command using docker-compose -f docker-compose-full.yml up ModuleNotFoundError: No module named 'sandbox' The trace is with regards to the following line in my settings.py: from sandbox.environment import EnvironmentChecker My project folder structure is as follows : django-commerce |- src |- sandbox | |- __init__.py | |- environment.py | |- settings.py | |- manage.py | |- urls.py | |- wsgi.py | |- uwsgi.ini |- DockerFile |- MakeFile |- Manifest.in |- setup.py |- setup.cfg The top lines in my Settings.py import os import sys import logging.config from django.utils.translation import gettext_lazy as _ from sandbox.environment import EnvironmentChecker Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Path helper location = lambda x: os.path.join( os.path.dirname(os.path.realpath(__file__)), x) My wsgi.py # isort:skip import os import sys root_path = os.path.abspath(os.path.split(__file__)[0]) sys.path.insert(0, os.path.join(root_path, 'django-commerce')) sys.path.insert(0, root_path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.wsgi import get_wsgi_application # isort:skip application = get_wsgi_application() I've also tried adding django-commerce.sandbox to my INSTALLED_APPS in settings.py as a last try but its not working. I've spent hours trying this to work. Help appreciated. … -
Django DEBUG False not working in the Production Environment
I am new to Django and Python world, I am currently working on an Dajngo site, which is hosted on a Ubuntu20.04 VM. Upon hosting the site to the production, I noticed that, although the DEBUG is set to False in the prodiuction settings. I still see the Django DEBUG erros as if the DEBUG is set to True . When I run python manage.py runserver command on the VM I get the below error. CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. Folder structure . ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-310.pyc │ ├── urls.cpython-310.pyc │ ├── views.cpython-310.pyc │ └── wsgi.cpython-310.pyc ├── settings │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-310.pyc │ │ ├── base.cpython-310.pyc │ │ ├── local.cpython-310.pyc │ │ └── production.cpython-310.pyc │ ├── base.py │ ├── local.py │ └── production.py base.py (Common settings) import os from os.path import dirname, join import posixpath from posixpath import join from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '393266f4-9cc7-4cfe-96a8-2f2809e53e32' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #ALLOWED_HOSTS = [] # Application references INSTALLED_APPS = [ # … -
OperationalError at /admin/card/group/ no such table: card_group
i created a table named group and also run makemigrations and migrate and also registered it in admin.py but it is showing error when i opening it in admin panel. this is my models.py class group(models.Model): dish_category = models.CharField(max_length=255) def __str__(self): return self.dish_category this is my admin.py from .models import group admin.site.register(group) i also reset db and run migration again but it not works the groups table is showing in db but when i click it it shows error that OperationalError at /admin/card/group/ no such table: card_group -
How to create dynamically jstree in django
how to create dynamic jstree in django website Actually, I don't know what type of json data send in ajax request for creating jstree. -
Django Rest Framework very slow on Azure
I had migrated from Heroku to Microsft Azure, and the speed is really very slow, my App service is having the following specs : P1V2 210 total ACU 3.5 GB memory Dv2-Series compute equivalent then when it comes to my Azure Database for PostgreSQL flexible server, the following are the specs : General Purpose (2-64 vCores) - Balanced configuration for most common workloads Am sure all these Specs are higher than the default Heroku specs it used to give, but why is my Django project very slow when it comes to response time of the API requests ? -
Loading category tags with load more button
i am new to jquery , i have implemented a load more button on my blog app using jquery however the categories tags doesnt get displayed on the html when i click on the load more button Every thing works fine so far, i can't just display the tags on the post card, it keeps returning undefined note: 'i am getting my categories with a many to many field relationship' enter image description here Here is my views : ` def home(request): post = BlogPost.objects.all()[0:5] total_post = BlogPost.objects.count() context = {'post': post, 'total_post':total_post} return render(request,'blog/home.html', context) def load_more(request): # get total items currently being displayed total_item = int(request.GET.get('total_item')) # amount of additional posts to be displayed when i click on load more limit = 3 posts = list(BlogPost.objects.values()[total_item:total_item+limit]) print(BlogPost.objects.all()) data = { 'posts':posts, } return JsonResponse(data=data) here is my template: <div class="blogpost-container"> <div class="blogposts" id="blog-content"> {% for post in post %} <div class="post"> <img id="img-src" src="{{post.image.url}} " image-url="{{post.image.url}}" alt=""> <p><strong>{{post.title}}</strong></p> {% for category in post.category.all%} <h3>{{category}}</h3> {%endfor%} <a id="post-detail-link" href="{% url 'detail' post.id %}" detail-url="{% url 'detail' post.id %}"><h2>{{post.summary}}</h2></a> </div> {%endfor%} </div> </div> <div class="add-more" data-url='{% url "load_more" %}'id="add-btn"> <button type="button" class="more-content">load more</button> </div> <div class="alert no-more-data" role="alert" id="alert"> No … -
How to make a '\n' or '<br/>' work rather than display it using django and html template?
I'm facing a serious problem with html and django. What I want to do: Create a table Fill the table with python string The most important one that I want to make line break for the string What I've tried: Use '\n' in the string Use '' in the String But they don't work, they are both displayed on the browser, I don't how to fix it. Can anyone help, Thanks a lot. ` <table border='1'> {% for x in datas %} <tr> <td>{{ x.0 }}</td> <td>{{ x.1 }}</td> <td>{{ x.3 }}</td> </tr> {% endfor %} </table> x.3 is a string and I tried both '\n' and <br/> in it ` -
Django: Use the different field for password in the Custom User Model
When you use the Custom User Model, you can change the "username" field using the USERNAME_FIELD = 'identifier' Is there a way to do similar thing for the "password" field? Something like PASSWORD_FIELD = 'my_password_field' If not, is there any was to store the password not in the default "password" field of the user model? No code tried because I don't know what to write in this case. Django docs contains the instruction about changing the changing the used identifier, but nothing about password. -
Wrong environment in Django
I'm a beginner at Django Web Framework.At the beginning when I start Django project I didnt see venv folder like on the picture on the left.I didnt have bin ,lab , gitignore and pyvenv.cfg files on the right picture.When I made new env I see venv folder but also there are duplicate bin and lib folders.All I want for now is when I start new Django project is to have one VENV folder and that it's gonna be my only enviornment and also bin and lab folders be in venv folder. What I try is this: That was the commands I enter on my MAC. pip install virtualenv virtualenv venv source venv/bin/activate That made a new env and folder venv.But I dont want to have another basic enviornemnt with name of the project like on the picture on the right.I dont want to have in project folder bin and lib folder also. Sorry for my english... -
I need help properly implementing a booking scheduler and availability in Django
This question has been asked many times before on StackOverflow and in the Django forums, but none of the answers I've found are appropriate or complete enough for my situation. First, the brief: I'm creating a web application for a car rental business. In addition to helping them organize and centralize their fleet, it will also help them collect orders directly from customers. As with most rentals, the logistics of it all can be somewhat confusing. Someone may place an order for a car today (December 12th) but actually take the car over the Christmas to New Year's period. A renter may borrow a car for just two days, and then extend the booking at the last minute. When this happens (often very frequently), the business usually has to scramble to find another one for a different customer who was scheduled to get that car the next day. Adding to that, an individual car can only be rented to one client at a time, so it can't have multiple bookings for the same period. Most answers advocate for a simple approach that looks like this: models.py class Booking(models.Model): car = models.ForeignKey(Car, ...) start_date = models.dateField(...) end_date = models.dateField(...) is_available = … -
how to get value from promise and how to get promise resolved
this is my javascript code . I'am trying to get data from backened through axios. how can i get the value in subs variable ? var subs = axios.get("/getdata/", ).then( function(resp){ console.log("respons",resp.data.value); return resp.data.value; }) .catch( function(err){ console.log(err); }) console.log(subs) // console result on browser. How to fulfill this pending promise ? Promise {<pending>} [[Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: "false" views.py file code def data_to_api(request): if request.method == "GET": user_name = request.user.get_username() print(user_name) user_obj = All_users.objects.get(username=user_name) subs= str(user_obj.subs_detail).lower() print(subs) request.data = subs data = { "value":subs, } return JsonResponse(data) -
Error No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
i'm working on a django project to create football trainings. I'm testing the model and its saving. The problem appears when I try to save it, must be something about redirection, because in the database the training does get saved, but it doesn't redirect me anywhere and the error comes out. models.py from django.db import models from django.utils import timezone from users.models import User class Entrenamiento(models.Model): autor = models.ForeignKey(User, on_delete=models.CASCADE) idEntrenamiento = models.AutoField(primary_key=True) idEquipo = models.IntegerField() fecha = models.DateTimeField(default=timezone.now) idDireccionCampo = models.IntegerField() temporadas = [ ('2022/2023','2022/2023'), ('2023/2024','2023/2024'), ('2024/2025','2024/2025'), ('2025/2026','2025/2026') ] temporada = models.CharField(max_length=50, choices=temporadas, default='2022/2023') def __str__(self): return 'Entrenamiento {}'.format(self.idEntrenamiento) @property def entreno(self): return 'Entrenamiento {} de {} para {} con fecha del {}, será en el campo {}'.format(self.idEntrenamiento, self.temporada, self.idEquipo, self.fecha, self.idDireccionCampo) views.py from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.messages.views import SuccessMessageMixin from django.contrib.auth.models import User from django.contrib import messages from django.http import HttpRequest, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.views.generic import (CreateView, DeleteView, DetailView, ListView,UpdateView) from django import forms from django.urls import reverse_lazy from .models import Entrenamiento def home(request): context = { 'entrenamientos': Entrenamiento.objects.all() } return render(request, 'entrenamientos/entrenamientos.html', context) class PostListView(ListView): model = Entrenamiento template_name = 'entrenamientos/entrenamientos.html'#<app>/<model>_<viewtype>.html context_object_name = 'entrenamientos' ordering = ['-fecha'] … -
Celery not retrying when an exception is raised when testing in Django
I have a class based celery task, which I would like to test by raising an error and then confirming that retry has been called. During the test, I want to raise a ConnectionError when msg.send() is called and then confirm that it is being 'retried'. The task essentially constructs an email using django.core.mail.EmailMultiAlternatives (which inherits EmailMessage) and then attempts to send that email. The task works well in practice, with a retry being called if a connection does not exist, my only problem is how to test it. So far, I have managed to raise the ConnectionError by patching EmailMultiAlternatives, however, the test does not trigger a retry in the celery terminal. tasks.py (Simplified) class SendMail(Task): max_retries = 4 base = 'BaseTask' def run(self, **kwargs): msg = EmailMultiAlternatives(kwargs.get('some_value'), etc.) msg.attach_alternative(rendered_html) try: msg.send(fail_silently=False) except ConnectionError as exc: self.retry(countdown=backoff(self.request.retries), exc=exc) test_task.py (simplified) class SendMailTest(TestCase): def setUp(self): self.message = {some data} def test_error(self): with patch.object(EmailMultiAlternatives, 'send', return_value=None) as mock_method: mock_method.side_effect = Exception(ConnectionError) SendMail(kwargs=self.message) My question is, why, when the test script is run and an exception is clearly being raise, does Celery not attempt to retry? -
How take path in request.FILE['file'] to put it for download link
I create foo to upload files to Django models, its InMemoryUpload object. and how can I collect the full path to download link? my models.py class Document(models.Model): """Class for uplaoded files. colect file and description working with analog form """ id = models.AutoField(primary_key=True) file_path = models.TextField(max_length=255) hash_size = models.CharField(max_length=255) def __str__(self): return f"{self.id},{self.file_path},{self.hash_size}" def get_hash(file: object) -> str: md = hashlib.md5() # with open(file, "rb") as f: for chunk in iter(lambda: file.read(4096), b""): md.update(chunk) return md.hexdigest() my views.py def model_form_upload_1(request: HttpRequest) -> HttpResponse: ''' view handling this form will receive the file data in :attr:`request.FILES <django.http.HttpRequest.FILES>`''' if request.method == 'POST': upload = request.FILES['file'] path = upload.chunks() print(path) hash_tuple = () form = DocumentForm(request.POST, request.FILES) if form.is_valid(): print(upload.size) if get_file_size(upload): hash = Document.get_hash(upload) hash_list = [x for x in Document.objects.all().values_list('hash_size')] hash_tuple += (hash,) if hash_tuple not in hash_list: Document.objects.create( file_path=request.GET.get(upload), hash_size=hash) else: return HttpResponseBadRequest("file bigger tha 300mb") return redirect("view") else: return HttpResponseBadRequest("Form invalid") else: form = DocumentForm() return render( request=request, template_name='model_form_upload.html', context={'form': form}) return render(request, 'model_form_upload.html') return render(request, 'model_form_upload.html') my template.py <tr> <td>{{document.id}}</td> <td>{{document.file_path}}</td> <td><a href="{{ document.file_path }}">download</a></td> <td>{{document.hash_size}}</td> </tr> before I tried to take request.open(file) but it's actually not what I need.