我知道如果我需要为django-admin中的字段定制"选择器",我需要创建一个自定义小部件.但是,如果小部件必须生成两个值,例如X和Y坐标,如何将它们填充到模型的两个不同字段中呢?
创建接受浮点数并具有与 NumberInput 相同功能的 django 表单字段的最佳方法是什么?我的意思是使用相同的功能是 django 的 NumberInput 在输入旁边有箭头,可以增加或减少数字,它也接受 min_value 和 max_value。如果我使用 TextInput 小部件,我将无法获得此功能。如果我使用 NumberInput 小部件,它将不适用于浮点数:
homework = forms.FloatField(required=False, max_value=10, min_value=0, widget=NumberInput(attrs={'id': 'form_homework'}))
Run Code Online (Sandbox Code Playgroud)

当我单击 + - 按钮时,它不包括浮点数(即 5.5)。此外,如果我想将实际浮点数(作业成绩)设置为初始值(使用 Jquery),它根本不显示浮点数。
欢迎任何建议。
编辑:
如果我做:
class NumberInput(TextInput):
input_type = 'number'
homework = forms.FloatField(required=False, max_value=10, min_value=0,
widget=NumberInput(attrs={'id': 'form_homework', 'step': '0.1'}))
Run Code Online (Sandbox Code Playgroud)
'step' 属性有效,但 max_value/min_value 无效。如果我不以这种方式定义 NumberInput 并使用常规的 NumberInput,则它根本不起作用。
我正在使用SelectDateWidget小部件在表单字段中输入日期.但我希望它默认显示当前日期.我怎样才能做到这一点?
model.py
bdate = models.DateField(default=datetime.date.today())
Run Code Online (Sandbox Code Playgroud)
这是错误的.任何人都可以告诉正确的方法吗?
另外,我的模板
{{ form.bdate }}
Run Code Online (Sandbox Code Playgroud)
当我在我的模板中使用上面提到的行时,它显示如下- - - 但我想要这样的月份日期.我怎样才能做到这一点?
我的表格是:
widgets = {
'bdate' : SelectDateWidget(),
}
Run Code Online (Sandbox Code Playgroud) 我有以下型号:
class Profile(models.Model):
verified = models.BooleanField(default=False)
def primary_phone(self):
return self.phone_set.get(primary=True)
class Phone(models.Model):
profile = models.ForeignKey(Profile)
type = models.CharField(choices=PHONE_TYPES, max_length=16)
number = models.CharField(max_length=32)
primary = models.BooleanField(default=False)
def save(self, force_insert=False, force_update=False, using=None):
if self.primary:
# clear the primary attribute of other phones of the related profile
self.profile.phone_set.update(primary=False)
self.save(force_insert, force_update, using)
Run Code Online (Sandbox Code Playgroud)
我Phone在ModelForm中用作formset.我要做的是Phone.primary在每个实例旁边显示一个单选按钮Phone.如果我将primary作为RadioSelect小部件:
class PhoneForm(ModelForm):
primary = forms.BooleanField(widget=forms.RadioSelect( choices=((0, 'False'), (1, 'True')) ))
class Meta:
from accounts.models import Phone
model = Phone
fields = ('primary', 'type', …Run Code Online (Sandbox Code Playgroud) 具体来说,我想在一个表单中呈现日期小部件,但我希望它"成为"HTML5(所以我可以忘记javascript或其他任何东西并相信Chrome,Opera和Safari来显示日期选择器).
请不要使用JavaScript解决方案,我已经在网上找到了这些解决方案.
这是我的代码片段,但它仍然将表单字段的类型属性thedate作为"文本".
#models.py
class MyModel(models.Model):
user = models.ForeignKey(User)
thedate = models.DateField()
#forms.py
class MyModelForm(ModelForm):
class Meta:
model = MyModel
widgets = {
'thedate': TextInput(attrs={'type': 'date'}),
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以请光明灯?
提前致谢.
我试图在一行上显示使用Django SelectDateWidget渲染出的3个选择字段.当我使用酥脆的表格时,它们都在不同的行上.有没有办法使用Layout帮助器来实现这一目标?
谢谢!
class WineAddForm(forms.ModelForm):
hold_until = forms.DateField(widget=SelectDateWidget(years=range(1950, datetime.date.today().year+50)), required=False)
drink_before = forms.DateField(widget=SelectDateWidget(years=range(1950, datetime.date.today().year+50)), required=False)
helper = FormHelper()
helper.form_method = 'POST'
helper.form_class = 'form-horizontal'
helper.label_class = 'col-lg-2'
helper.field_class = 'col-lg-8'
helper.add_input(Submit('submit', 'Submit', css_class='btn-wine'))
helper.layout = Layout(
'name',
'year',
'description',
'country',
'region',
'sub_region',
'appellation',
'wine_type',
'producer',
'varietal',
'label_pic',
'hold_until',
'drink_before',
)
class Meta:
model = wine
exclude = ('user', 'slug', 'likes')
Run Code Online (Sandbox Code Playgroud) 是否存在Django小部件的任何示例,这些小部件对具有"通过"属性的ManyToManyFields有用吗?例如,我有这些模型(从django文档获取源代码):
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
Run Code Online (Sandbox Code Playgroud)
很明显,标准的ModelMultipleChoiceField在这里不起作用.我需要在添加时填充'date_joined'和'invite_reason'.实现这一目标的最简单方法是什么?
我正在努力将JSONEditor集成到Django管理员中.我的模型中有一个字段使用Postgres JSON,这个库中的树编辑器是完美的.
class Executable(models.Model):
""" Simplified model for sake of the question."""
recipe = JSONField(null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)
我已经取得了不错的进展(我认为)将JSONEditor库集成在Django Admin的相应创建/编辑屏幕中.加载时数据显示正确,但由于某些原因,当我在JSONEditorWidget中进行编辑时,不会保存更改.我确信save我需要处理一些覆盖,或者我遗漏了一些显而易见的东西,但我真的不确定从哪里开始.
import json
from django import forms, utils
from django.contrib import admin
from .models import Executable
class JSONEditorWidget(forms.Widget):
html_template = """
<div id='%(name)s_editor_holder'></div>
<script type="text/javascript">
var options = {
"mode": "tree",
"search": true
};
var %(name)s_editor = new JSONEditor(container, options);
var json = %(value)s
%(name)s_editor.set(json);
%(name)s_editor.expandAll();
var json = %(name)s_editor.get(json);
</script>
<textarea readonly class="vLargeTextField" cols="40" …Run Code Online (Sandbox Code Playgroud) django django-admin django-widget django-admin-tools django-jsonfield
如果某个字段有小部件错误,我如何访问?
使用默认我试过:
{% if widget.attributes.has_errors %} or {% if widget.has_errors %}
Run Code Online (Sandbox Code Playgroud)
但是没有用.
我使用自定义窗口小部件模板,我想使用自定义窗体字段并覆盖默认字段.
我知道clean方法存在,但我不知道如何向我的小部件推送我想要的动态(非默认)数据/属性.
我试过了:
class AWidget(forms.Widget):
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
has_errors = context['widget']['attrs'].pop('has_errors', None)
context['widget']['has_errors'] = has_errors
Run Code Online (Sandbox Code Playgroud)
它适用errors但我不知道是否是最好的选择加上我想从Form Field传递其他值/属性,我认为最好尝试覆盖Form Field但我不确切知道如何.
还使用以下方式访问各个属
{{ widget.attrs.maxlength }} or {{ widget.attrs.items.maxlength }}
Run Code Online (Sandbox Code Playgroud)
即使在for循环中加入也是如此
我知道我可以添加一个带有一类错误的父div:
<div class="{% if form.field.errors %}pass_error{% endif %}">
{{ form.field }}
</div>
Run Code Online (Sandbox Code Playgroud)
但是,这意味着css级别的重大变化.
我已经使用自定义小部件覆盖所有Django小部件,错误我不仅需要更改边框颜色,而是显示或不显示小部件模板的不同元素以及其中一些的位置发生变化.
我已经修改了基于窗口小部件以添加错误,但是我希望通过从字段传递到窗口小部件,以及根据错误类型的参数,以更优雅的方式在字段级别执行此操作.
所以我的问题是我需要覆盖从字段传递到窗口小部件错误和其他变量?
我即将DurationField为管理站点添加 的小部件,并希望持续时间字段的小部件用于输入。
PromoCode下面的类中有DurationField就是duration。但在管理中它显示TextInput为输入。
class PromoCode(models.Model):
"""
Promo Code model to maintain offers
"""
code = models.CharField(_("Code"), max_length=60, help_text="Promo code")
# Validations and constraints for promo code
start_date = models.DateField(_("Start date"), null=True, blank=True, help_text="Start date of promo code offer")
end_date = models.DateField(_("End date"), null=True, blank=True, help_text="End date of promo code offer")
duration = models.DurationField(_("Duration"), null=True, blank=True, help_text="Validity period of promo code")
...
...
Run Code Online (Sandbox Code Playgroud)
管理员.py
class PromoCodeAdmin(admin.ModelAdmin):
"""
Model admin for promocodes …Run Code Online (Sandbox Code Playgroud)