我创建了一个表格来创建我的汽车经销商模型的实例。现在,我希望能够单击编辑图标,并转到带有预先填充有模型实例属性的表单的页面。
我还想知道是否需要创建单独的表单,视图和模板以进行创建和编辑,或者我是否可以某种方式重用它们?
models.py
class Dealer(models.Model):
name = models.CharField(max_length=50)
phone = models.CharField(max_length=50)
website = models.CharField(max_length=100)
address = models.CharField(max_length=100)
featured_image = models.ImageField(upload_to="dealers/")
def image_tag(self):
return mark_safe('<img src="%s" style="height: 300px; width: auto;"/>' % (self.featured_image.url))
image_tag.short_description = 'Image'
class Meta:
verbose_name_plural = "Dealers"
def __str__(self):
return self.name
views.py
def create_dealer_view(request):
if request.method == "POST":
form = CreateDealerForm(request.POST, request.FILES)
if form.is_valid():
dealer = form.save(commit=False)
dealer.save()
return redirect('main:homepage_view')
else:
form = CreateDealerForm
context = {
"title": "Create - Dealer",
"form": form,
}
return render(request=request, template_name="main/create/create_dealer.html", context=context)
forms.py
class CreateDealerForm(forms.ModelForm):
class Meta:
model = Dealer
fields = ('name', 'phone','website', 'address', 'featured_image',)
widgets = {
'name': forms.TextInput(attrs={'class': 'dealer-name-field', 'placeholder': 'Dealer name'}),
'phone': forms.TextInput(attrs={'class': 'dealer-phone-field', 'placeholder': 'Dealer phone'}),
'website': forms.TextInput(attrs={'class': 'dealer-website-field', 'placeholder': 'Dealer website'}),
'address': forms.TextInput(attrs={'class': 'dealer-address-field', 'placeholder': 'Dealer address'}),
}
答案 0 :(得分:3)
您只需要编写一个更新视图及其URL,就可以使用相同的表单和模板
def update_dealer_view(request, pk=none):
instance = get_object_or_404(Dealer, pk=pk)
form = CreateDealerForm(request.POST, request.FILES, , instance=instance)
if form.is_valid():
dealer = form.save(commit=False)
dealer.save()
return redirect('main:homepage_view')
context = {
"title": "Update - Dealer",
"form": form,
"instance=instance"
}
return render(request=request, template_name="main/create/create_dealer.html", context=context)
并为此视图创建一个网址
path('dealer/update/<int:pk>/', update_dealer_view, name='update_dealer),