因此,我正在从事这个项目,我正在使用JavaScript执行到S3存储桶的上传,为此,我创建了一个小部件并创建了带有URLField的ModelForm。我想使用要用于保存在模型中的URL字段(由Javascript在运行时设置)。
我的代码如下:
widgets.py
class S3DirectWidget(widgets.TextInput):
class Media:
js = (
's3direct/js/bundled.js',
'https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js',
)
css = {
'all': (
's3direct/css/bootstrap-progress.min.css',
's3direct/css/styles.css',
)
}
def __init__(self, *args, **kwargs):
self.upload_to = kwargs.pop('upload_to', None)
super(S3DirectWidget, self).__init__(*args, **kwargs)
def render(self, name, value, attrs=None, **kwargs):
if value:
file_name = os.path.basename(urlunquote_plus(value))
else:
file_name = ''
tpl = os.path.join('s3direct', 's3direct-widget.tpl')
output = render_to_string(tpl, {
'signed_url': reverse('s3direct'),
'element_id': self.build_attrs(attrs).get('id', '') if attrs else '',
'file_name': file_name,
'upload_key': os.path.join(self.upload_to, file_name),
'file_url': value or '',
'name': name,
'style': self.build_attrs(attrs).get('style', '') if attrs else '',
})
return mark_safe(output)
models.py
class Kitten(models.Model):
video = models.URLField(editable=False)
forms.py
class S3DirectUploadForm(forms.ModelForm):
misc = forms.URLField(widget=S3DirectWidget(upload_to='carousel/'))
class Meta:
model = Kitten
exclude = ('video',)
def save(self, commit=False):
super(S3DirectUploadForm, self).__init__(commit)
admin.py
class KittenAdmin(admin.ModelAdmin):
form = S3DirectUploadForm
admin.site.register(Kitten, KittenAdmin)
我的目标是修改misc(FormField)运行时并将其替换为video(ModelField)以保存对象。