我正在尝试在Django Admin中实现CSV导入,并保存与CSV文件行对应的批量数据。
这是我的Admin类:
class EmployeeAdmin(admin.ModelAdmin):
list_display = ('user', 'company', 'department', 'designation', 'is_hod', 'is_director')
search_fields = ['user__email', 'user__first_name', 'user__last_name']
form = EmployeeForm
这是我的Form类:
class EmployeeForm(forms.ModelForm):
company = forms.ModelChoiceField(queryset=Companies.objects.all())
file_to_import = forms.FileField()
class Meta:
model = Employee
fields = ("company", "file_to_import")
def save(self, commit=True, *args, **kwargs):
try:
company = self.cleaned_data['company']
records = csv.reader(self.cleaned_data['file_to_import'])
for line in records:
# Get CSV Data.
# Create new employee.
employee = CreateEmployee(...)
except Exception as e:
raise forms.ValidationError('Something went wrong.')
我的员工课程是:
class Employee(models.Model):
user = models.OneToOneField(User, primary_key=True)
company = models.ForeignKey(Companies)
department = models.ForeignKey(Departments)
mobile = models.CharField(max_length=16, default="0", blank=True)
gender = models.CharField(max_length=1, default="m", choices=GENDERS)
image = models.ImageField(upload_to=getImageUploadPath, null=True, blank=True)
designation = models.CharField(max_length=64)
is_hod = models.BooleanField(default=False)
is_director = models.BooleanField(default=False)
当我上传文件并点击save
时,会显示此错误:
'NoneType' object has no attribute 'save'
异常位置:
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py in save_model, line 1045
编辑我知道我需要拨打super.save
,但我无法确定拨打电话的位置,因为doc说保存方法保存并返回实例。但就我而言,超类没有单个实例可以保存和返回。我在这儿失踪了吗?
TIA。
答案 0 :(得分:1)
您应该将super().save()
添加到函数的末尾:
def save(self, *args, commit=True, **kwargs):
try:
company = self.cleaned_data['company']
records = csv.reader(self.cleaned_data['file_to_import'])
for line in records:
# Get CSV Data.
# Create new employee.
employee = CreateEmployee(...)
super().save(*args, **kwargs)
except Exception as e:
raise forms.ValidationError('Something went wrong.')