如何实现基于UpdateView类的视图

时间:2017-08-01 16:22:56

标签: python django

我正在构建一个应用程序,企业可以使用大量信息上传本地商店。目前,有一个表格正在运行,但我想实施UpdateView,以便企业随时更新他们的信息。

这是我的model.py:

class Business(models.Model):
owner = models.OneToOneField(User, null=False)
name = models.CharField(max_length=75)
logo = models.ImageField(null=True, blank=False, upload_to=upload_location)
players = models.CharField(max_length=4, choices=PLAYERS_CHOICES, default='2-4')
average_price = models.IntegerField()
number_games = models.IntegerField()
city = models.CharField(max_length=25, choices=CITY_CHOICES)
address = models.CharField(max_length=200)
website = models.CharField(max_length=300)
description = models.TextField(max_length=1000, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
slug = models.SlugField(null=True, blank=True)

请注意,我使用的是OneToOneField,因为一个所有者在网站中只能拥有一个商家。

我的views.py表单:

class BusinessCreateView(LoginRequiredMixin, CreateView):
form_class = BusinessCreateForm
login_url = '/login/'
template_name = 'business/form.html'
success_url = '/'

def form_valid(self, form):
    instance = form.save(commit=False)
    instance.owner = self.request.user
    return super(BusinessCreateView, self).form_valid(form)

这是我的forms.py:

class BusinessCreateForm(forms.ModelForm):
class Meta:
    model = Business
    fields = [
        'name',
        'logo',
        'players',
        'average_price',
        'number_games',
        'city',
        'address',
        'website',
        'description',
    ]

我一直在检查文档,但我还没有能够实现UpdateView。

我怎么能这样做?

提前非常感谢你!

更新

我已经在我的views.py中尝试了一个查询集,但它无效:

def get_queryset(self):
    return Business.objects.filter(user=self.request.user)

1 个答案:

答案 0 :(得分:0)

您还没有真正解释实施UpdateView的难度。也许您需要的提示是覆盖get_object以返回要更新的业务:

from django.shortcuts import get_objet_or_404

class BusinessUpdateView(LoginRequiredMixin, UpdateView):
    form_class = BusinessUpdateForm
    template_name = 'business/form.html'

    def get_object(self):
        return get_object_or_404(Business, owner=self.request.user)