我使用的是django-ajax-selects,這是一個免費的django應用程序,提供jQuery自動完成功能。django-ajax-selecting應用程序:如果數據庫中尚未存在一個新對象,我該如何創建一個新對象?
我得到它的工作 - 即它是自動完成我想要的表單字段。
class Skater(models.Model):
name = models.CharField(max_length=64)
surname = models.CharField(max_length=64)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
class Partnership(models.Model):
female_partner = models.ForeignKey(Skater, limit_choices_to = {'gender': FEMALE}, related_name='female_partner_set')
male_partner = models.ForeignKey(Skater, limit_choices_to = {'gender': MALE}, related_name='male_partner_set')
我希望用戶能夠把一個名字和姓成female_partner和male_partner:但是我有一個問題...我在其中添加了合作對象數據庫中的ModelForm使用它即使這樣的Skater對象不存在,我也希望創建該對象。我如何去做這件事?我不能把代碼放在窗體的保存方法中,因爲這個字段不會被驗證(它不是一個有效的Skater)。
EDIT 1: 添加在多個代碼...
形式:
class PartnershipAddForm(forms.ModelForm):
female_partner = AutoCompleteSelectField('female_skater',required=True)
male_partner = AutoCompleteSelectField('male_skater',required=True)
class Meta:
model = Partnership
settings.py:
AJAX_LOOKUP_CHANNELS = {
'female_skater' : ('skaters.lookups', 'FemaleLookup'),
'male_skater' : ('skaters.lookups', 'MaleLookup'),
}
lookups.py(MaleLookup是相同的除了性別=男性):
class FemaleLookup(object):
def get_query(self,q,request):
""" return a query set. you also have access to request.user if needed """
return Skater.objects.filter(Q(gender=FEMALE) & (Q(name__istartswith=q) | Q(surname__istartswith=q)))
def format_item(self,skater):
""" simple display of an object when it is displayed in the list of selected objects """
return unicode(skater)
def format_result(self,skater):
""" a more verbose display, used in the search results display. may contain html and multi-lines """
return "%s<br/>" % unicode(skater)
def get_objects(self,ids):
""" given a list of ids, return the objects ordered as you would like them on the admin page.
this is for displaying the currently selected items (in the case of a ManyToMany field)
"""
return Skater.objects.filter(pk__in=ids).order_by('name','surname')
+1使用AutoCompleteField,唯一的問題是,當使用窗體進行編輯時,該字段預先填充了id而不是文本值。 – 2017-03-31 10:30:12