Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access a Django form field through HTML?
This is how the Django form is written in the html file: <form method='post' action="{%url 'getNewAbstracts' %}"> {% csrf_token %} {{editViewAbstractForm|crispy }} <input type="submit" value="Submit" class="btn btn-primary"> <br><br> </form> This is the form written in the django forms file: class editViewAbstract(forms.ModelForm): class Meta: model = abstract `enter code here` fields = ['abstractTitle', 'publicationDate', 'pmid', 'leadAuthor', 'publicationName', 'abstractBody', 'keywordIdList', 'currentStatus'] I am trying to access a specific field of the form for example the field abstractTitle and change the value of that input box through the html file. The reason is that I need to change the fill-text in the Django form every time that a html button is clicked without reloading the page. What is the best way to do this? Thank you for your help. -
add shortcut or link from storage inside static folder in django
When users upload an image it will be placed in : BASE_DIR/storage folder. My static files are placed in: BASE_DIR/static folder Here is my root folder (BASE_DIR) in following image: I have created a shortcut ( or link) from storage folder inside the static folder, and you can see my static folder in following image: I have a test.jpg inside my storage folder and when i try to open the file in my browser using following url: http://localhost:8000/static/storage/test.jpg I get a 404 error: 'storage\test.jpg' could not be found but when I copy and paste the storage folder without creating a shortcut (or link) browser displays image successfully. my question is how can I display the image using a shortcut or link from storage inside static folder? -
Display different inputs based on one form field in Django
So I've got my models - 'product' from CartItem is a foreign key of a Product: class Product(models.Model): name = models.CharField(max_length=64, verbose_name=_('Name')) type = models.ForeignKey('pizza.ProductType', related_name='pizza', on_delete=models.CASCADE, verbose_name=_('Type')) size = models.ForeignKey('pizza.Size', related_name='pizza', on_delete=models.CASCADE, verbose_name=_('Size')) price = models.DecimalField(max_digits=4, decimal_places=2, verbose_name=_('Price')) class CartItem(models.Model): user = models.ForeignKey('accounts.CustomUser', related_name='carts', on_delete=models.CASCADE, verbose_name='User') product = models.ForeignKey('pizza.Product', related_name='carts', on_delete=models.CASCADE, verbose_name=_('Product')) quantity = models.SmallIntegerField(verbose_name=_('Quantity')) toppings = models.ManyToManyField('pizza.Topping', related_name='cart_items', blank=True) extras = models.ManyToManyField('pizza.SubExtra', related_name='cart_items', blank=True) And I want to use a CreateView to add a product to user cart, but I want a user to choose Product Type and Product Size and based on that selection I would add a product to cart, so instead of the field 'product' in form, I would like user to see 'product__type' and 'product__size' in the form. I tried with something like that, but it doesn't work: class CartItemForm(forms.ModelForm): class Meta: model = CartItem fields = ['product__type', 'product__size', 'quantity', 'toppings', 'extras'] Is there a way to do it? -
In Django with Django REST Framework, what is the best way to update old objects when adding new field?
I have a database with a model that I'm updating by adding a new field. When I added the field, all the old objects in the database populated that field with an empty string value. I need these fields to have values. In the future, objects be forced to contain a value by either specification or a default value. What is the best way to update this field for the old objects? I have a couple ideas but I'm not sure if one is 'proper.' Again, this is something that only needs to be done once, as all future objects will have all required data. Enable PUT by adding the UpdateModelMixin to the ViewSet, then disable PUT (I do not want PUT permanently allowed) Create some sort of migration script to do the updates for me. Something I'm missing? -
Switch from using one database to having one for auth and one for everything else
Within my Django app I currently only have one DB, under settings it is default. What I want to do is port over all of the Auth tables created by Django to a separate database, Ill say SiteAuth for now. I have copied all of the auth tables over to the SiteAuth db, but I am not sure how to integrate those changes within the site. I know I am going to have to add another db the databases section of settings, But I am not sure how to do the migrations, or how to specify which database I want to query. How would I do the migrations? how would I specify which database I want to query? how would my models.py change? Thanks for all the help! -
Django Urls - Template Issue {% url '' %}
When I started Django I used 1.11 and since then upgraded to 2.0. My urls worked and had no problems and I would imagine something has been updated but I keep going over the documentation and I can't see where the issue is. From what I've seen my url in template is correct, even though I have also tried with '' and still get the same issue. NoReverseMatch at /admin/dashboard Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/admin/dashboard Django Version: 2.2.6 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Exception Location: /home/bridgetsarah/.local/lib/python3.5/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 673 Python Executable: /usr/bin/python3 Python Version: 3.5.2 Python Path: ['/home/bridgetsarah/voyage/bridgetsarah', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/bridgetsarah/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Fri, 25 Oct 2019 19:26:43 +0000 Any information, would be much appreciated. <ul> 24 <li> <i class="fas fa-tachometer-alt"></i> <a href="#"> Dashboard </a> </li> 25 <li><i class="fas fa-tasks"></i> <a href='#'> Projects </a> </li> 26 <li><i class="fas fa-users"></i> <a href="{% url client %}"> Clients </a> </li> 27 <li><i class="fas fa-server"></i><a href='#'> Servers </a> </li> 28 </ul> 29 from django.urls import include, path , … -
Python / Django: Make a lookup / database query inside a model class
What is the right way to lookup a table and use its last value as a value in a new model class? Something like this: class MyClass(models.Model): id = models.AutoField(primary_key=True) obj = MyClass.objects.latest('id') my_field = models.IntegerField(default=(obj+1)) -
Django built-in tags encoding '?' to '%3F'
I'm trying to do a pagination that passes in ?page={{ page_num }} into the end of the url. This is what I'm trying to do and this is what the output is: $('#prev-page').click(() => { window.location.pathname = "{% url 'xadmin:get_deposits' %}?page={{ page_no|add:'-1' }}" }); $('#next-page').click(() => { window.location.pathname = "{% url 'xadmin:get_deposits' %}?page={{ page_no|add:'1' }}" }); Expected URL: http://localhost:8000/xadmin/deposits/?page=1 Actual URL: http://localhost:8000/xadmin/deposits/%3Fpage=1 -
Trouble opening a WEBSOCKET connection between Angular 2+ client and DJANGO backend
I am trying to open a websocket connection from my angular 2+ app with my Django backend using Django Channels. I went through this tutorial: https://www.youtube.com/watch?v=RVH05S1qab8 and managed to get everything working with the javascript portion written inline in a Django html template. But I am having issues simply opening a websocket connection when I migrated the front-end chat form to a separate angular 2 app. Both font-end and backends are hosted locally. Front End - Chat Form Template <div *ngFor="let message of thread.messages"> <div>{{message.message}}</div> </div> <form #formData [formGroup]="form"> <div class="form-group"> <input formControlName="messageInput" #msgInput type="text" class="form-control" id="newMessage" placeholder="Type a message"> </div> <button (click)="onSubmit($event)" type="submit" class="btn btn-primary">Send</button> </form> </div> Front End - Chat Form Component otherUser: User; me: User; threadId: number; thread: Thread; endpoint: string; socket: WebSocket; form = new FormGroup({ messageInput: new FormControl("") }); get messageInput() { return this.form.get('messageInput'); } getThreadById(id: number) { this._chatService.getThreadById(id).subscribe(thread => { console.log("response: thread found", thread); this.thread = thread; }, error => { console.log("error", error); }); } getEndpoint() { let loc = window.location let wsStart = "ws://" if (loc.protocol == "https:") { wsStart = 'wss://' } this.endpoint = wsStart + loc.host + loc.pathname; return this.endpoint; } constructor(private _activatedRoute: ActivatedRoute) { } ngOnInit() { this._activatedRoute.params.subscribe(params => { … -
Django's rest/login returns wrong user model fields after login
I have created a custom user model using AbstractUser class which is working fine. To login a user i am using rest_auth package. on using url /auth/login, i am able to login the user, but the json that i am getting after login contains fields first_name and last_name which is not included in my custom user model i analyzed parent classes and found that serializer.py file in rest_auth package returns user model on verifying the credentials through authenticate method. i am not able to understand how authenticate method is working model- from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): username = models.CharField(unique=True,max_length=30) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email class UserProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name='profile') photo=models.ImageField(upload_to='uploads',blank=True,null=True) city=models.CharField(max_length=50,blank=True,null=True) dob=models.DateField(blank=True,null=True) firstname=models.CharField(max_length=50,blank=True,null=True) lastname=models.CharField(max_length=50,blank=True,null=True) serializer- from rest_framework import serializers from .models import User,UserProfile class UserProfileSerializers(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('photo','city','dob') class UserSerializers(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializers(required=True) class Meta: model = User fields = ('id','username','email','first_name','last_name','password','profile') def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user=User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user,**profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile print('hello') print(profile) instance.username = validated_data.get('username',instance.username) instance.email = validated_data.get('email',instance.email) instance.first_name = … -
How to add attributes to a Django form widget's media fields?
I can render media files for a django form, through a custom widget, like this: class TinyMCEWidget(Textarea): def __init__(self, attrs=None): if attrs is None: attrs = {} attrs.update({ 'class':'listing-template', }) super().__init__(attrs) class Media: js = ('https://cdn.tiny.cloud/1/my_api_key/tinymce/5/tinymce.min.js/',) But I need to add referrerpolicy="origin" to the script. Is there a way this can be done without a javascript hack? How can I add attributes to a widget's media fields through the widget or form class? This question shows how I can add an arbitrary amount of attributes to a form widget, but does not show how to add attributes to a widget's media fields, therefor my question is not a duplicate. -
ModuleNotFoundError... No Module named Google
I'm trying to link my Google App to cloud storage so I can upload and store images. It worked just fine locally. Now I'm getting this error: (showrooom is the name of my app, and create is the page containing the upload form) ModuleNotFoundError at /showroom/create/ No module named 'google' Following the documentation and previous answers, I used PIP to install google-cloud, google-cloud-vision, and google-cloud-storage. Running pip now shows that google-cloud is installed in my Virtual Environment. Requirement already satisfied: google-cloud in c:\users\user\envs\torque\lib\site-packages (0.34.0)``` But checking in Python (still within the directory and virtualenv), it returns none: >>> import google >>> print(google.__file__) None Can anyone point me in the right direction? There are a lot of interesting errors, so I'll post the full traceback (torque is the name of my app). Request Method: POST Request URL: https://torque-256805.appspot.com/showroom/create/ Django Version: 2.2.5 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'showroom', 'django.contrib.humanize', 'django.contrib.sites', 'crispy_forms', 'allauth', 'allauth.account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/env/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/env/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/env/lib/python3.7/site-packages/django/views/generic/base.py" in view 71. return … -
Is it possible in Django to insert data in var/dynamic table name via Models META?
Thank you for reading i am new to Django and For my application it's a requirement to create a table for each client to store his data. Each client table has the same data so i made a Model for it. But the table name is variable: I tried to do this via the Meta: db_table: Other_function The table is not created and i get error. In the url the customername is available, als in the view as variable. I tried to do this via the Meta: db_table: get_create_table The table is not created and i get error. because the function needs the var instance get_create_table(instance) if (instance.organisation in connection.introspection.table_names()): return instance.organisation else: with connection.cursor() as c: c.execute("CREATE TABLE %s (organisation varchar(255)," "organisation_code varchar(255)," % instance.organisation)``` and in the model: ``` class Import(models.Model): class Meta: db_table = get_table_name() organisation = models.CharField(max_length=255) ``` i get of course and error for instance because it doesnt exists from the view. In the view i have: ``` model = Import() model.organisation = organisation model.save() ``` i also changed the model to: ``` class Import(models.Model): class Meta: db_table = get_table_name organisation = models.CharField(max_length=255) ``` but it doesnt create the table and gives errors. i would … -
Adding reviews to shopping cart buid with react and django
I've built a react shopping cart using reactjs and backend build with django is it possible to add customers review's on my web app and i have a Google authentication set up -
How to extend Django groups for dynamic user types?
I have a SaaS project which many companies will use and within the companies there will be employees which will be applied to one of two groups: Supervisor or Non-Supervisor. This will probably look as such: class EmployeeGroup(Group): .... Each company will be able to create their own EmployeeType which falls into one of the EmployeeGroups. e.g. an EmployeeType may be Food and Beverage Supervisor which is an EmployeeGroup: Supervisor: class EmployeeType(models.Model): .... employee_type = models.CharField( max_length=32, default='Server' ) employee_group = models.ForeignKey( EmployeeGroup, null=True ) company = models.ForeignKey( Company, on_delete=models.CASCADE, null=True ) And obviously each User will have an EmployeeType: class User(AbstractUser): .... employee_type = models.ManyToManyField( EmployeeType, null=True, ) In this situation, can several companies share EmployeeGroups without sharing EmployeeTypes? My concern is that if an EmployeeType: Server is created at Company A then Company B will not be able to create an EmployeeType: Server as well. Or that if they do then information will get crossed. It wuold help to have an understanding of how the database works but I do not. Any links to external resources specific to this situation would be greatly appreciated! -
redirect() not directing to proper view
I have the following urls.py: from django.contrib import admin from django.urls import path from users import views as usersViews urlpatterns = [ path('admin/', admin.site.urls), path('', usersViews.index, name = 'index'), path('register/', usersViews.register, name = 'regsister'), ] and the following views.py: from django.shortcuts import render, redirect from .forms import RegistrationForm from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('signed up') def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) # get data from form if form.is_valid(): form.save() # save form? to db? username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') return redirect("index") else: form = RegistrationForm() # pass blank form to template return render(request, 'users/registration.html', {'registrationForm':form}) Upon submission of the form I am being redirected to "/register/index.html" and not "/" (index page). Can anyone help with this? -
Error updating model data using .objects.filter().update() in Django using Djongo "djongo.sql2mongo.SQLDecodeError"
Hello there I'm using Django and MongoDB for building a REST API project. I'm using Djongo for connecting Django with MongoDB I've created my models as follow: Models from djongo import models class OPCNetworkNode(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) address = models.CharField(max_length=100, default="localhost", blank=False, null=False) port = models.CharField(max_length=10, default="58725") class OPCTagBrowserSesson(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) opc_node = models.ForeignKey(OPCNetworkNode, on_delete=models.CASCADE,related_name='node_opc_sesson', unique=True) clientId = models.CharField(max_length=100, blank=False, null=False) token = models.CharField(max_length=100, blank=False, null=False) timestamp = models.DateTimeField(default=timezone.now()) and I've created a function based view as follow: View @api_view(['POST']) def getOPCRoot(request): opc_uri = request.data.get('opc_uri') sessonInstance = OPCTagBrowserSesson.objects.filter(opc_node__address__exact=opc_uri) sessonInstance.update(clientId = "88888888888888") return Response(data={"check cmd"}) But when I request a POST request to the url with the 'opc_uri' parameter to perform an update on the model data it gives me the following error. Error: djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "asset_herarchi_opctagbrowsersesson" SET "clientId" = %(0)s WHERE "asset_herarchi_opctagbrowsersesson"."id" IN (SELECT U0."id" FROM "asset_herarchi_opctagbrowsersesson" U0 INNER JOIN "asset_herarchi_opcnetworknode" U1 ON (U0."opc_node_id" = U1."id") WHERE U1."address" = %(1)s) Params: ('88888888888888', 'localhost') Pymongo error: {'index': 0, 'code': 40081, 'errmsg': '$in requires an array as a second argument, found: missing'} Version: 1.2.35 -
Heroku doesn't upload static files to S3 bucket in production: Possibly permission error
I configured my django app so that it uploads static and media files to S3. I configured everything that my static folder should be public. My media folder has one private and one public folder. Now, locally everything runs perfectly fine. My static files are public, my private media folder is private, my public media folder is public. In production a weird behaviour happens. The only static files being uploaded to my bucket is the folder admin and rest_framework. My custom static files (css etc) are not uploaded. I set my env variables in heroku. And this is my config: #GENERAL AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = 'public-read' #AWS S3 Static AWS_STATIC_LOCATION = 'static' STATIC_URL = 'http://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) STATICFILES_DIR = [os.path.join(BASE_DIR, 'heatbeat_website/static')] STATICFILES_STORAGE = 'config.settings.storage_backends.StaticStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) #AWS S3 Private Media Upload AWS_PUBLIC_MEDIA_LOCATION = 'media/public' AWS_PRIVATE_MEDIA_LOCATION = 'media/private' PRIVATE_FILE_STORAGE = 'config.storage_backends.MediaStorage' # MEDIA # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = str(APPS_DIR('media')) # https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' My storages are: class StaticStorage(S3Boto3Storage): location = settings.AWS_STATIC_LOCATION default_acl = 'public-read' class PublicMediaStorage(S3Boto3Storage): location = settings.AWS_PUBLIC_MEDIA_LOCATION default_acl = 'public-read' file_overwrite = False class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = … -
How does "return render(request, 'path/path')" works in Django?
Please explain how "return render(request, 'path/path')" this works step by step in any particular views.py file in django. MYcode: (views.py) from django.shortcuts import render from basic_app.forms import UserForm,UserProfileInfoForm from . import forms def index(request): return render(request,'basic_app/index.html') def register(request): registered=False if request.method=="POST": profile_form=UserProfileInfoForm(data=request.POST) user_form=UserForm(data=request.POST) if profile_form.is_valid() and user_form.is_valid(): user=user_form.save() user.set_password(user.password) user.save() profile=profile_form.save(commit=False) profile.user=user if 'profile_pic' in request.FILES: profile.profile_pic=request.FILES['profile_pic'] profile.save() registered=True else: print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request,'basic_app/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) Code: (registration.html) {% extends "basic_app/basic.html" %} {% load staticfiles %} {% block body_block %} <div class="jumbotron"> {% if registered %} <h1>Thank you for registering!</h1> {% else %} <h1>Register Here!</h1> <form enctype="multipart/form-data" method="post"> {{user_form.as_p}} {{profile_form.as_p}} {% csrf_token %} <input type="submit" name="" value="Register"> </form> {% endif %} </div> {% endblock %} ALSO EXPLAIN: How the dictionary defined in "return" statement in views.py works step by step. -
inhereting models in forms in django
while I am linking my models to my forms by using forms.ModelForm and running the server the error appearing is "ModelForm has no model class specified" class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class meta: Model= User fields=('username' , 'email' , 'password') -
How to refresh cache from DB in django rest service?
The main intent of this question is to know how to refresh cache from db (which is populated by some other team not in our control) in django rest service which will then be used in serving requests received on rest end point. Currently I am using the following approach but my concern is since python (cpython with GIL) is not multithreaded then can we have following type of code in rest service where one thread is populating cache every 30 mins and main thread is serving requests on rest end point.Here is sample code only for illustration. # mainproject.__init__.py globaldict = {} # cache class MyThread(Thread): def __init__(self, event): Thread.__init__(self) self.stopped = event def run(self): while not self.stopped.wait(1800): refershcachefromdb() # function that takes around 5-6 mins for refreshing cache (global datastructure) from db refershcachefromdb() # this is explicitly called to initially populate cache thread = MyThread(stop_flag) thread.start() # started thread that will refresh cache every 30 mins # views.py import mainproject @api_view(['GET']) def get_data(request): str_param = request.GET.get('paramid') if str_param: try: paramids = [int(x) for x in str_param.split(",")] except ValueError: return JsonResponse({'Error': 'This rest end point only accept comma seperated integers'}, status=422) # using global cache to get records output_dct_lst … -
Text area not reading HTML
I have Django´s Blog APP installed, all working fine, but I need to add posts (via admin) with HTML in the post content field, now, the text area can only read plain text (it doesn´t render HTML). This is the field: (models.py) content = models.TextField() This is the HTML for this field: <h6 class="card-text" ><small>{{post.content|slice:":500" |linebreaks |safe}}</small></h6> Question is: are there special configs for Django/Python in order for the field to render HTML? -
Page not Found (404) in django
Am using django I got this error Page not Found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in VibezT.urls, Django tried these URL patterns, in this order music/ admin/ The empty path didn't match any of these. VibezT\urls.py from django.contrib import admin from django.urls import include, path urlpatterns =[ path('music/', include('music.urls')), path('admin/', admin.site.urls), ] For music URLs I have this code music\urls.py from django.urls import path from . import views urlpattern = [ path(r'^$',/ views.index, name='index') ] For views i have this code from django.http import HttpResponse def index(request): return HttpResponse("Hello World") -
Template tag doesn't respect passed context variable
I'm having an issue with my custom template tag not respecting passed context variable. So, I have a template named task_list.html, which includes paginator.html that references my custom template tag ({% url_replace %}): task_list.html: ... {% include 'paginator.html' with page_obj=tasks_tomorrow page='page_tomorrow' %} ... paginator.html: ... <a class="page-link" href="?{% url_replace page=page_obj.paginator.num_pages %}" ... However, the URL constructed is http://127.0.0.1:8000/todo/?page=2, instead of http://127.0.0.1:8000/todo/?page_tomorrow=2. This is my template tag: from django.utils.http import urlencode from django import template register = template.Library() @register.simple_tag(takes_context=True) def url_replace(context, **kwargs): query = context['request'].GET.dict() query.update(kwargs) return urlencode(query) What is the issue here? -
How to get a value from a select for a variable in javascript
I am trying to get a value from a variable. console.log ($ ('# id_prova'). val ()) works perfectly when inspecting element, console.log (proofIdQuestao), which is part of app.js, does not work. I want to make one dropdown dependent on another. The questions depend on idProva. app.js let urlQuestoes = $('#myForm').data('urlquestoes'); var provaIdQuestao = $('#id_prova').val() console.log($('#id_prova').val()) console.log(provaIdQuestao); console.log(urlQuestoes); $('#questaoSelect').change(function() { let urlQuestoes = $('#myForm').data('urlquestoes'); let questaoIdQuestao = $(this).val(); console.log(questaoIdQuestao); $.ajax({ url: urlQuestoes, data: { questao: provaIdQuestao }, success: function(response) { $('#provaSelect').html(response); } }) }); }); base.html <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" type="text/javascript"></script> </script></head> index.html <form action='/pesquisa' id="myForm" method="GET" data-urlquestoes="{% url 'questoes_choices_ajax' %}" data-urlcategorias="{% url 'categorias_choices_ajax' %}"> {% csrf_token %} <div class="card acik-renk-form"> <div class="card-body"> <div class="row"> <div class="col-md-4"> <div class="form-group"> <label for="provaSelect">Provas</label> {% render_field form.prova title="Provas" class="form-control" %} </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="questaoSelect">Questões</label> <select class="form-control" name='questao' id="questaoSelect"> <option value="">---------</option> </select> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="categoriaSelect">Categoria</label> <select class="form-control" name='categoria' id="categoria"> <option value="">---------</option> {% for categoria in categorias %} <option value={{categoria.idCategoria}}>{{categoria.nomeCategoria}}</option> {% endfor %} </select> </div> </div> </div> <div class="row"> <div class="col-md-10"> <div class="form-group"> <input placeholder="Termo" type="text" name="q" class="form-control"> </div> </div> <div class="col-md-2"> <button type="submit" class="btn btn-block btn-md btn-primary pl-6 pr-6">Pesquisar questões</button> </div> </div> </div> </div> </form>