gpt4 book ai didi

django-ajax-选择应用程序 : How do I create a new object when there isn't already one in the database?

转载 作者:行者123 更新时间:2023-12-02 14:11:35 34 4
gpt4 key购买 nike

我正在使用django-ajax-selects ,这是一个免费提供的 django 应用程序,提供 jquery 自动完成功能。

我已经让它工作了 - 即它正在自动完成我想要的表单字段。但我有一个问题...我在 ModelForm 中使用它,它将 Partnership 对象添加到数据库中:

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 字段中输入姓名,即使这样的 Skater 对象不存在并且我希望创建该对象。我该怎么做呢?我无法将代码放入表单的保存方法中,因为该字段无法验证(它不是有效的 Skater)。

编辑1:添加更多代码...

形式:

class PartnershipAddForm(forms.ModelForm):
female_partner = AutoCompleteSelectField('female_skater',required=True)
male_partner = AutoCompleteSelectField('male_skater',required=True)

class Meta:
model = Partnership

设置.py:

AJAX_LOOKUP_CHANNELS = {
'female_skater' : ('skaters.lookups', 'FemaleLookup'),
'male_skater' : ('skaters.lookups', 'MaleLookup'),
}

lookups.py(MaleLookup 相同,只是性别=MALE):

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')

最佳答案

AutoCompleteSelectField 保存对象的 ID 而不是文本,这就是为什么我一直遇到“必需”错误的原因(以及 Daniel 的解决方案不起作用的原因)。 value 变量为空,因为不存在的 Skater 没有 id。

我不确定这是最好的方法,但我最终使用 AutoCompleteField 而不是 AutoCompleteSelectField。 AutoCompleteField 保存文本,但它不会为我创建 Skater 对象。

代码:

class PartnershipAddForm(forms.ModelForm):
female_partner = AutoCompleteField('female_skater',required=True)
male_partner = AutoCompleteField('male_skater',required=True)

class Meta:
model = Partnership

def save(self):
partners = [self.cleaned_data['female_partner'],
self.cleaned_data['male_partner']]
name = ['','']
surname = ['','']
for i in [0,1]:
name[i],surname[i] = get_name_surname(partners[i])
partners = [None,None]
partners_created = [None,None]
gender = [FEMALE,MALE]
for i in [0,1]:
partners[i],partners_created[i] = Skater.objects.get_or_create(
name=name[i],
surname=surname[i],
gender=gender[i]
)

partnership, created = Partnership.objects.get_or_create(
female_partner=partners[0],
male_partner=partners[1],
)
return partnership

关于django-ajax-选择应用程序 : How do I create a new object when there isn't already one in the database?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2128947/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com