我度过了可怕的时光,找到了正确的方法来初始化 TemplateHTMLRenderer ,以渲染用于创建对象的表单。我的API非常适合发布(DRF可浏览API表单),但这不是前端解决方案。
我可以使用文档和模板包https://www.django-rest-framework.org/topics/html-and-forms/#rendering-forms创建一个详细信息页面。文档非常清楚如何创建UPDATE表单。
但是我无法终生初始化相同的表单来进行初始创建。
当具有自动生成的表单功能时,我不想手动编写表单来与API交互以创建对象...但是我完全不知所措。
从views.py工作更新视图:
class LicensedSoftwareDetail(APIView):
model = LicensedSoftware
renderer_classes = [TemplateHTMLRenderer]
template_name = 'licsoftware-detail.html'
def get(self, request, pk):
if pk:
licensedsoftware = get_object_or_404(LicensedSoftware, pk=pk)
serializer = LicensedSoftwareSerializer(licensedsoftware)
return Response({'serializer': serializer, 'licensedsoftware': licensedsoftware})
else:
serializer = LicensedSoftwareSerializer()
return Response({'serializer': serializer})
def post(self, request, pk):
if pk:
licensedsoftware = get_object_or_404(LicensedSoftware, pk=pk)
serializer = LicensedSoftwareSerializer(licensedsoftware, data=request.data)
if not serializer.is_valid():
return Response({'serializer': serializer, 'licensedsoftware': licensedsoftware})
serializer.save()
else:
serializer = LicensedSoftwareSerializer(data=request.data)
serializer.save()
return redirect('../../licsoftware/')
这是具有自定义更新和创建方法的嵌套(OneToOne)序列化程序。
来自serializers.py:
class SoftwareSerializer(WritableNestedModelSerializer):
class Meta:
model = Software
fields = '__all__'
class LicensedSoftwareSerializer(WritableNestedModelSerializer):
software = SoftwareSerializer()
available = serializers.SerializerMethodField()
class Meta:
model = LicensedSoftware
fields = '__all__'
read_only_fields = ('available',)
def get_available(self, obj):
return int(obj.numpurchased) - obj.software.assignees.count()
def update(self, instance, validated_data):
software_data = validated_data.pop('software')
software = instance.software
for attr, value in software_data.items():
if attr == 'assignees':
instance.software.assignees.set(value)
else:
setattr(software, attr, value)
software.save()
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
return instance
def create(self, instance, validated_data):
software_data = validated_data.pop('software')
software = instance.software
for attr, value in software_data.items():
if attr == 'assignees':
instance.software.assignees.set(value)
else:
setattr(software, attr, value)
software.save()
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
return instance
我有一个引用TemplateHTMLRenderer表单的模板,当它可以调用PK时,它非常适合更新。但是,我无法创建将拉动表单进行创建/发布的视图或URL。
型号:
class Software (models.Model):
brand = models.CharField(max_length=50, blank=True, null=False)
title = models.CharField(max_length=50, blank=True, null=False, verbose_name="Software Title")
version = models.CharField(max_length=50, blank=True, null=False)
website = models.CharField(max_length=100, blank=True, null=False)
active = models.BooleanField()
notes = models.CharField(max_length=1000, blank=True, null=True)
assignees = models.ManyToManyField(User, related_name='software_assigned', blank=True, verbose_name="Installed Users:")
def __str__(self):
return "{0} {1} Version {2}".format(self.brand, self.title, str(self.version))
class LicensedSoftware(models.Model):
software = models.OneToOneField(Software, primary_key=True, on_delete=models.CASCADE)
vehicle = models.CharField(max_length=50, blank=True, null=False, verbose_name="Contract/Purchase Vehicle")
vendor = models.CharField(max_length=50, blank=True, null=False)
licensekey = models.CharField(max_length=50, blank=True, null=False)
subscription = models.BooleanField()
term = models.CharField(max_length=50, blank=True, null=False)
renewaldate = models.DateField(blank=True, null=True, verbose_name="Renew By")
supportincluded = models.BooleanField(verbose_name="Support Included")
numpurchased = models.IntegerField(blank=True, null=False, verbose_name="Licenses Purchased")
其他视图不起作用并且不包含PK:
class LicensedSoftwareList(APIView):
queryset = LicensedSoftware.objects.all()
serializer_class = LicensedSoftwareSerializer
renderer_classes = [TemplateHTMLRenderer]
template_name = 'licsoftware-detail.html'
def get(self, request, format=None):
licsoftware = LicensedSoftware.objects.all()
serializer = LicensedSoftwareSerializer(licsoftware)
return Response({'result': serializer.data})
def post(self, request, format=None):
serializer = LicensedSoftwareSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
模板:
{% extends 'base.html' %}
{% load rest_framework %}
{% block content %}
<h1>Licensed Software - {{ licensedsoftware.software.brand }} {{ licensedsoftware.software.title }} {{ licensedsoftware.software.version }}</h1>
<form class="form-horizontal" method="post" novalidate>
{% csrf_token %}
{% render_form serializer template_pack='rest_framework/horizontal'%}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit!</button>
</div>
</div>
</form>
{% endblock %}
URL:
urlpatterns = [
path('', views.index, name='index'),
path('inventory/', views.inventory, name='inventory'),
path('schema/', schema_view),
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
path('inventory/mobile-detail/<int:pk>/', views.MobileDetail.as_view()),
path('inventory/licsoftware-detail/<int:pk>/', views.LicensedSoftwareDetail.as_view()),
path('inventory/licsoftware-detail/', views.LicensedSoftwareList.as_view()),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('docs/', include_docs_urls(title='API Documentation')),
path('profiles/', views.ProfileList.as_view()),
path('profile-detail/<int:pk>/', views.ProfileDetail.as_view()),
path('inventory/licsoftware/', licensedsoftware_view, name='licensed_table'),
path('inventory/mobile/', mobile_view, name='mobile_table'),
API要求工作。可浏览的API将允许创建/发布。 路径('inventory / licsoftware-detail //',views.LicensedSoftwareDetail.as_view()),有效 path('inventory / licsoftware-detail /',views.LicensedSoftwareList.as_view()),给出错误:
尝试获取序列化程序software
上字段LicensedSoftwareSerializer
的值时, Got AttributeError。
序列化程序字段的名称可能不正确,并且与QuerySet
实例上的任何属性或键都不匹配。
原始异常文本为:'QuerySet'对象没有属性'software'。
答案 0 :(得分:1)
好的,以我理解您的问题的方式,您希望DRF自动生成用于创建和更新许可软件的表单。因此,我尝试这样做,但与您使用的方式略有不同,即我使用ModelViewSet代替了APIView,并且更改了两个序列化器的create函数。
Serializers.py
class SoftwareSerializer(serializers.ModelSerializer):
class Meta:
model = Software
fields = '__all__'
def create(self, validated_data):
assignees = validated_data.pop('assignees')
software = Software.objects.create(**validated_data)
for user in assignees:
user = User.objects.get(id=user.id)
software.assignees.add(user)
return software
class LicensedSoftwareSerializer(serializers.ModelSerializer):
software = SoftwareSerializer()
available = serializers.SerializerMethodField()
class Meta:
model = LicensedSoftware
fields = '__all__'
read_only_fields = ('available',)
def get_available(self, obj):
return int(obj.numpurchased) - obj.software.assignees.count()
def update(self, instance, validated_data):
software_data = validated_data.pop('software')
software = instance.software
for attr, value in software_data.items():
if attr == 'assignees':
instance.software.assignees.set(value)
else:
setattr(software, attr, value)
software.save()
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
return instance
def create(self, validated_data):
software_data = validated_data.pop('software')
assignee = software_data.pop("assignees")
user_list = []
for user in assignee:
user_list.append(user.id)
software_data.update({'assignees': user_list})
software_serializer = SoftwareSerializer(data=software_data)
software_serializer.is_valid()
software = software_serializer.save()
validated_data.update({"software": software})
ls = LicensedSoftware.objects.create(**validated_data)
return ls
views.py
class LicensedSoftwareDetail(ModelViewSet):
queryset = LicensedSoftware.objects.all()
serializer_class = LicensedSoftwareSerializer
如果要在此处进行任何更改,请随时提及。另外,作为建议,我会说创建一个单独的端点来创建软件,然后将PrimaryKeyRelated字段或任何其他此类字段用于LicensedSoftwareSerializer,因为当您使用嵌套序列化程序时,情况变得很糟。
和平
编辑:
好的,没有pk的视图对于生成创建模板来说是有点错误的。 这就是我的工作方式:
class LicensedSoftwareCreate(APIView):
queryset = LicensedSoftware.objects.all()
serializer_class = LicensedSoftwareSerializer
renderer_classes = [TemplateHTMLRenderer]
template_name = 'licsoftware-detail.html'
def get(self, request, format=None):
serializer = LicensedSoftwareSerializer()
return Response({'serializer': serializer})
def post(self, request, format=None):
serializer = LicensedSoftwareSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
希望有帮助。