Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does django cache.set() store weird characters
When I save the string via django's cache framework from django.core.cache import cache cache.set('host_cache_key_81e44325-c046-44c6-88d7-bad7cd91ec13', ""brown.example.com:8006") And try to get the value out: 127.0.0.1:6379> get :1:host_cache_key_81e44325-c046-44c6-88d7-bad7cd91ec13 "\x80\x05\x95&\x00\x00\x00\x00\x00\x00\x00\x8c\"brown.example.com:8006\x94." I get some weird characters around it, why is that and how to make it not do it? -
Django set formset with current user
Django 3.2.7 I have a form that contains multiple inlineformset_factory formset. For all my models, they all have a meta field call created_by. Only the main form Person's created_by is filled by current user. For all the formsets (emailfs, imagefs), it did not set their created_by with current user. How can I do that? Here is my views and my 7 different failed approaches. # views.py class PersonCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): ... model = Person form_class = PersonForm def get_context_data(self, **kwargs): context = super(PersonCreateView, self).get_context_data(**kwargs) if self.request.POST: context["emailfs"] = PersonEmailFormSet( self.request.POST, self.request.FILES ) context["imagefs"] = PersonImageFormSet( self.request.POST, self.request.FILES ) # Method 6 # context["imagefs"] = PersonImageFormSet( # self.request.POST, self.request.FILES, user=self.request.user # ) # Method 7 # context["imagefs"] = PersonImageFormSet( # self.request.POST, self.request.FILES, form_kwarg={'created_by': self.request.user} # ) else: context["emailfs"] = PersonEmailFormSet() context["imagefs"] = PersonImageFormSet() return context def form_valid(self, form): form.instance.created_by = self.request.user context = self.get_context_data() emailfs = context["emailfs"] imagefs = context["imagefs"] personfs = [emailfs, imagefs] if ( form.is_valid() and all(fs.is_valid() for fs in personfs) ): self.object = form.save() for fs in personfs: # Method 1 # fs.created_by = self.request.user # Method 2 # self.created_by = self.request.user fs.instance = self.object # Method 3 # fs.created_by = self.request.user # Method 4 # fs.instance.created_by = … -
how can I get the id of the object from Subjects model?
I want to associate a post for that certain object in the subject's model but I can't figure it out (error in views.py). Your help is appreciated for a beginner like me. models.py class Subjects(models.Model): title = models.CharField(max_length=200) slug = AutoSlugField(populate_from=['title'], max_length=250, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.title}" @property def posts(self): return Post.objects.filter(subject=self) class Post(models.Model): subject = models.ForeignKey( Subjects, on_delete=models.CASCADE, related_name='subject_model') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views.py class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'post/post_create.html' model = Post fields = ['body'] success_url = '/' def form_valid(self, form): form.instance.author = self.request.user form.instance.subject_id = self.kwargs['id'] # error here form.save() return super(PostCreateView, self).form_valid(form) urls.py urlpatterns = [ path('', views.CourseList.as_view(), name='course_list'), path('create_subject', views.SubjectCreateView.as_view(), name='create_subject'), # register path('register/', views.register, name='register'), # detailview path('<int:id>/', views.SubjectDetailView.as_view(), name='subject-detail'), # post create view path('post/new/', views.PostCreateView.as_view(), name='post-create') ] error KeyError at /post/new/ 'id' -
How can I pass a page param in Django url template tag?
I'm creating a simple search application. I have a model with some data, and the index page is just a search bar that search results of that model. I'm creating the form using just HTML, not a proper Django Form. index.html: <form method="get" action="{% url 'core:search' %}?page=1&q={{ request.GET.q }}"> <div class="form-floating mb-3"> <input type="search" class="form-control" id="floatingInput" name="q" value="{{ request.GET.q }}"> <label for="floatingInput">Type your search</label> </div> <button class="w-100 btn btn-lg btn-primary" type="submit">Search</button> </form> The results are paginated, so I need that the url requested by the form is http://127.0.0.1:8000/search/?page=1&q=query, query being the search term typed in the input. But what I wrote in the action parameter in the form doesn't work as I expected: even though it's writen action="{% url 'core:search' %}?page=1&q={{ request.GET.q }}, the URL requested is just http://127.0.0.1:8000/search/?q=query. The page param simply doesn't show up. I wrote page=1 because, as is the search result, the first one requested is always the first page. The view that process this request is the search_view. I'm putting it below just as more info, but I think the problem is my misunderstanding of url template tag in the action form parameter. search_view: def search_view(request): posts = Post.objects.all() query = request.GET.get('q') page_num = request.GET.get('page') … -
How to know when testing? Django
i'm writing tests for a django app and i need to know whether a view is in a test. # views.py class SomeClass(View): def get(self, request): # how to know if this view is called by test? Thank you! -
getting specific errors type message from HTTPError while working django +firebase
i was trying to make signup page using django and while using the ff code user = auth_.create_user_with_email_and_password(email, password) while reaching this point it throws different errors depending on user input like if user input short password less than 6 characters and also if email is already registered .... with same code error 400 and i need that message to to identify the specific error and display the error back here is the message : [Errno 400 Client Error: Bad Request for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIzaSyBmnhaFGTVelDMkPQ3pjvdPMQc28c-JrTs] { "error": { "code": 400, "message": "WEAK_PASSWORD : Password should be at least 6 characters", "errors": [ { "message": "WEAK_PASSWORD : Password should be at least 6 characters", "domain": "global", "reason": "invalid" } ] } } -
How to remove buttons from CKeditor 4 in Django using settings.py
I am trying to remove buttons from CKeditor 4 toolbar from Django's settings.py file I added the following line to CKEDITOR_CONFIGS but it didn't work 'removeButtons' : ['Underline,JustifyCenter'], The CKEDITOR_CONFIGS lines: CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here 'toolbarGroups': [ # { 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }, # { 'name': 'clipboard', 'groups': [ 'clipboard', 'undo' ] }, # { 'name': 'editing', 'groups': [ 'find', 'selection', 'spellchecker' ] }, # { 'name': 'forms' }, { 'name': 'basicstyles', 'groups': [ 'basicstyles', 'cleanup' ] }, { 'name': 'paragraph', 'groups': [ 'list', 'indent','align' ] }, { 'name': 'links' }, { 'name': 'insert' }, { 'name': 'styles'}, # { 'name': 'colors' }, # { 'name': 'tools' }, # { 'name': 'others' }, # { 'name': 'about' } ], # 'removeButtons' : ['Underline,JustifyCenter'], # 'height': 291, # 'width': '100%', # 'filebrowserWindowHeight': 725, # 'filebrowserWindowWidth': 940, # 'toolbarCanCollapse': True, # 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML', 'tabSpaces': 4, 'extraPlugins': ','.join([ 'uploadimage', # the upload image feature # your extra plugins here 'div', 'autolink', 'autoembed', 'embedsemantic', 'autogrow', # 'devtools', 'widget', 'lineutils', 'clipboard', 'dialog', 'dialogui', 'elementspath' ]), } } -
Djano annotate with subtract operation returns None when the subtrahend is None
My objective is to get the balance for a billing instance by subtracting the payments posted within the period. In my Billing model, I have a backlog field that contains the backlogs from previous period. The Billing model has m2m relationship with Payment model through PaidBills model. In my queryset: ''' qs = Billing.objects.filter( bill_batch=prev_batch, balance__gt=0).annotate( payment=Sum('paidbills__amount_paid', filter=Q( paidbills__pay_period=batch.period))).order_by( 'reservation__tenant__name', 'reservation__apt_unit').only( 'id', 'bill_batch', 'reservation') qs = qs.annotate(new_bal=F('backlog') - F('payment')) ''' The result is correct when the expression F('payment') contains a value, but will give a result None when F('payment') returns None. I have tried to replace the expression F('payment') with any fixed value, say 5000, and it worked as expected. How to go about this? (Django 3.2.7, Python 3.9.5) -
error: Table <name_table> dosen't exist in mysql (The Django)
I have created successfully a database and data table in MySQL by command line, but until retrieving the table then It's doesn't exist (I using the Django framework), and when checking in the database, the data table doesn't. Can anyone help me, please, thanks in advance enter image description here enter image description here enter image description here -
Python - Invalid Syntax - Why is this error being thrown?
I already know that this is going to be a trashy question, as per the SO question guidelines, but I have to keep details down to a minimum. I have a traceback, but I don't know why its throwing an error. Traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "...USER...\threading.py", line 954, in _bootstrap_inner self.run() File "...USER...\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "...USER...\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "...USER...\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "...USER...\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "...USER...\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "...USER...\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "...USER...\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "...USER...\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "...USER...\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "...USER...\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "...USER...\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "...USER...\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "...USER...\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen … -
How can I do a multi file upload in Django, allowing user to remove file upload before form submission?
I am trying to do a fairly common user requirement, allowing the user to upload multiple files in Django, and giving them the option to remove files that they may have accidentally uploaded. As far as I can tell, even if the user remove the uploaded files from the DOM prior to the user submitting the form via Javascript code as shown here...Multiple file upload - with 'remove file' link, the uploaded files remain in the request.FILES.getlist(''). I have spent most of today researching this. I have in fact determined that when the uploaded files are deleted via Javascript from the DOM they are in fact still present in the request.FILES.getlist(''). I verified this by printing out the contents of the getlist file in my CreateView as shown below... list=[] #myfile is the key of a multi value dictionary, values are the uploaded files for f in request.FILES.getlist('files1'): #myfile is the name of your html file button filename = f.name print(filename) My question is how can I get the contents of the DOM and compare it to what's in request.FILES.getlist? I surmise that's how I'll be able to tell Django what's real and what's not. Thanks in advance for any … -
How to make 2 way access verification in django?
I would like to improve security for access, making a 2 way access verification using a code to send to whatsapp or by using a qrcode. Is there any program or library with such a function? -
Django: Why does database login every query?
In my settings.py, I have a database configured. I have a page that issues a sql query against the database defined in settings.py every 10 seconds. I have been using it for 1 year now and never had any issues with it. My database admin ran a login audit on our database. As it turns out, each individual single sql query has a unique login to the database. His audit took 5 minutes to run just today and it is because of my django application logging in. I was pretty surprised to find out that every query that is issues has a unique login attempt to the database. Is there anyway to create a "session" for the backend database in settings.py. I really feel that the application should have a single login and use that session to issue commands. Did I miss a setting to do this? Sql login audit: -
Amazon RDS: OperationalError: (2003, "Can't connect to MySQL server on rds.amazonaws.com (110)"
I have set up a MySQL database and I'm trying to connect it with my application. But I'm getting the above error. My database settings in settings.py are as follows: DATABASES = { 'default': { 'ENGINE': config('db_engine'), 'NAME': config('db_name'), 'USER': config('db_user'), 'PASSWORD': config('db_password'), 'HOST': config('db_host'), 'PORT': config('db_port') } } and my database environment variables are these: db_engine=django.db.backends.mysql db_name=stagingdatabase db_user=staginguser db_password=stagingpassword db_host=somestagingname.somestagingid.us-east-2.rds.amazonaws.com db_port=3306 I know the port is correct, which is the solution for most cases of these types of errors. All other variables are correct as well. I can't ping somestagingname.somestagingid.us-east-2.rds.amazonaws.com even though it's status is available, so there must be an issue in this: -
calculate difference between consecutive numbers in rows af the same model
I am trying to calculate the difference between consecutive numeric values in the odometer_reading field of my model. My Models.py has fields like below: class Refuel(models.Model): vehicle = models.ForeignKey(Vehicle, blank=True, null=True, on_delete=models.SET_NULL) gaz_station = models.ForeignKey( GazStation, related_name=_("Station"), blank=True, null=True, on_delete=models.SET_NULL ) odometer_reading = models.PositiveIntegerField(_("Compteur KM"), blank=True, null=True) snitch = models.PositiveIntegerField(_("Mouchard KM"), blank=True, null=True) fuel_quantity = models.DecimalField(_("Quantitée en Litres"), max_digits=5, decimal_places=1) fuel_unit_price = models.DecimalField(_("Prix en DH"), max_digits=6, decimal_places=2) note = models.CharField(_("Remarque"), max_length=255, blank=True, null=True) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) is_active = models.BooleanField(default=True) @property def total_price(self): total_price = self.fuel_quantity * self.fuel_unit_price return total_price class Meta: ordering = ["gaz_station", "-created_at"] def __str__(self): return self.vehicle.serie I want to use a CBV to get the distance between every two refuel for the same vehicle so I can calculate fuel consumption per km. is there a way to do it? -
calling from browser to phone - django
I am working on an app using Django, I want my users to call clients using the app just by clicking on the call button and then the clients receive the call on their phone, I want you to suggest to me the first steps I have to follow. thank you, I will really appreciate your help and guide. -
How to save celery task to a temporary db which will then be updated to the master db
What is a good way to compare new data with old data which is updated everyday with Django ORM? Basically I have a scraper which fetches hackathons everyday (basically just a celery task) and I want the newest to be unioned it with my master database which has the latest fetched hackathons from yesterday. I don't want to destroy my master database and then just upload everything that I just fetched since that seems wasteful. -
I am getting a pre-receive hook declined when trying to push to heroku
I am trying to push my python/django project to heroku for deplyment but I keep getting ! [remote rejected] master -> master (pre-receive hook declined) . not sure why is this happening ? I have tried deleting and starting over but nothing happened, any ideas please ?! -
import error in parallel folders python django cant be fixed with PYTHONPATH
django structure this is my django structure I am trying to import "home_view" function from Pages APP to main urls in "Kianwoodco" project these statements seem to be not working from ..Pages.views import home_view from src.Pages.views import home view also importing views is giving out the same error as result errors : no module name 'src' attempted relative import beyond top-level package any help would be appreciated I have tried sys.path.append("#path to Pages") and adding init.py to src -
How to use jQuery to find balance from Debit and Credit in Django row table
Please help, i have my Django app where i have row table where fetch numbers from database and it work correctly, i have one problem i want to calculate balance by taking balance plus debit side and minus credit side by using jquery but refer what i get in a link plus what i expect. Note: I failed to use django itself because balance doesn`t saved to database What i get: [https://paste.pics/DW7TA] Expected: [https://paste.pics/DW7WP] javascript < script > $(document).ready(function() { $('tr').each(function() { var balance = []; $(this).find('#col1').each(function() { var bal = $(this).text(); if (bal.length !== 0) { var bala = $("#balance").text(); balance = bal + bala } }); $(this).find('#col2').each(function() { var bal = $(this).text(); if (bal.length !== 0) { var bala = $("#balance").text(); balance = bala - bal } }); $(this).find("#balance").html(balance); }); }); < /script> html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <th>DR</th> <th>CR</th> <th>BALANCE</th> </tr> {% for statement in customer_stat %} <tr style="margin-top: 20px; font-size: 25px; margin-left: 90px;"> <td class="col" id="col1">{{statement.total_amount}}</td> <td class="col" id="col2">{{statement.to_amount}}</td> <td id="balance"></td> </tr> {% endfor %} </table> -
django project : static directory not available in docker
i'm working on a personal project, basic webapp, which is working fine locally. /home/mxp/DOCKER/django_cv/django/venv/bin/gunicorn my_cv.wsgi --bind 0.0.0.0:8000 -e "DEBUG=1" -e "SECRET_KEY=****" -e "DJANGO_ALLOWED_HOSTS=localhost 127.0.01" [2021-09-16 20:50:13 +0200] [560882] [INFO] Starting gunicorn 20.1.0 [2021-09-16 20:50:13 +0200] [560882] [INFO] Listening at: http://0.0.0.0:8000 (560882) [2021-09-16 20:50:13 +0200] [560882] [INFO] Using worker: sync [2021-09-16 20:50:13 +0200] [560884] [INFO] Booting worker with pid: 560884 now i run the same image with my Dockerfile as follow FROM python:3.8 RUN apt-get update RUN mkdir /usr/src/app RUN useradd -U django RUN mkdir /home/django && chown django:django /home/django USER django ENV MICRO_SERVICE=/usr/src/app/django COPY . $MICRO_SERVICE WORKDIR $MICRO_SERVICE ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH=$PATH:/home/django/.local/bin RUN pip install --upgrade pip RUN pip install -r requirements.txt WORKDIR /usr/src/app/django/my_cv% And i have this not found message : sudo docker run -p 80:8000 7484050feceb gunicorn my_cv.wsgi --bind 0.0.0.0:8000 -e "DEBUG=1" -e "SECRET_KEY=****" -e "DJANGO_ALLOWED_HOSTS=localhost 127.0.01" [2021-09-16 19:10:04 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2021-09-16 19:10:04 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2021-09-16 19:10:04 +0000] [1] [INFO] Using worker: sync [2021-09-16 19:10:04 +0000] [8] [INFO] Booting worker with pid: 8 Not Found: /static/cv/custom.css Not Found: /static/cv/me.jpg I know that this is not the best way, and that i should use an nginx … -
vuejs + django passwordreset email and redirect to vue front end
I am trying to implement a password reset by sending the email to users using Django in the backend and vue in the frontend (both work on different IP addresses). I tried by using the package django-rest-passwordreset and the steps provided by (Django REST-Auth Password Reset and https://newbedev.com/django-rest-auth-password-reset) its not clear what is vuedj.constant and how they are importing site_url, site_full_name, site_shortcut_name from vuedj.constants. I even tried by custom based ResetPasswordEmailRequestSerializer and SetNewPasswordSerializer I am able to get email by using these, but not able to redirect to frontend or get uidb64 and token for the specific user in the frontend. serializers.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from rest_framework.exceptions import AuthenticationFailed from django.utils.encoding import force_str from django.utils.http import urlsafe_base64_decode class ResetPasswordEmailRequestSerializer(serializers.Serializer): email = serializers.EmailField(min_length=2) redirect_url = serializers.CharField(max_length=500, required=False) class Meta: fields = ['email'] class SetNewPasswordSerializer(serializers.Serializer): password = serializers.CharField( min_length=6, max_length=68, write_only=True) token = serializers.CharField( min_length=1, write_only=True) uidb64 = serializers.CharField( min_length=1, write_only=True) class Meta: fields = ['password', 'token', 'uidb64'] def validate(self, attrs): try: password = attrs.get('password') token = attrs.get('token') uidb64 = attrs.get('uidb64') id = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(id=id) if not PasswordResetTokenGenerator().check_token(user, token): raise AuthenticationFailed('The reset link is invalid', 401) user.set_password(password) user.save() return (user) except Exception as e: raise AuthenticationFailed('The reset link is … -
Is it possible to use gunicorn for my Django app inside a WSL Ubuntu system?
I am working on a Windows 10 machine using Ubuntu inside WSL. I did this because I cannot get gunicorn to work as I've researched it is not available in Windows. I can successfully run my app using my docker-compose file within my WSL Ubuntu perfectly fine. I then run the gunicorn myapp.wsgi command and the server spins up with the terminal giving me the following output: [2021-09-16 19:11:53 +0000] [25] [INFO] Starting gunicorn 20.1.0 [2021-09-16 19:11:53 +0000] [25] [INFO] Listening at: http://127.0.0.1:8000 (25) [2021-09-16 19:11:53 +0000] [25] [INFO] Using worker: sync [2021-09-16 19:11:53 +0000] [26] [INFO] Booting worker with pid: 26 However, I cannot connect to my site at localhost:8000. I also did a curl request against the localhost:8000 from inside my docker container and got a 302 error. I've researched using gunicorn, mod_wsgi and uwsgi, all given as options in the Django documentation. However, I want to use gunicorn or uwsgi to have access to either nginx or Apache (plus the documentation on mod_wsgi has a dead link for the windows install file). Does anyone have suggestions on how I can get this to work? -
Django NoReverseMatch at logout function error
I am encountering such an error in the logout part of my Django project. I tried many ways with examples I searched on the internet, but the error does not go away. layout.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"> <title>Layout</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> --> <link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet"> </head> <body> {% block content %} {% endblock %} <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> dash.html {% extends 'layout.html'%} {% load static %} {% block content %} <div class="sidebar-container"> <div class="sidebar-logo"> Ox.v1 </div> <ul class="sidebar-navigation"> <li> <a href="#"> <i class="fa fa-home" aria-hidden="true"></i>Anasayfa </a> </li> <li> <a href="#"> <i class="fas fa-chart-line"></i> Dashboard </a> </li> <li> <a href="#"> <i class="fas fa-phone-volume"></i> Infotmation </a> </li> <li> <a href="#"> <i class="fas fa-adjust"></i> Users </a> </li> <li> <a href="{% url 'logout_view' %}"> <i class="fas fa-outdent"></i> Exit </a> </li> </ul> </div> {% endblock %} views.py from django.shortcuts import render from django.db import connections from django.shortcuts import redirect, render from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User … -
Is there a downside of redirecting to another view rather than returning it directly?
I've built a hardcoded target_url to use it as redirect argument to trigger another view. I could also return this view directly, but I want the user to have the specific url in the browser address field. Is there any downside to call the other view directly other than having a different url than desired? I don't think that Version 1 is common practice: # Version 1 def view_one(request): [..] target_url_view_two = '/poller/' + str(random_poller_id) + '/' return redirect(target_url_view_two, request, random_poller_id) # Version 2 def view_one(request): [..] return view_two(request, random_poller_id)