Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django /static/ files not found, 404 error
I have a problem with loading static files. It wont load images on my page at all. When i look for the address it says /apps/assets/img..... But it should be /static/assets/img like on the home page and login page. (/apps/ is my view name but i don't get it why it loads it like that..( All apps are in my installed apps directory, DIRS in templates is configured, i have 'django.contrib.staticfiles', tried running collectstatic, rerunning the server, ALLOWED_HOSTS = ["*"] , STATIC_URL = '/static/' , STATIC_ROOT = os.path.join(VENV_PATH, 'static_root' -
Is there a method to save model based form for specific user , I tried this but the form did not save on my data base, If I avoid author it saves
here is my models.py file, I try to save task, completed, and completiondate from my front with the logged-in user as a default author. *> #My models.py from django.db import models from django.contrib.auth.models import User class Task(models.Model): task=models.CharField(max_length=50) completed=models.BooleanField (default=False) comletiondate=models.DateTimeField (auto_now_add=False) author = models.ForeignKey(User, on_delete=models.CASCADE,default=None) def __str__(self): return self.task in my views.py file I try to save the data which I get from the front end with specific author #my views.py @login_required(login_url='/') def index(request): form=TaskForm() if request.method == 'POST': form=TaskForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() else: form=TaskForm() return redirect('/') context={'form':form} return render(request, 'todo/index.html',context) #my forms.py from django import forms from.models import * from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class TaskForm(forms.ModelForm ): class Meta: model=Task fields='__all__' class CreateUser(UserCreationForm): class Meta: model=User fields=['username','email', 'password1','password2']* -
How would I integrate BIRT with Python Django Project by using Py4j
Hi is there anyone who is help me to Integrate BIRT report with Django Projects? or any suggestion for connect third party reporting tools with Django like Crystal or Crystal Clear Report. -
Django rest authentication with email verification redirect to flutter app
How can I redirect a user to the mobile app developed in flutter after he has confirmed the authentication link sent by email? I need the token included in the link (same for password reset). Right now it takes me back to the django rest page. I am using dj-rest-auth and allauth to handle authentication in django. -
ModuleNotFoundError: No module named 'musiclibrary.song'
There is an issue while importing model 'Artist' of my django app in views.py. from musiclibrary.song.models import Artist when I runserver it gives ModuleNotFoundError. from django.shortcuts import render from django.http import HttpResponse from musiclibrary.song.models import Artist def hello_world(request): return HttpResponse("Hello World!") def home(request): return render(request, "home.html") def artist(request): artist_list = Artist.objects.all(). //// I have to make this line of code work context = {'artist_list': artist_list} return render(request, 'artist.html', context) Models code: from django.db import models class Artist(models.Model): name = models.CharField(max_length=250) country = models.CharField(max_length=150) birth_year = models.IntegerField() genre = models.CharField(max_length=150) class Song(models.Model): Title = models.CharField(max_length=250) release_date = models.IntegerField() length = models.DateField() artist = models.ForeignKey('Artist', on_delete=models.CASCADE) Error log: File "/Users/m.zcomputer/PycharmProjects/myFirstApp/musiclibrary/musiclibrary/views.py", line 4, in <module> from musiclibrary.song.models import Artist ModuleNotFoundError: No module named 'musiclibrary.song' -
Unexpected back button behavior after encountering external 404 using react SPA
I'm making a SPA app with react 18 and Django. I'm having trouble understanding and fixing an issue where after I encounter a 404 and press back, the browser's title changes but doesn't reload the page, even though the URL changes to match the title. To make it happen, I navigate to the home page, "/". I press a react "Link" to go to "/e" within the SPA. If I press reload on "/e", it works, because I added a path in the django urls.py for "/e" and also a react SPA react router route in my App.js. I then click another link to navigate to "/b". Now that I'm at "/b", which is a a react router route but NOT a django path, and refresh, I get a standard django "natural", non SPA 404. Pressing browser Back, the title of the "/e" route is correct, and the URL itself of the browser is correct, but the page does not reload my SPA and it stays a 404 page. I do not understand this behavior or know how to fix it. If I press back one more time, it will THEN reload the spa, and show "/" correctly, then pressing … -
Why Am I getting an Integrity Error while uploading csv file to django app?
While uploading a csv file I'm getting an Integrity Error. I have a correctly working QuizApp which has models about Quiz, Questions and Answers. But I've created another app csvs to upload csv file with Questions and Answers. While I'm trying to upload a CSV file I'm getting that error. The file isn't uploaded to the website. IntegrityError at /something/admin/csvs/csv/add/ null value in column "quiz_id" of relation "csvs_csv" violates not-null constraint DETAIL: Failing row contains (11, csvs/example_KLOIQJK.csv, 2022-09-15 05:46:25.666689+00, f, null) csvs.models.py class Csv(models.Model): file_name = models.FileField(upload_to="csvs") uploaded = models.DateTimeField(auto_now_add=True) activated = models.BooleanField(default=False) csvs.forms.py from django import forms from csvs.models import Csv class CsvModelForm(forms.ModelForm): class Meta: model = Csv fields = ("file_name",) csvs.views.py from django.shortcuts import render from django.http import HttpResponse from .forms import CsvModelForm # Create your views here. def upload_file_view(request): form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm() return render(request, "csvs/import.html", {"form": form}) quiz.models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse, reverse_lazy import uuid class Quiz(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) short_description = models.CharField(max_length=500) resolution_time = models.PositiveIntegerField( help_text="Quiz Duration in minutes", default=15 ) number_of_questions = models.PositiveIntegerField(default=1) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) is_public = … -
Could not find a version that satisfies the requirement Python
Could not find a version that satisfies the requirement librabbitmq==1.6.1 (from versions: 0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 0.9.9, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.5.0, 1.5.1, 1.5.2, 1.6.0, 1.6.1, 2.0.0) I am getting similar error while install librarabbitmq,numpy,supervisor,xattr,MySQL-python there are specific versions i am trying to install and it pops out the same error while the version remain in the packages it can't find those. -
Django-filters , display min price and max price in the placeholder
I have a models price and using class base views, i have added 'django_filters' to settings as well,this is what i have in my project: model.py class Product(models.Model): price = models.IntegerField(default=0) setting.py 'django_filters', views.py class ProductListView(generic.ListView): template_name = "product/product_list.html" queryset = Product.objects.all() filter_set = ProductFilter filters.py class ProductFilter(django_filters.FilterSet): min_price = django_filters.NumberFilter(field_name="price", lookup_expr='gt',widget=RangeWidget(attrs={'placeholder': 'min_price'})) max_price = django_filters.NumberFilter(field_name="price", lookup_expr='lt',widget=RangeWidget(attrs={'placeholder': 'max_price'})) class Meta: model = Product fields = { 'min_price', 'max_price' } everything is working perfectly when using price only in fields without 'min_price', 'max_price', but what i want is to have min_price and max_price show in my placeholder. When i run the code above, i get this error: "TypeError: 'Meta.fields' must not contain non-model field names: min_price, max_price" -
Restarted Apache2 with Ubuntu for a Django Website, and CSS format no longer recognized. The site only shows basic HTML format. Any ideas to fix this?
I had a functional Django Website that uses Materialize CSS apache2 and ubuntu. I made some small changes to the site (like changed text), then restarted the apache2 server sudo service apache2 restart After the restart, the website no longer showed the CSS format. The website is a basic html website now. I'm a quite new to building websites, so hoping there could be some ideas for what changed after the apache restart. -
Can I create Django widgets at an own discretion?
There is a widget in Django, called NumberInput, the type of which can be defined as range. It is an usual range. There is a graphical element – a slider (a range as well) in a website. That's convenient that it has an animated label with number value. A code and an image of the slider will be on the website. I found a supposed code realizing a similar thing, here is the code from that website: import floppyforms as forms class Slider(forms.RangeInput): min = 5 max = 20 step = 5 template_name = 'slider.html' class Media: js = ( 'js/jquery.min.js', 'js/jquery-ui.min.js', ) css = { 'all': ( 'css/jquery-ui.css', ) } I tried to redefine template_name variable with an html-file containing the code and also to point paths to css and js files but an error appears at testing in Django shell (run as python manage.py shell). If to apply a widget in Django form, to take an instance of the form, and to print the instance, then html code must be returned, but an error did. The error is about not existing a template (TemplateDoesNotExist). I think what to do. Can I create Django widgets at an own discretion? … -
Could not resolve URL for hyperlinked relationship django
Tried the solutions provided in question asked by Daniel Costa. Here is my models.py file class Integrations(models.Model): integration_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) integration_type = models.CharField(primary_key=True, max_length=256) def __str__(self): return self.integration_type class Meta: ordering = ["integration_type"] verbose_name = "Integration" verbose_name_plural = "Integrations" def get_default_mqtt(): return Integrations.objects.get(integration_type="MQTT") class MQTTSubscription(models.Model): mqtt_subscription_name = models.CharField( max_length=256, verbose_name="Subscription Name" ) mqtt_url = models.CharField(max_length=256, verbose_name="Mqtt Host") integration_type = models.ForeignKey( Integrations, default=get_default_mqtt, on_delete=models.PROTECT ) def __str__(self): return self.mqtt_subscription_name class Meta: ordering = ["mqtt_subscription_name"] verbose_name = "MQTT Subscription" The urls.py integrations_list = IntegrationsViewSet.as_view({"get": "list", "post": "create"}) integrations_detail = IntegrationsViewSet.as_view( {"get": "retrieve", "put": "update", "delete": "destroy"} ) mqtt_list = MQTTSubscriptionViewSet.as_view({"get": "list", "post": "create"}) mqtt_detail = MQTTSubscriptionViewSet.as_view( {"get": "retrieve", "put": "update", "delete": "destroy"} ) urlpatterns = [ path("integrations/", integrations_list, name="integrations_list"), path("integrations/<str:integration_type>/", integrations_detail, name="integrations_detaial"), path("mqttsubscription/", mqtt_list, name="mqtt_list"), path("mqttsubscription/<str:mqtt_subscription_name>/", mqtt_detail, name="mqtt_detail"), ] Views.py class IntegrationsViewSet(viewsets.ModelViewSet): serializer_class = IntegrationsSerializer queryset = Integrations.objects.all() lookup_field = "integration_type" class MQTTSubscriptionViewSet(viewsets.ModelViewSet): serializer_class = MQTTSubscriptionSerializer queryset = MQTTSubscription.objects.all() lookup_field = "mqtt_subscription_name" serializers.py class IntegrationsSerializer(serializers.ModelSerializer): class Meta: model = Integrations fields = ["integration_type"] class MQTTSubscriptionSerializer(serializers.ModelSerializer): lookup_field = "integration_name" class Meta: model = MQTTSubscription fields = [ "mqtt_subscription_name", "mqtt_url", "integration_type", ] The issue here is if "integrations/" is removed from urls.py it does not interpret the mqttsubscription/. While I update the … -
django unit testing timezone
In my settings.py I have implemented timezone as TIME_ZONE = os.environ.get("TIMEZONE", "Europe/London") How would I test if this is working on my test_timezone.py file? -
Django URL in Templates with Apache ProxyPass
I have a Django project behind a ProxyPass server in Apache. The project has an app called 'home', with this url patterns: urls.py urlpatterns = [ path('', views.HomeView.as_view(), name='index'), path('projects', views.HomeView.as_view(), name='dashboard'), path('projects/<int:pid>/members', views.ProjectMembersView.as_view(), name='project.members'), There are two URL that have the same View class (the first used for the root). In the HomeView class uses a template called 'dashboard.html' and get a list of projects to send to the template view class HomeView(LoginRequiredMixin, ListView): template_name = 'home/dashboard.html' context_object_name = 'projects' login_url = 'accounts.login' def get_queryset(self): ... # returns a list of projects The template renders a tablet with some information of the project and an URL to see the employess working on the project template <td class="align-middle text-center text-sm"> <a href="{% url 'project.members' pid=project.id %}">See employees</a> </td> In the case, the project behind the Apache ProxyServer, the URL generated in the template is the form: "https://example.com/4554/members", here, Django doesn't recognizes the URL The other situation, without Apache Proxypass the URL generated is like this: "http://127.0.0.1:8000/projects/4554/members", Django can recognize the URL and return the template when click in the link. The ProxyPass configuration in Apache is in file: "/etc/apache2/sites-enabled/the-projects.conf" proxypass <VirtualHost *:80> ServerName example.com ErrorLog /var/log/apache2/projects_perror.log CustomLog /var/log/apache2/projects_access.log combined RequestHeader … -
sqlite3 table is not updating when trying to add pandas dataframe
I am trying to add a Pandas data frame to a sqlite3 table in my Django project. However, when I try to add it to the table, nothing updates and no errors are printed in the console. For reference, the beginning of my code is correctly formatting the date in the csv file and then I am attempting to add it to an empty but existing table named 'daos_transaction' with the same attributes 'from_address', 'to_address', 'date_time', and 'amount'. import pandas as pd import sqlite3 # Reads data from csv file df = pd.read_csv("correct/path/to/csv/file") # Formats the date for dt in range(len(df['date_time'])): no_t_string = df['date_time'][dt].replace('T', ' ') clean_string = no_t_string.split('+')[0] df['date_time'][dt] = clean_string # Converts the column to a date time field df['date_time'] = df['date_time'].astype('datetime64[ns]') cnx = sqlite3.connect('correct/path/to/db') df.to_sql('daos_transaction', cnx, if_exists='append') -
Django Rest Framework With Djoser Jwt
I was looking into have more secure login and logout using JWT authentication and authorization .But in Djoser ,it has 3 endpoints /jwt/create/,/jwt/refresh/,/jwt/verify/. Here I want user login with jwt token and get verified token simultaneously and when logout refresh comes in to get access token.How could I do this? -
I am getting: TypeError: view must be a callable or a list/tuple in the case of include()
My root urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('webarticles.urls')), ] While I have seen this error answered on stackoverflow before, they don't seem to work for me. Specifically there are 2 components of the answers that confuse me: Why url is used instead of path If I am to import webarticles, how to do that given that my project and app are on the same level Thank you for any help you are able to provide! -
How to send html-styled password reset email with django
I created an html-styled version of a password reset email to be set with django located at 'registration/html_password_reset_email.html'. From other stackoverflows, I learned I needed to add the html_email_template_name parameter for the html version of the email to be sent. However, even with the below code, it is just the text version of the file that is being sent ('registration/password_reset_email.html'). Hints on what I'm doing wrong? from django.contrib import admin from django.urls import include, path from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from django.urls import reverse from . import views urlpatterns = [ path('', views.homeview, name="homeview"), path('dashboard/', include('dashboard.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path("register/", views.register_request, name="register"), path('reset_password/', auth_views.PasswordResetView.as_view( template_name='registration/password_reset_form.html', html_email_template_name='registration/html_password_reset_email.html', email_template_name='registration/password_reset_email.html', ), name="reset_password"), # Submit email form path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), # Email sent success message path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), # Link to password reset form in email path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), # Password successfully changed message ] -
Submitting a Django form using a One-To-Many relationship
I'm trying to implement a One-to-Many relationship between two models in Django, and have been doing so based on this answer. I have a very simple Projects model, and a ProjectNotes model, so one Project can have multiple Notes. My models.py: class Project(models.Model): project_name = models.CharField(max_length=500) project_type = models.CharField(max_length=500) project_leader = models.CharField(max_length=500) class ProjectNotes(models.Model): note_date = models.DateField(default=date.today) assigned_project = models.ForeignKey(Project, related_name='projectnotes', on_delete=models.CASCADE) note = models.TextField(max_length=500) My use case for this is to show a webpage showing the info for a given Project object, and show a textfield form where notes can be added (also showing any notes that may exist). To that end I have my forms.py: class AddProjectNoteForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddProjectNoteForm, self).__init__(*args, **kwargs) self.fields['note'].required = True class Meta: model = ProjectNotes fields = ['note'] My template displays the formfield correctly (and I believe would show any notes that existed correctly), however when attempting to submit a note I get an error complaining an id field is null: null value in column "attached_project_id" violates not-null constraint My understanding of this is that the project_id field cannot be blank, but as I don't define it, it is something django handles internally. If that is the case, why is it … -
How to use permissions added using django-rules library in Django App?
I am creating a Django App in which I am using django-rules library to define and add permissions. I have followed the documentation and created the predicates in a separate file called permissions.py. I have also added the permissions in the same file. My permissions.py looks like below: from .models import WorkspaceMembership import rules @rules.predicate def is_workspace_member(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_workspace_member return False @rules.predicate def is_workspace_admin(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_workspace_admin return False @rules.predicate def is_active_member(user, workspace): workspace_membership = WorkspaceMembership.objects.get_by_member_and_workspace(user, workspace) if workspace_membership is not None: return workspace_membership.is_active return False rules.add_perm("accounts.view_workspace", is_workspace_member) rules.add_perm("accounts.view_workspace", is_workspace_admin) rules.add_perm("accounts.view_workspace", is_workspace_member | is_workspace_admin) Now, I want to use these permissions in my class-based views and programmatically like checking below: if user.has_permissions("any-permission") I am unable to figure out that how to use the permissions. Because the predicates will required two objects, one is User instance and another is Workspace instance, in order to work, which are not present in permissions.py file. So, how do I use the permissions, can anybody guide me? -
How do I successfully connect Django to Azure Cache for Redis?
I have a django application that I have just migrated to MS Azure from Digital Ocean, and the app runs perfectly on Azure. However, I'm struggling to implement a cache backend with an Azure Cache for Redis service. I have the following configuration in settings.py: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://<my_redis_service_name>.redis.cache.windows.net:6380,password={secrets.AZURE_REDIS_PASSWORD},ssl=True,abortConnect=False", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", }, } } I have replaced my redis service name with <my_redis_service_name>. With this setup and DEBUG=True, I receive the error: ValueError at /accounts/login/ Redis URL must specify one of the following schemes (redis://, rediss://, unix://) Strange since redis:// is in the url. I have verified the keys, and ensured the redis service firewall accepts my VM's IP4 address, as well as making sure port 6380 is open on the VM. I have also tried various permutations of the connection string, such as: "LOCATION": f'redis://:{secrets.AZURE_REDIS_PASSWORD}@<my_redis_service_name>.redis.cache.windows.net:6380,ssl=True,abortConnect=False', No luck. If it's relevant, I'm using Django 4.0.7, Python 3.8, django-cachalot, and jazzband's django-redis pacakge. Azure Cache for Redis states that it's using Redis version 6.0.14. For what it's worth, my development environment works fine with a local daemonized redis cache at "LOCATION": "redis://127.0.0.1:6379/1",. Any help appreciated. -
How Can I filter Django Models To Get Field Values From Different Tables
I am working on Django Ticketing Application where I have a Pin Status Check View. And I want to query the Pin Model to know whether the PIN is activated, and if Activated query the Guest, and Profile Models to get the guest profile information and display in template. I have been able to use Django Forms with search to display the PIN details but NOT able to figure out the logic code for getting the guest profile if PIN is ACTIVATED. Someone may wish to help. thanks. Models code: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) phone = PhoneNumberField() image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) #Method to save Image def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) #Check for Image Height and Width then resize it then save if img.height > 200 or img.width > 150: output_size = (150, 250) img.thumbnail(output_size) img.save(self.image.path) def __str__(self): return f'{self.user.username}-Profile' class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, … -
Django ValueError: Cannot assign * must be a * instance
I am getting this error but I don't know why. models.py class Year(models.Model): year = models.CharField(max_length=5, unique=True) class Meta: ordering = ['-year'] def __str__(self): return self.year class Photo(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='photos/') thumbnail = ResizedImageField(blank=True, size=[360, 360], force_format='JPEG', upload_to='thumbnails/') submitter = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) year = models.ForeignKey(Year, blank=True, on_delete=models.CASCADE) views.py def photo_create_view(request): form = AddPhotoForm() if request.method == 'POST': image = request.FILES['image'] thumbnail = request.FILES['image'] title = request.POST.get('title') description = request.POST.get('description') year = request.POST.get('year') people = request.POST.get('people') tags = request.POST.get('tags') photo = Photo(image=image, thumbnail=thumbnail, title=title, description=description, year=year, people=people, tags=tags, submitter=request.user,) photo.save() return redirect('/photo/?page=1') return render(request, 'photoapp/create.html', context={'form':form}) Cannot assign "123": "Photo.year" must be a "Year" instance. I have checked the Year table and year.id 123 exists. What am I missing? -
Django update multiple objects with options
I want to update the same field for multiple objects with the same value giving the user the available choices for that given field in a view, all this accessible from a custom action. I'm stuck at getting the value selected by the user in the view. I don't want to use the mass_edit package. This would be the custom action in the modeladmin in admin.py: def edit_selected(self, request, queryset, extra_context=None): context = {} labels = models.Label.objects.all() crop_ids = [] for i in queryset.values(): crop_id = i.get('id') crop_ids.append(crop_id) context = { "labels": labels, "ids": crop_ids, } return render(request, template_name="bulk_edit.html",context=context ) my template in bulk_edit.html: {% extends 'admin/base.html' %} {% csrf_token %} {% load spex_template %} {% block content %} {# {% if user.is_autheticated %}#} <div class="row"> <div class="col-md-12"> <form method="get"> {{ filter.form.as_p1 }} <select style="width:100px" name="label" placeholder="Add new Label" id="id_label__id"> <option value="none" selected disabled hidden>New Label</option> {% for label in labels %} <option value="{{ label.id }}">{{ label.id }} - {{label.name}}</option> {% endfor %} </select> <button type="submit">Update</button> <br> </form> <div class="card card-body"> <div><h1>Crop Ids: {% for id in ids %} {{ id }}, {% endfor %} </h1></div> <table class="table table-sm"> <tr> </tr> <br> </table> </div> </div> </div> {# {% endif %}#} … -
Django widget tweaks and variable attributes
Trying to include variables as attributes and values into a form field in a Django app. There is a somewhat related thread but to my understanding it covers one side of the problem I am facing with django-widget-tweaks / custom tags. In my case I not only want to assign a dynamic value to a predefined attribute (which I can do with extra template tags as described for instance here) but to first dynamically create an attribute and assign a value to it for the purpose of htmx requests such as hx-post or hx-delete. Including partials behaves as expected if I specify the type of htmx request directly in render_field and pass the value (in this case URL) via include as well as when I add the attribute and hard code its value using |attr: like so: {% include "partials/input-text.html" with field=form.email|attr:"hx-post:/search/" %} I have tried to apply append_attr the newly created attribute but I'm seeing AttributeError: 'SafeString' object has no attribute 'as_widget' and also getting a sensation that I'm missing the point. Ideally I'm seeking to be able to pass attribute&value as variables (could be via custom template tags), along the lines of {% include "partials/input-text.html" with field|attr:"{{hxaction}}:{{hxurl}}" %}