Search code examples
pythondjangodjango-modelsdjango-formsdjango-generic-views

Django ModelForm Foreign Key Dropdown passes __str__ but stores fkey_id


There are two models and I would like to store a column field from one model to another model.

models.py:

class Company(models.Model):
   name = ...
 def __str__(self):
         return self.name

class Rate(models.Model):
   company = models.ForeignKey(Company)
   currency = ...
   name = ...

 def __str__(self):
         return self.name + " " + self.currency

class Client(models.Model):
   name = ...
   currency = ....
   company = models.ForeignKey(Company)
   base_rate = models.ForeignKey(Rate)

 def __str__(self):
         return self.name

forms.py:

class ClientForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = (
               "name",                
               "company",
               "base_rate", )

views.py:

class ClientCreateView(FormView):
    template_name = "client/new_package.html"
    form_class = ClientForm
    success_url = reverse_lazy("home")

    def form_valid(self, form):
        detail = form.save(commit=False)
        base_rate_id = form.cleaned_data['base_rate']
        detail.currency = Rate.objects.values_list("currency", flat=True).filter(base_rate_id=base_rate_id)
        detail.save()

        if detail is not None:
            return redirect('display_package' , detail.id)
        else:
            return super(ClientCreateView, self).form_valid(form)

Basically, I want selected currency value to be saved in my client model from Rate model. Any help will be appreciated as from cleaned data I am getting str returned value instead of selected option id value (i.e. str from client model ).


Solution

  • I'm not really sure why you want that. But more to the point, why you are doing it with filter and values_list? You need to get the value and store it.

    detail = form.save(commit=False)
    detail.currency = form.cleaned_data['base_rate'].currency
    detail.save()