Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, is it possible to force prefetch_related to exec only one SQL query?
with these models: class CustomUser(PaymentUserMixin, AbstractUser): pass class Customer(StripeModel): subscriber = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name="djstripe_customers", ) Is it possible to force this QuerySet to use only one SQL query (instead of two) ? CustomUser.objects.prefetch_related('djstripe_customers').get(email="user@gmail.com") that generates that: SELECT "accounts_customuser"."id" FROM "accounts_customuser" WHERE "accounts_customuser"."email" = 'user@gmail.com' LIMIT 21; args=('user@gmail.com',) SELECT "djstripe_customer"."djstripe_id" FROM "djstripe_customer" WHERE "djstripe_customer"."subscriber_id" IN (6); args=(6,) Note: I cannot modify Customer model -
Editing Django formset data creating new records instead of updating
I am trying to update a group of formsets that are related the main form (Project Information) by the main forms pk. The create form works fine, but I am finding it extremely difficult to implement the update version. I swear to you that I have read everything and taken some online courses and I just cannot get this. The form that is presented to the user has a dropdown choice and they select the project they would like to update. I've included an image of this. The selected project triggers an AJAX request to def project_data(request) below in view.py and the data for each formset is looped through and the formsets are created dynamically and populated. This also can be partially seem in the included image. All of that works fine. It's the save as an update part that I cannot for the life of me figure out. Here comes the example. Don't laugh! view.py @login_required def edit_project(request): SampleInformationFormSet = formset_factory(SampleInformationForm, extra=1) DissolutionMethodsFormSet = formset_factory(DissolutionMethodsForm, extra=1) DissolutionEndAnalysisFormSet = formset_factory(DissolutionEndAnalysisForm, extra=1) DissolutionSamplingFormSet = formset_factory(DissolutionSamplingForm, extra=1) DissolutionStandardsFormSet = formset_factory(DissolutionStandardsForm, extra=1) DissolutionMediaFormSet = formset_factory(DissolutionMediaForm, extra=1) DissolutionAnalysisRunFormSet = formset_factory(DissolutionAnalysisRunForm, extra=1) form = ProjectInformationForm(request.POST or None) si_formset = SampleInformationFormSet(request.POST or None, prefix='si') d_formset = … -
The django admin login in is not working and the template is lost
I just get into the Django. everything works on my local: enter image description here but after I deploy it on the on Heroku, the admin login page becomes like this: enter image description here enter image description here and I can not log in ever thought I create the superuser. here is my setting.py INSTALLED_APPS = [ 'event.apps.EventConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', #'django.contrib.gis', ] 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', ] ROOT_URLCONF = 'meetUpFinder.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS':[os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] WSGI_APPLICATION = 'meetUpFinder.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR , 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR , 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, … -
Django and Azure SQL Database connection error?
I'm trying to link my SQL database in azure to my django application, here are my settings: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'network-project', 'USER': 'adminenrique@network-project', 'PASSWORD': '***', 'HOST': 'network-project.database.windows.net', 'PORT': '1433', 'OPTIONS': { 'driver':'ODBC Driver 13 for SQL Server' }, }} Here's the error when I'm trying to migrate: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial...Traceback (most recent call last): File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\sql_server\pyodbc\base.py", line 546, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Foreign key 'django_admin_log_user_id_c564eba6_fk_network_user_id' references invalid table 'network_user'. (1767) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Could not create constraint or index. See previous errors. (1750)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Enrique Mota\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Enrique … -
Cant get page to redirect with Django
I cant seem to get the redirecting to work. Everything else works up till there please help. Below are my code and error views.py error -
How does one keep a user logged in with Django Rest Framework?
I'm new to Django coming from the Firebase world, where authentication and keeping a user logged in is super easy. In learning Django (Rest Framework) I came to find out that you can log in a user, get a token and save the token in Cookies to reuse is next time that same user goes into the website. Is this the best way to keep a user logged in? So far, I can log a user in, get their token and some additional info, but I'm not sure how to prevent this from happening over and over again. I'd like to know how to keep the user logged in. Also, whenever the user gets back on the browser, do I place a POST request to get their own information (if needed to display on the screen)? Always? I'm very confused as to how authentication/logging in works. -
Show all user articles in his profile (DetailView) [django]
In user appI have Profile model: class Profile(AbstractUser, HitCountMixin): bio = models.TextField(blank=True, null=True, default='Brak') slug = models.SlugField(null=False, unique=True) photo = models.ImageField(blank=True, null=True, upload_to='profile_photos') In Views: class ProfileView(HitCountDetailView): model = Profile template_name = 'profile/profile.html' count_hit = True Also I have 2 other app: articles and videos. class AllArticlesListView(ListView): template_name = 'news/articles_list.html' model = Article paginate_by = 5 def get_queryset(self): return self.model.objects.all().order_by('-pk') class AllVideosListView(ListView): template_name = 'video/videos_list.html' model = Video queryset = Video.objects.order_by('-pk') paginate_by = 5 How can I put all user articles and videos to his profile to ProfileView(DetailView)? -
Retrieving multiple rows from seperate model in django relationships
I've been struggling with this puzzled for a few hours. Here's a schema of what I'm trying to do. I have a user model and a profile model, it's a one-to-one relationship, but I'd like to be able to query a user and retrieve all the email addresses (from the User model) for users that share the same company (from the Profile Model). To be fair, my understanding of django is limited, but I went through the serializer relations guide and tried my hands at most approach described there, to no avail. At this point, I'm not even sure I'm on the right path. So, my understanding of it is From the user, I need to fetch the profile (a source='profile' approach may work) From that profile, I need to retrieve the company From that company, I need to retrieve all the user_id that belongs to that company From those user_ids, I need to lookup the email fields of all those users I need to also filter out the email address of the user making the request Does this make any sense? At this point, I'm trying to accomplish all of that from the serializer, but was unsuccessful. Here are … -
How to render markdown file to HTML using django?
I am trying to render a page that written in markdown to HTML when clicking a link using Django. but every time I click on the link the markdown page does not render will here's my views.py: from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def search(request, name): return render(request, f"{ name }.md") and here's the urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.search, name="search") ] -
How to export arabic characters to pdf in xhtml2pdf?
I want to export arabic characters to pdf using xhtml2pdf, cause I'm using it in my django app. I know that they made an update saying that they fixed it, but it didn't work with me, I used a custom font but still not working. So please anyone knows the right encryption for this or anyway around it, help me. invoice.html : {% load static %} <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <head> <title>{{title}}</title> <style type="text/css"> @font-face { font-family: Amiri, "Amiri Font"; src: url("{% static 'font/Amiri-Italic.ttf'%}"); } body { font-weight: 200; font-size: 14px; } </style> </head> <body><pdf:language name="arabic"/> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # {{ invoice_ID }} </p> </div> <div> <div class='details'> <pdf:language name="arabic"/> <p> تجربة</p> customername : {{customer_name}} <br><hr> <hr class='hrItem' /> </div> </div> </body> </html> utils.py : from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None views.py : from django.shortcuts import render, redirect, HttpResponse import pandas as pd from .models import SaleInvoice, TransferWays, User, InstallingCities from siteManagment.models import MarketersManagment, … -
DRF - Create a Viewset Mixin/Baseclass to inherit a viewset-action
I have a website that is essentially a wiki for a DnD campaign that I am participating in. As such it has articles of Creatures, Characters, Locations and more. I wanted to use Viewsets to access them easily and wanted to use a Viewset action (together with a custom router) to be able to look for individual records not through pk, but through various query-parameters. I already have something that works for this, now I would like to apply some inheritance to it to not repeat myself. What I'd like to do is something like this: class WikiBaseViewset (viewsets.ModelViewSet): detail_with_params_url_pattern_suffix: str @action(detail=True, url_name="detail-params", url_path=detail_with_params_url_pattern_suffix) def detail_through_params(self, request, **kwargs): if self.detail_with_params_url_pattern_suffix == "": raise InvalidViewsetURLException("URL of view 'detail_through_params' of WikiBaseViewset is not defined!") model = self.serializer_class.Meta.model instance = get_object_or_404(model, **kwargs) serializer = self.get_serializer(instance) return Response(serializer.data) class CharacterSerializer (serializers.HyperlinkedModelSerializer): class Meta: model = wiki_models.Character fields = '__all__' class CharacterViewSet(WikiBaseViewset): """Called with URLs: character, character/<str: name>""" serializer_class = CharacterSerializer queryset = wiki_models.Character.objects.all() detail_with_params_url_pattern_suffix = "(?P<name__iexact>.+)" However, I'm struggling over the fact that the decorator absolutely requires the URL parameter in the base class. Otherwise the code just doesn't compile. If you were to set detail_with_params_url_pattern_suffix="" in the base-class in order to not get … -
Django-allauth confirm email message redirect to different URL
I am trying to set up django-allauth to verify user emails. Currently, I have set it up to send an email, however, after signup, it redirects to the login page and I do not know how to configure it to should a custom HTML message that users need to verify email address. Currently my signup view is: from allauth.account.utils import * def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() send_email_confirmation(request, user, True) return redirect('main:user_login') else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) How can I configure it so it shows a message: Confirmation email sent to someone@example.com On my custom HTML template. I cannot find this on the docs I only have managed to change the custom email template which I have set in my project directory in: project --app1 --app2 --templates ----account -------email ---------emain_confirmation_message.txt How can I redirect users after signup to a message page that they need to verify their email address? And they can resend if it is incorrect? -
Django Rest Framework - How to return all info from a model in a Response when getting Object of type model is not JSON serializable?
I am trying to return an object with more information after a user logs in. class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) player = Player.objects.get(id=user.pk) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email, 'full_user_info': player, # Object of type Player is not JSON serializable }) I've tried dict(player) but then the error reads TypeError: 'Player' object is not iterable -
AttributeError: 'QuerySet' object has no attribute '_require_cacheprofile'
I have an error when trying to use @cached_as(OmittedLeadEmail) @cached_as(OmittedLeadEmail) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/cacheops/query.py", line 92, in cached_as querysets = lmap(_get_queryset, samples) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/funcy/seqs.py", line 114, in lmap return _lmap(make_func(f, builtin=PY2), *seqs) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/funcy/compat.py", line 8, in lmap return list(map(f, *seqs)) File "/pyenv/versions/3.7.8/lib/python3.7/site-packages/cacheops/query.py", line 88, in _get_queryset queryset._require_cacheprofile() AttributeError: 'QuerySet' object has no attribute '_require_cacheprofile' -
How To Make Files Downloadable But Not shareable
I am developing a music distribution platform like that of Itunes model, I want to be able to allow music artist upload their tracks and sell it, but I want to make it in such a way that they are downloadable after being paid for but when they get to any third party device they can no longer be shared via Bluetooth, social media apps or any file sharing software. I want one music to be unique to a single device. any suggestions ?? -
Django on Heroku: relation "app_label" does not exist
I'm trying to deploy my Django app on Heroku. The build is successful, but the deployment fails with django.db.utils.ProgrammingError: relation "app_label" does not exist. I'm deploying directly from GitHub; the repo is public. I already looked for advice online and added try-except around the urlpatterns as suggested here, but it didn't help. I also have all the migrations committed. Now I'm not sure what might have caused the problem or how to fix it. I have successfully deployed another Django and proceeded the same way now, which is why I'm surprised it doesn't work. I'm trying to connect to the same PostgreSQL DB on Heroku that I use for the other Django app. Is that a problem? Do I need to reconfigure something here? Or do I ever need to run python manage.py migrate manually on Heroku? I think this should be taken care of by my Procfile. Any ideas or tips? I'm using Python 3.8 and Django 3.1. -
Django conditional field display on form
I am trying to make a simple form, that conditionally shows the website input field based on the value of another database field (that is not on the form) status. For the sake of this process the status field is not editable by the user, just by the admin. Both fields are in the same table: profile. After working at this for a while I copped-out and just did the conditional hiding and showing on the template. But, I realise this is the unsophisticated method, and would like to improve it. What I tried so far in forms.py: class WebsiteForm(forms.ModelForm): class Meta: model = Profile fields = ( 'e-mail', 'website', ) if Profile.status == 'personal' : exclude = ('website',) This method in forms.py works effectively, in that I can conditionally show and hide the field if I use test comparitors in the if statement like: if 1 == 1: or if 1 != 1: But, I cannot get an effective test using the field Profile.status, the value in the field seems to be unavailable at the point the if test in forms.py is performed. If I use print(Profile.status) I get the following output in the terminal: user__profile__status__isnull, so I think … -
static files doesnt want to work as they are shown on website
From this link i copied all to create my index.html https://codepen.io/jeffglenn/pen/KNYoKa I copied and pasted all css into new created main.css file in statics and rest of HTML i pasted into my index.html body section, typed on the top {% load static %} created new lane in head <link rel="stylesheet" type="text/css" href="{% static 'wwwapp/main.css' %}"> and when Im restarting localserver, then i can see .css images but they are not moving as they are on demo + they are all the time grey... If you can explain me how can i amend this lane <div class="tl-bg" style="background-image: url(https://placeimg.com/802/802/nature)"></div>to get my .jpg instead of rendered photo from www. my path to downloaded images is wwwapp/static/wwwapp/images/11.jpg and 22.jpg and so one... Can someone help ?:) -
Djang multiple levels of template extension while keeping the elements of the upper levels
I have 3 templates as following: base.html (the top level template, as usual). <body> <div id="header"> ... </div> <div id="content"> {% block content %} {% endblock %} </div> </body> category.html : {% extends "base.html" %} {% block content %} ....display some elements here... <div class="item_row"> {% block level_2_content %} {% endblock %} </div> </div> {% endblock %} and item.htlm {% extends "category/category.html" %} {% block level_2_content %} <div id="test_div"> {% for item in menu_items %} <p>{{item.name}}</p> {% endfor %} </div> {% endblock %} When item.html is rendered, all the elements that were rendered by category.html are gone. Only the elements of the base.html are retained. How do I retain all elements in all parent templates instead of just base.html? A general method to do this for more than 3 levels of extension like in my case? -
Django Rest Framework object has no attribute pk
I am working in Django / DjangoRestFramework trying to use extra actions to build out a foreignkey that is routable. I am getting the following error, I believe it has something to do with the create method on the FinancialsSerializer, or lack thereof, but I am not sure web_1 | AttributeError: 'dict' object has no attribute 'pk' stocks.viewset 19 class StockViewSet(viewsets.ModelViewSet): 20 queryset = Stock.objects.all() 21 serializer_class = StockSerializer 22 lookup_url_kwarg = "ticker" 23 lookup_field = "ticker__iexact" 24 25 @action(detail=True, methods=["POST", "GET"]) 26 def financials(self, request, ticker=None): 27 if request.method == "GET": 28 stock = self.get_object() 29 financials = stock.get_financials() 30 financials = FinancialsSerializer(financials) 31 return Response(financials.data) 32 if request.method == "POST": 33 serializer = FinancialsSerializer(request.data) 34 financials = Financials.objects.create(serializer.data) 35 financials.save() FinancialsSerializer 9 class FinancialsSerializer(WritableNestedModelSerializer): 10 balance_sheet = BalanceSheetSerializer() 11 income_statement = IncomeStatementSerializer() 12 cashflows_statement = CashflowsStatementSerializer() 13 14 class Meta: 15 model = Financials 16 fields = ["balance_sheet", "income_statement", "cashflows_statement"] -
django simple history field indexing
How can I tell DSH to index particular field? Some queries that I do to historical models take too much time I've base abstract model and all my models inherit from that model. The history field is also defined in this base model: class BaseModel(models.Model): class PublishingStatus(models.TextChoices): DRAFT = 'draft', _('Draft') ACCEPTED = 'accepted', _('Accepted'), REJECTED = 'rejected', _('Rejected'), MODIFIED = 'modified', _('Modified') publishing_status = models.CharField( max_length=9, choices=PublishingStatus.choices, default=PublishingStatus.DRAFT, help_text=_("Publishing status represents the state of the object. By default it is 'draft'") ) history = HistoricalRecords(inherit=True) And I've also added indexes in this base model class Meta: abstract = True indexes = [models.Index(fields=[ 'publishing_status', ])] It would be nice if Django Simple History could check which fields are indexed and create the same indexes in the historical models Maybe there is a way to tell django simple history explicitly which field must be indexed additionally? -
ValueError at /profiles/user-profile/ Field 'id' expected a number but got 'testuser'
I am creating follow system in my project but got an error. Can anybody tell me how i can fix it? models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) def __str__(self): return f'{self.user.username}' views.py class UserProfileFollowToggle(View): def post(self, request, *args, **kwargs): print(request.POST) user_to_toggle = request.POST.get('username') print(user_to_toggle) profile_ = UserProfile.objects.get(user__username__iexact=user_to_toggle) profile_1 = request.user.userprofile user = request.user print(user,'p') if user_to_toggle in profile_.follower.all(): profile_.follower.remove(user_to_toggle) else: profile_.follower.add(user_to_toggle) return redirect(f'/profiles/{profile_.pk}') If more code or detail is require than tell me in comments i will share that by updating my question with that detail. -
In Django My form is resubmitting every time I refresh, I know I can solve this by redirecting it but i also want to pass pass data to my template
This is my code in views def pay(request): if request.method == 'POST': name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') course_name=request.POST.get('course_name') amount=int(request.POST.get('amount')) client = razorpay.Client(auth=('rzp_test_W8wCwbUqAGeqku','uETWabWBUeK53r70Qnz0Sg2Vknb')) payment = client.order.create({'amount':amount*100, 'currency':'INR', 'payment_capture':'1'}) order = Order(course_name=course_name, name=name, email=email, phone=phone, amount=amount, payment_id=payment['id']) order.save() return render(request, 'pay.html',{'payment':payment}) `I know I can solve this by redirecting it like this return redirect('womenlab:pay') but I also want to pass payment variable` return render(request, 'pay.html') I do not want every time I refresh the page it get resumbitted, please help -
Djnago Template - Url with multiple parameter
I am using Django template. I want to add multiple parameter in URL currently I am passing only one parameter my reset_password.html Click on this link to reset your password {% if htmlVersion %} <div> <a href="{{domain}}{% url 'pweuser:user_password_sms_reset' token %}"> {{domain}}{% url 'pweuser:user_password_sms_reset' token %} </a> </div> {% else %} {{domain}}{% url 'pweuser:user_password_sms_reset' token %} {% endif %} This link will expire in 15 minutes my urls.py url(r"^resetPasswordSms/(?P<token>[-\w_=]{28})/$", PasswordResetSmsView.as_view(), name="user_password_sms_reset",), my views.py t = loader.get_template("reset_password.html") c = {"htmlVersion": True, "domain": settings.SITE_DOMAIN, "token": token.token} htmlVersion = t.render(c) c = {"htmlVersion": False, "domain": settings.SITE_DOMAIN, "token": token.token} textVersion = t.render(c) Here its is working good in this I want to add more than 1 parameter. means here token is the 1st parameter and I need to add userId as 2nd parameter and need to pass in template.. how can i add multiple parameter in URL and template URL -
Trying to return a variable mid script to my template
I am wanting to display a dynamic count on my home.html. While my for loop is running I would like my Template to display the current count of the loop. Is this possible, and if so what is this process called so I can read up on it. home.html <!DOCTYPE html> <html> <body> {% block content %} {% if output >= 1 %} <p>Current count is {output}</p> {%endif%} {% endblock content %} </body> </html> views.py def page_objects(request): output = 0 for row in c: output = output + 1 return output return render(request, 'home.html') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home'), path('views', views.page_objects, name = 'page_objects') ]