Создание django виджета 3.x - PullRequest
       7

Создание django виджета 3.x

0 голосов
/ 24 апреля 2020

Я пытался создать виджет формы в Django 3.x, и, похоже, не многие из блогов 2.x работают. Следующее не работает

widgets.py

from django import forms
from django.template import loader
from django.utils.safestring import mark_safe
class AutocompleteInputWidget(forms.Widget):
    template_name = 'widgets/autocomplete.html'

    def get_context(self, name, value, attrs=None):
        return {'widget': {
            'name': name,
            'value': value,
        }}

    def render(self, name, value, attrs=None, renderer=None):
        context = self.get_context(name, value, attrs)
        template = loader.get_template(self.template_name)
        return mark_safe(template)

apps.py

from django.apps import AppConfig
class WidgetsConfig(AppConfig):
    name = 'widgets'

forms.py

from django import forms
from .models import Country, CountryList
from .widgets import AutocompleteInputWidget
class CountryForm(forms.ModelForm):
    name = forms.CharField(max_length=20, widget=AutocompleteInputWidget())
    class Meta:
        model = Country
        fields = ['name']
        # widgets={'last_name':AutocompleteInputWidget()}

lookups.py

from ajax_select import register, LookupChannel
from .models import Country
from django.db.models import Lookup

# @register('country')
class CountryLookup(Lookup):
    model = Country
    def get_query(self, q, request):
        return self.model.objects.filter(country__icontains=q).order_by('country')[:50]

    def format_item_display(self, item):
        return u"<span class='tag'>%s</span>" % item.country

models.py

from django.db.models.fields import Field
Field.register_lookup(CountryLookup)
from django.db import models
from .widgets import AutocompleteInputWidget

class CountryList(models.Model):
    name = models.CharField("name", max_length=20, blank=False, null=False)

class Country(models.Model):
    # country = models.CharField(verbose_name="Country", max_length=20, blank=False, null=False)
    country = models.ForeignKey(CountryList, on_delete=models.PROTECT, verbose_name="Country")
...