如何解决Django:在 ModelField 中显示实例字符串值
我在将它发送到前端之前初始化了一个 ModelForm。一切正常,但生成的表单显示“associative_subscription”和“course” ID,但我想显示转换后的字符串值(对用户更易读)。
这是我的代码:
models.py
class CourseSubscription(models.Model):
start_date = models.DateField(default=datetime.date.today,null=False,blank=False,verbose_name="Data di inizio")
associative_subscription = models.ForeignKey(AssociativeSubscription,on_delete= models.CASCADE,verbose_name="Iscrizione Associativa")
course = models.ForeignKey(Course,verbose_name="Corso")
fee_paid = models.DecimalField(max_digits=7,decimal_places=2,verbose_name="Quota versata")
payment_completed = models.BooleanField(default=False,verbose_name="Pagamento Completo")
expiration_date = models.DateField(editable=False,verbose_name="Scadenza")
payment_method = models.CharField(
max_length = 4,verbose_name="Modalità di pagamento",choices=PAYMENTS
)
class Meta:
unique_together = ("associative_subscription","course")
def __str__(self):
return u'%s / Iscrizione corso %s dal %s al %s' % (self.associative_subscription.member,self.course,self.start_date.strftime('%d/%m/%Y'),self.expiration_date.strftime('%d/%m/%Y'))
forms.py
class CourseSubscriptionForm(ModelForm):
def __init__(self,max_value,*args,**kwargs):
super(CourseSubscriptionForm,self).__init__(*args,**kwargs)
self.fields['fee_paid'] = forms.DecimalField(
max_digits=7,required=True,label="Quota Versata",min_value=0.01,max_value=max_value,help_text= f"Valore Massimo: {max_value}",widget = forms.Numberinput()
)
class Meta:
model = CourseSubscription
exclude = ('expiration_date','payment_completed')
widgets = {
'associative_subscription': forms.TextInput(attrs={'readonly':'readonly'}),'course' : forms.TextInput(attrs={'readonly':'readonly'})
}
views.py
def add_course_subscription(request,associative_subscription_id,course_id):
if request.method == 'POST':
...
return JsonResponse(context)
associative_subscription = AssociativeSubscription.objects.get(id= associative_subscription_id)
course = Course.objects.get(id = course_id)
remaining_fee = course.inscription_price
form = CourseSubscriptionForm(
initial={
'associative_subscription': associative_subscription,'course':course,'fee_paid': 1.00,},max_value = remaining_fee
)
return render(request,'form.html',{'form': form})
That's what I obtain,but I want the __str__
result of the instance
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。