Django CreateView customise form default field based on url parameter

我怕爱的太早我们不能终老 提交于 2019-12-10 09:13:16

问题


file: Capacity/models.py

class Env(models.Model):
    name = models.CharField(max_length=50)
    def get_absolute_url(self):
            return reverse('index')

class Envhosts(models.Model):
    env =  models.ForeignKey(Env)
    hostname = models.CharField(max_length=50)
    count = models.IntegerField()

    class Meta:
        unique_together = ("env","hostname")

    def get_absolute_url(self):
        return reverse('index')

file: Capacity/views.py

 class EnvhostsCreate(CreateView):
    model = Capacity.models.Envhosts
    fields=['env','hostname','count']
    template_name_suffix = '_create_form'

file Capacity/urls.py:

urlpatterns = patterns(........ url(r'^createhosts/(?P<envid>\d+)/$',EnvhostsCreate.as_view(),name='envhosts_create'))

So now, when i open this form: /Capacity/createhosts/3/ (where 3 is my env id) It shows an option of env objects as a drop down list based on the number of object of Env. But i want it to take the env on its own based on the env id ('3' in this case)

I know i have to override some method in class EnvhostsCreate(CreateView). But i m unable to figure out which method and how to take the env based on the part after /createhosts/


回答1:


You can use the pattern described in the documentation for adding request.user - it's the same principle. Remove env from the fields list, then define form_valid():

class EnvhostsCreate(CreateView):
    model = Capacity.models.Envhosts
    fields = ['hostname', 'count']
    template_name_suffix = '_create_form'

    def form_valid(self, form):
        form.instance.env = Envhosts.objects.get(pk=self.kwargs['envid'])
        return super(EnvhostsCreate, self).form_valid(form)


来源:https://stackoverflow.com/questions/20421017/django-createview-customise-form-default-field-based-on-url-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!