Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i've got error while downloading video from pytube library
i've got error while downloading youtube video via pytube library pytube version is 12.0.0 RegexMatchError at /144p regex_search: could not find match for (?:v=|/)([0-9A-Za-z_-]{11}).* please help me to solve this error. -
Is it possible to use a related field as a choice field in Django?
In Django, if I have something like this: class Library(models.Model): name = models.CharField(...) address = models.CharField(...) book_of_the_week = ? class Book(models.Model): library = models.ForeignKey(Library, on_delete=models.CASCADE, related_name="books") name = models.CharField(...) This gives me the ability to create multiple libraries, each with a large number of books. For book_of_the_week, I want this to be a reference to a Book instance, so that in Django Admin, the field is represented as a dropdown that lets you select from the books in the current library, and in code, you can use .book_of_the_week to access a specific instance of Book. Is this possible? -
Set default url parameter or ignore the none input when nothing is specified - Django Project
I have a list of dictionaries: mylist= [{'Date': '10/2/2021', 'ID': 11773, 'Receiver': 'Mike'}, {'Date': '10/2/2021', 'ID': 15673, 'Receiver': 'Jane'}, {'Date': '10/3/2021', 'ID': 11773, 'Receiver': 'Mike'}, ... {'Date': '12/25/2021', 'ID': 34653, 'Receiver': 'Jack'}] I want to select the rows based on my input date range. I've successfully done this by appending the URL with ?start=val1&end=val2 and I was able to call the input date values from views.py to template.html : Appending the URL with ?start=val1&end=val2 based on my input dates in my HTML <div class="d-sm-flex align-items-center justify-content-between mb-4"> <form method="get" action="/chart/"> <div class="form-row"> <label for="start">Start Date:</label> <div class="col"> <input type="date" class="form-control" name="start" min="2020-01-03" required> </div> <label for="end">End Date:</label> <div class="col"> <input type="date" class="form-control" name="end" min="2020-01-03" required> </div> <button type="submit" class="btn btn-primary"> Generate Report</button> </div> </form> Define start and end in my views.py: start = request.GET.get('start', None) end = request.GET.get('end', None) Select the rows based on the input date range in my views.py: dfmylist = pd.DataFrame(mylist) dfmylist['Date'] = pd.to_datetime(dfmylist['Date']) # you missed this line dfmylistnew = (dfmylist['Date'] > start) & (dfmylist['Date'] <= end) new = dfmylist.loc[dfmylistnew] And I was able to recall the {{new}} in my HTML. The only thing is, when I open the default URL, it shows the error: `Invalid … -
ManyToManyField and ModelMultipleChoiceField not working
I am trying to create an event staff management tool in Django. One part of the data model is that a staff member (class Staff) is linked to a scheduled shift (ScheduledEventShift) via ManyToManyField through StaffShift. Every member of staff can see the shifts available for him / her and select them via ModelMultipleChoiceField. This works perfectly fine and the relation is correctly written to the StaffShift table depending on whether the shift is ticked or not. (sorry the tool is in German, but it should be clear from context what I mean) What I want to do now is "the opposite" of that, i.e. I as an admin want to look at a single shift, see which staff members have applied for that shift and untick those that are "too much" (i.e. 2 required, 3 applied). When using a ModelMultipleChoiceField in that direction, I am able to show all the relevant staff members as a QuerySet but the choices are always unticked and it has no effect whatsoever on the StaffShift table if I tick something. Here the relevant part of my code: models.py: class Staff(models.Model): <...> shifts = models.ManyToManyField(ScheduledEventShift, through='StaffShift', related_name='applied_staff') forms.py: class ScheduledEventShiftEditForm(forms.ModelForm): class Meta: model = … -
How to stop django from inserting column into MySQL if record already exists
Models.py: class signUpUser(models.Model): username = models.CharField(max_length = 100, unique = True) passwd = models.TextField() passwd2 = models.TextField() email = models.EmailField(unique = True) def save(self, *args, **kwargs): if not self.pk: self.passwd = make_password(self.passwd) self.passwd2 = make_password(self.passwd2) super(signUpUser, self).save(*args, **kwargs) class Meta: db_table = "users" views.py def signUp(request): if request.method == "POST": if request.POST.get('username') and request.POST.get('passwd') and request.POST.get('email'): post = signUpUser() post.username = request.POST.get('username') post.passwd = request.POST.get('passwd') post.passwd2 = request.POST.get('passwd2') post.email = request.POST.get('email') post.save() messages.success(request, "Success.") return render(request, "signup.html") signup.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@200&display=swap" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/css/styles.css' %}"> <body style="background-color: rgb(37, 37, 37);"> <script src="{% static 'js/index.js' %}"></script> <title>Document</title> <body class="bkg_signup"> <div id="particles-js"> <div class="top-nav"> <a href="{% url 'hpage' %}">HOME</a> <a href="{% url 'prodpage' %}">PRODUCTS</a> <a href="{% url 'cpage' %}">CONTACT</a> <a href="{% url 'apage' %}">ABOUT</a> <a style="float: right;" href="{% url 'lpage' %}">LOGIN</a> <a style="float: right;" href="{% url 'spage' %}">SIGN UP</a> </div> <div class="item-box2"> <div class="div-align2" style="font-size: 28px;"> <h1 style="margin-right: 40px; color: rgb(255, 255, 255);">Sign Up</h1> </div> <form class="fontmaker" method="post" action="{% url 'signup' %}"> {% csrf_token %} <input style="border-color: black;" class="input-corners" placeholder="Username" type="text" … -
python django smart-selects is not working properly
I have install django-smart-selects but when i add the url in the urls.py url(r'^chaining/', include('smart_selects.urls')), when i run my application after this i got this error from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' so here in django.utils.encoding I didn't find any import force_text so I change it to force_str. I am using django 4.0 -
Django EmailMessgae() Error: MIMEPart.__init__() takes from 1 to 2 positional arguments but 5 were given
This is my views file and this is the screenshot of the error email = EmailMessage( email_subject, message2, settings.EMAIL_HOST_USER, [myuser.email], ) email.fail_silently=True email.send_mail() -
Payment gateway Integration in django
I am implementing the payment integration in Django and creating api using Django rest framework. Want print response of the sandbox link with the parameter like fullname,email,phone which is coming from frontend. I am getting the data from front end but can't able to pass the parameter in the link. I am not getting that how to pass the parameter in the sandbox link. I replaced '{}' to '{{}}' but this also didn't work. @api_view(['POST']) def user_payment(request): headers = { 'Content-Type': 'application/json' } successUrl= 'https://****/thank.html?test=*' cancelUrl= 'https://*********' serializer = user_payment_detailSerializer(data=request.data) #print(request.data) print(serializer) data=request.data fullName=data['fullname'] email=data['email'] phone = data['phone_number'] sum = data['total_amount'] reques = requests.get(f"https://sandbox.abcd.co.il/server/createPaymentProcess/?pageCode={pageCode}&sum={sum}&successUrl={successUrl}&cancelUrl={cancelUrl}&pageField[fullName]={fullName}&pageField[phone]={phone}&pageField[email]={email}", headers=headers) response_body = reques.text print(response_body) if serializer.is_valid(): pass # serializer.save() return render(request,'home.html') -
How to pass a variable coming from HTML to another django view function
Intro: I've been looking for all stackoverflow questions but unfortunately after hours of research I cannot find a solution that suits my needs. I have a variable generated after the user submits a form. I get this variable using an Ajax call and then I pass it to a django view. file.html //if user clicked submit button, call ajax to pass variable to django view $('#submit').click(function() { var dato = 0; $.ajax({ url: '{% url 'todo:get_dato' %}', dataType: 'text', method: "POST", data: { csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), data: JSON.stringify(dato), }, success: function(data, status, xhr){ }, error: function(xhr, status, error){ } }) }) Problem: I can "receive" this variable into a django view function but I cannot pass ajax_date variable to another view function inside the same views.py file views.py 1st function where I get ajax variable coming from HTML @login_required @user_passes_test(staff_check) def get_dato(request): if request.method == 'POST' and 'data' in request.POST: ajax_response_dict = json.loads(request.POST['data']) ajax_date = ajax_response_dict.get('date_id') request.session['ajax_date'] = ajax_date 2nd function where I need to use ajax_date variable @login_required @user_passes_test(staff_check) def calendario(request): form = EventForm(request.POST) if form.is_valid(): form.save() #HERE I NEED TO USE VARIABLE ajax_date = request.session.get('ajax_date') Actual situation: If I print ajax_date from 2nd function I got: None <class 'NoneType'> while … -
Django - AttributeError 'str' object has no attribute 'court_number'
My edit view in my application won't update the court details whenever I want to edit it. I keep getting the error below. Adding, Viewing & Deleting functions are working okay. I cant find a solution on the other S/O answers. Some help on this would be appreciated. Thanks Exception Value: 'str' object has no attribute 'court_number' model.py # Create your models here. class Court(models.Model): court_number = models.CharField(max_length=255, verbose_name='Court Number.') accused_person = models.ForeignKey(AccusedPerson, on_delete=models.CASCADE, verbose_name='Accused Person') court = models.CharField(choices=COURTS, max_length=255, verbose_name='Court') court_verdict = models.CharField(choices=VERDICT, max_length=50, verbose_name='Court Status') scheduled_on = models.DateField(verbose_name='Scheduled On') created_by = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name='Police Officer') date_created = models.DateTimeField(auto_now_add=True, verbose_name='Date Created') date_updated = models.DateTimeField(auto_now=True, verbose_name='Date Updated') def __str__(self): return str(self.court_number) class Meta: verbose_name_plural = 'Court' forms.py class EditCourtInfoForm(forms.Form): court_number = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'id': 'court_number', 'class': 'form-control mb-4', 'name': 'court_number', 'placeholder': 'Court Number'})) accused_person = forms.ChoiceField(required=True, widget=forms.Select(attrs={'id': 'accused_person', 'class': 'form-control mb-4', 'name': 'accused_person', 'placeholder': 'Accused Person'})) court = forms.ChoiceField(choices=COURTS, required=True, widget=forms.Select(attrs={'id': 'court', 'class': 'form-control mb-4', 'name': 'court', 'placeholder': 'Court'})) court_verdict = forms.ChoiceField(choices=VERDICT, required=True, widget=forms.Select(attrs={'id': 'court_verdict', 'class': 'form-control mb-4', 'name': 'court_verdict', 'placeholder': 'Verdict'})) scheduled_on = forms.DateField(required=True, widget=forms.DateInput(attrs={'type': 'date', 'id': 'scheduled_on', 'class': 'form-control mb-4', 'name': 'scheduled_on', 'placeholder': 'Scheduled On'})) def __init__(self, *args, **kwargs): super(EditCourtInfoForm, self).__init__(*args, **kwargs) self.fields['accused_person'].choices = [(e.pk, f"{e.first_name}" + ' … -
How to compare dates in django
I am working on a task manager project, user can define the "ending date" of the task, I would like to change the front end code of a task that isn't completed before the "endind_date".I tried playing around in models.py but i get back this error: "can't compare datetime.datetime to datetime.date" models.py: class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(max_length=200, null=True, blank=True) complete = models.BooleanField(default=False) importance = models.ForeignKey(Importance, null=True, blank=False, on_delete=models.CASCADE) creation_date = models.DateField(default=timezone.now) ending_date = models.DateField(null=True, blank=False) # jd = models.DateField(null=True, blank=True) def __str__(self): return self.title def is_end_date(self): if datetime.now() > self.ending_date: if not self.complete: return True else: pass else: pass html(only included related code to the problem): {% if task.is_end_date %} #code {% else %} #code -
I Use for loop inside django template, but Django Generic editing views don't send data to template
I'm very new to django. I'm creating student attendance system. I can add classes and students in each class. But when it comes to check attendance I get stuck. My model, form, view and template for checking attendance are here: models.py choice_list = [(1, 'Present'), (2, "Absent")] class AttendanceChecking(models.Model): pupil = models.OneToOneField(ClassPupils, on_delete=models.CASCADE, related_name='pupil_attendance') pupil_class = models.ForeignKey(SchoolClassess, on_delete=models.CASCADE, related_name='class_attendance') teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='responsible_attendance') date = models.DateField() mark_attendance = models.CharField(max_length=100, choices=choice_list, default='Present') forms.py choice_list = [(1, 'Present'), (2, "Absent")] class AttendanceForm(forms.ModelForm): mark_attendance = forms.ChoiceField(choices=choice_list) class Meta: model = AttendanceChecking fields = ('mark_attendance',) views.py class AttendanceListView(LoginRequiredMixin, FormView): form_class = AttendanceForm context_object_name = 'classes' model = SchoolClassess template_name = 'app_school/attendance_list_view.html' attendance_list_view.html {% extends 'base.html' %} {% block content %} <form method="POST"> {% if user.is_authenticated %} {% for pupil in classes.pupils.all %} {{ pupil.pupil_lname }} {{pupil.pupil_fname}} {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit" name=""> {% endfor %} {% endif %} </form> {% endblock %} My purpose is creating a table which is the list of all students in a class and additional column for attendance as shown in image students list for checking attendance. when confirm button is clicked the data must be saved db table. I tried, but when I … -
im using django 4.0.2 and i have thist error
i'm new in django and i cant find the error to resolve, it appears on object 'user'. Any suggestions to make this work? It looks like in the past, this would be the answer class Checkout(LoginRequiredMixin, View): def post (self, request): addres = request.POST.get('addres') comment = request.POST.get('comment') cart = request.session.get('cart') user= request.session.get('user') product = Product.get_product_by_id(cart) print(addres, comment, User, cart, product ) for product in product: print(cart.get(str(product.id))) order = Order(user=User(id=user), product=product, price=product.price, addres=addres, comment=comment, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect ('cart:cart_detail') i was watching a tutorial and doing it but i cant resolve the error that appearsenter image description here, i cant find a solution yet class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product): if str(product.id) not in self.cart.keys(): self.cart[product.id]={ "product_id": product.id, "title":product.title, "quantity": 1, "image":product.image.url, "thumbnail":product.thumbnail.url, "price": str(product.price) } else: for key, value in self.cart.items(): if key== str(product.id): value["quantity"] = value["quantity"]+ 1 break self.save() def save(self): self.session["cart"] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def decrement(self, product): for key, value in self.cart.items(): if key == str(product.id): value["quantity"] = value["quantity"]- 1 if … -
Pesquisa por id em django
Estou tentando realizar uma busca por um imóvel pelo id do imóvel, mas não está me retornando nada, o código é seguinte: def buscaPorCodigo(request): id = request.GET.get('id') imovel = get_object_or_404(Imovei, id=id) sugestoes = Imovei.objects.filter(cidade=imovel.cidade).exclude(id=id)[:2] return render(request, 'imovel.html', {'imovel': imovel, 'sugestoes': sugestoes, 'id': id}) -
django pytest / update delete view testing
I'm working on pytest testing for my 1st django app, kind of cookery book. I have problems with edit/delete view tests. For example, i have a test for testing add recipe view. Here is recipe model: class Recipe(models.Model): """Instructions how to prepare a single dish.""" title = models.CharField(max_length=50) cooking_time = models.IntegerField(help_text='in minutes', validators=[MinValueValidator(1), MaxValueValidator(5000)]) difficulty_level = models.IntegerField(choices=DIFFICULTY_LEVELS, default=1) description = models.TextField() created = models.DateTimeField(auto_now_add=True) cuisine = models.ForeignKey('Cuisine', on_delete=models.CASCADE, null=True) ingredient = models.ManyToManyField(Ingredient, through='IngredientRecipe') meal_plan = models.ManyToManyField('MealPlan', through='RecipeMealPlan') here is it's fixture: @pytest.fixture() def example_recipe(): rec = Recipe.objects.create(title='rec', cooking_time=10, difficulty_level=2, description='bla, bla, bla') return rec And tests which works fine: @pytest.mark.django_db def test_add_recipe(client, example_recipe): dct = { 'title': 'rec', 'cooking_time': 10, 'difficulty_level': 2, 'description': 'bla, bla, bla' } url = reverse('add-recipe') response = client.post(url, dct) assert response.status_code == 302 assert Recipe.objects.get(**dct) @pytest.mark.django_db def test_add_recipe2(client): url = reverse('add-recipe') response = client.get(url) assert response.status_code == 302 Now I'm trying to write test for recipe update/delete views. My recipe update test currently looks like this: @pytest.mark.django_db def test_ingredient_update_view(client, example_ingredient): url = reverse('update-ingredient', kwargs={'id': example_ingredient.id}) response = client.get(url) assert Ingredient.objects.save( name='cos', nutrient=2, glycemic_index=2 ) I know its wrong but i face problems to make it work. Same with delete view. Could someone take a look … -
What should I use to enter data to my database on Django? Django admin or SQL code?
I am a newbie in programming, but now I connected my project with PostgreSQL. I learned the way to enter by SQL code and also found out that we can actually enter /adming (by creating the superuser and add data there). So which one is widely used in webdev? -
Redis server run on heroku
I am using windows and I have deployed a Django project to heroku. This project need to run a redis server for a chatroom. I ran it perfectly on my localhost, but after I deployed it to heroku, the redis server only run in redis://127.0.0.1:6379 only. I have tried to change the redis.conf file from bind 127.0.0.1 to bind mywebsite but it doesn't work. Thanks for all help in advance -
How to send url from template to view in django
How can I send a URL from a template to a view? I have noticed that a normal string works but a URL doesn't. Here is what I have tried. path('imageviewer/<str:theimage>', mainviews.imageviewer, name="imageviewer"), def imageviewer(request, theimage): response = render(request, "imageviewer.html", {"theimage": theimage}) return response How I attempt to pass it : (value.image) is a url <a href="{% url 'imageviewer' theimage=value.image %}" class="effect-lily tm-post-link tm-pt-60"> Error I Get: Reverse for 'imageviewer' with keyword arguments '{'theimage': 'https://storage.googleapis.com/katakata-cb1db.appspot.com/images/humours/1643758561'}' not found. 1 pattern(s) tried: ['imageviewer/(?P<theimage>[^/]+)\\Z'] Thank you. -
What does the empty list passed in the assert function mean?
sorry for the weird title. I am currently learning Django, and going through their tutorial. In Part 5, it discusses test cases which I am understanding well. However, I am unclear what the last line of the snippet means. def test_future_question(self): #questions with a pub_date in the future aren't displayed on the index page. create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) Why must we pass an empty list? It doesn't make any sense to me, and I am just wanting to learn why. Thank you! -
How do i access request.user in self.client.post Testing
I have a model called Quote which has a ForeignKey pointing to User. I want to make a post request to create a Quote but i don't know what data i should give to self.client.post, this is what i got so far i am talking about the test_can_save_a_POST_request: from django.contrib.auth import get_user_model from django.test import TestCase from quotes.models import Quote from quotes.views import home_page User = get_user_model() class HomePageTest(TestCase): def test_uses_home_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'home.html') def test_display_all_quotes(self): user1 = User.objects.create(email="rafik@test.com", password="foo") Quote.objects.create(text='quote 1', user=user1) Quote.objects.create(text='quote 2', user=user1) response = self.client.get('/') self.assertIn('quote 1', response.content.decode()) self.assertIn('quote 2', response.content.decode()) def test_can_save_a_POST_request(self): user1 = User.objects.create(email="rafik@test.com", password="foo") self.client.post('/', data={ 'quote_text': 'The first ever quote' } ) -
Error while deploying django channels to amazon elastic beanstalk
I am facing an issue with websockets. When I run the program locally it works fine but when I deploy it to aws elastic beanstalk I face the following issue. I have a simple code as mentioned below. django.config ``` option_settings: aws:elasticbeanstalk:container:python: WSGIPath: playzone.wsgi:application aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static ``` Procfile ``` web: gunicorn playzone.wsgi websocket: daphne -p 5000 my_app.asgi:application ``` asgi.py ```py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from . import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') application = get_asgi_application() application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': URLRouter( routing.websocket_urlpatterns ) }) And there are 2 more simple files `routing.py` and `consumers.py`. I've even configured the load balancers on the environment's settings (80 - HTTP ; 5000 - HTTP). So once deployed, when I try routing to the webpage which has a websocket connection, I get an error saying `WebSocket connection to 'ws://zzzzzzzzzzzz.com/ws/' failed:`. Please help me out on how I can fix it. Also am not using redis or any channel layer. Please help me out on how I can fix it. -
Webpack: Do not parse specific html tag
I'm using webpack to build html templates using Django's templating language. Django templates contain variables and tags using {{ }} and {% %} syntax. Webpack has ignored these just fine and built the html templates as expected, except when parsing srcset tags. Webpack errors when it tries to parse the following html: <source srcset="{% static 'images/my-image.png' %}"> I'd like webpack to either ignore all srcset tags completely, or have some sort of # noqa equivalent which makes webpack simply not make changes to this row of the file. Is that possible? -
Python: Run a code after return something
This is an ApiView from my django project: class Receive_Payment(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAdminUser,) def get(self, request, cc_number): if Card.objects.filter(cc_num = cc_number).exists(): client = Client.objects.get(client_id = (Card.objects.get(cc_num = cc_number).client)) if not client.is_busy: client.is_busy = True client.save() resp = "successful" else: resp = "client_is_busy" else: resp = "fail" return Response({"response": resp}) As you see, if client.is_busy is not True, I'm making it True in here. But in this situation, I need to client.is_busy = False after 30 seconds. If I do it under client.save() code, it delays to response. How can I do it? -
Django - UniqueConstraint not created
I am trying to enforce a constraint for mysql where user is prohibited from inserting twice the same name and model. E.g This should not be allowed to be inserted twice: name:Name1 model:Model1 #Model class Car(models.Model): name = models.CharField(max_length=100) model = models.CharField(max_length=100) #View class CarListCreateAPIView(generics.ListCreateAPIView): serializer_class = CarSerializer def get_queryset(self): trip_code = self.kwargs.get("pk") return Car.objects.filter(trip = trip_code) #Return cars for given trip #Seializer class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('__all__') constraints = [ models.UniqueConstraint(fields=['name', 'model'], name='car_name_model_constraint') ] The problem is that the constraint is never created and thus not enforced. What might be the issue with the code? -
Minio: InvalidRequest when change AWS_S3_FILE_OVERWRITE to False
When AWS_S3_FILE_OVERWRITE was equal to True everything worked fine. But when it was changed to False I get error (when click on link on frontend): At the same time if I copy a link to a file and paste it into browser directly there is no error. Why that's happening this way? P.S. Using django-storages