Issue
I have one many-to-many field in one of my models which is currently coming as Multiselect but I need a dropdown where users can select multiple values as I have huge data to show.
I am trying this in forms.py but it is not showing the dropdown field.
model.py:
class Chain(models.Model):
chain_id = models.AutoField(primary_key=True)
chain_name = models.CharField(max_length=255, unique=True)
chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE)
history = HistoricalRecords()
class Meta:
ordering = ('chain_name')
def __str__(self):
return self.chain_name
class Brg(models.Model):
brg_campaign_id = models.AutoField(primary_key=True)
campaign_tracking = models.ForeignKey(CampaignTracking, on_delete=models.CASCADE)
brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE, related_name="primary_brg",
help_text='Add Brgs/chain names for these above campaign has run')
brg_benchmark = models.ManyToManyField(Chain, related_name="competitor_brg", null=True,
blank=True, help_text='Add max.5 other benchmarks brgs to check overall impact')
history = HistoricalRecords()
class Meta:
verbose_name = 'Brg Campaign Tracking'
def __str__(self):
return "Brg names list"
forms.py:
class ChainForm(forms.ModelForm):
class Meta:
model: Chain
# fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',)
widgets = {'chain_name': Select()}
Solution
you can use django-ajax-selects
library
https://github.com/crucialfelix/django-ajax-selects/
Define a lookup channel:
yourapp/lookups.py
from ajax_select import register, LookupChannel
from .models import Tag
@register('tags')
class TagsLookup(LookupChannel):
model = Tag
def get_query(self, q, request):
return self.model.objects.filter(name__icontains=q).order_by('name')[:50]
def format_item_display(self, item):
return u"<span class='tag'>%s</span>" % item.name
Add field to a form:
yourapp/forms.py
from ajax_select.fields import AutoCompleteSelectMultipleField
class DocumentForm(ModelForm):
class Meta:
model = Document
tags = AutoCompleteSelectMultipleField('tags')
Answered By - Amir Alaghmandan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.