Home > OS >  Django widget tweaks and variable attributes
Django widget tweaks and variable attributes

Time:09-16

Trying to include variables as attributes and values into a form field in a Django app template via a partial/component.

There is a somewhat related thread but to my understanding it covers one side of the problem I am facing with django-widget-tweaks and 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-get or hx-post.

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}}" %}

CodePudding user response:

Everything I've read about doing complicated template stuff like this, there's always people saying it's not what django templates are made for.. So you should try and have as much logic as you can in the backend and not in the template..

and to do this I'd say you should extend the Form.py

Basic Attributes (forms.py)

class TheForm(forms.ModelForm):
    class Meta:
        model = The
        fields = (
            'email',
            )

    def __init__(self,  *args, **kwargs):
        super(TheForm, self).__init__(*args, **kwargs)
        self.fields['email'].widget.attrs={'class': 'form-control', 'hx-post':'/search/'}

More Dynamic Attributes (forms.py)

  • Passing extra kwargs to form
class TheForm(forms.ModelForm):
    class Meta:
        model = The
        fields = (
            'email',
            )

    # helper
    def ValOrDefault(self, key, default_value):
        if self.extra and key in self.extra:
            return self.extra[key]
        return default_value

    def __init__(self,  *args, **kwargs):
        self.extra =  kwargs['extra'] if 'extra' in kwargs else None
        super(TheForm, self).__init__(*args, **kwargs)
        self.fields['email'].widget.attrs={
            'class': 'form-control',
            'hx-post': ValOrDefault('email_hx-post', '/search/'),
        };

More Dynamic Attributes (view.py)

extraDict = {
    'email_hx-post': '/sendmail/{0}'.format(obj.email),
    # more attributes, different fields
}

form = TheForm(extra=extraDict)

Now there's definitely smarter ways you could do the dynamic.. That's just generally what I'd do with my current understanding, probably had some more helper functions

  • Related