Prefill modelform based on url

I’m struggling around Django form. I’m not really comfortable with this part of the framework.
Here is the case. I have a ModelForm containing a OneToOneField. I would like to prepopulated the ModelChoice Field with the object referenced in the URL. Ex: catalogue/location/add/7 to add a location to the product with pk=7
NB: if the PK is not included, the form is just not prefilled

models.py

class Product(models.Model):
   pass

class ProductLocation(geo_models.Model):
   product = geo_models.OneToOneField(Product, verbose_name=_('Product'), on_delete=geo_models.CASCADE, null=True,)
   geo_point = geo_models.PointField(verbose_name=_('Location'), blank=True)
   address = geo_models.CharField(verbose_name=_('Address'), max_length=255)

urls.py

urls += [
            re_path(r"^location/add/(?P<product_pk>d+)/$",
                 self.add_update_location.as_view(),
                 name='catalogue-product-location-add'),  # Prepopulate product ModelChoiceField

            path("location/add",
                 self.add_update_location.as_view(),
                 name='catalogue-location-create'  # Empty product ModelChoiceField
                 ),

            path("location/<int:pk>",
                 self.add_update_location.as_view(),
                 name='catalogue-location-update')  # Edit an existing Location
        ]

views.py

class LocationCreateUpdateView(generic.UpdateView):
    form_class = ProductLocationForm

    creating = True
    product = None

    def get_object(self, queryset=None):
        """
        Extend the role of get_object to retrieve the product specified in the url
        """
        self.creating = "pk" not in self.kwargs
        if self.creating:
            if self.kwargs.get("product_pk"):
                self.product = get_object_or_404(Product, pk=self.kwargs["product_pk"])
            return None
        else:
            return super().get_object(queryset)

# Try this way
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        if self.product and not self.request.POST.get('product'):
            kwargs["product"] = self.product
        return kwargs

# Or this way
    def get_initial(self):
        initial = super().get_initial()
        if self.product:
            initial["product"] = self.product
        return initial

forms.py


class ProductLocationForm(forms.ModelForm):
    def __init__(self, product=None, instance=None, *args, **kwargs):
        # I tried this
        if not instance and product:
            instance = ProductLocation(product=product)
        super().__init__(instance=instance, *args, **kwargs)

I tried to override get_initial() to pass the product to the form didn’t validate, ask to select a product in the list and moreover, it erase the inital value.

I also use get_form_kwargs() to pass the product to the form init function and try to :

  • attach the product to the ProductLocation instance
  • set inital data in the init
  • set self.fidels['product'].initial = product

Thanks for your help

PS : some references on SO

  • Pass initial value to a modelform in django
  • How to instantiate a Django ModelForm with pre-filled required fields?
  • Set initial value in django model form

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật