Home > Back-end >  How to get the current object in UpdateView?
How to get the current object in UpdateView?

Time:11-10

To update the data in the table, I use the class o inherited from UpdateView, the fields are automatically filled from the database, but can I somehow in my class get the data from the user_guid field?

Here is my form and class code:

class CampaignEditor(UpdateView):
    model = Campaigns
    template_name = 'mailsinfo/add_campaign.html'
    form_class = CampaignsForm

    def get_context_data(self):
        context = super().get_context_data()
        data = list(Emails.objects.values()) # you may want to further filter for update purposes
        data = MailsTableWithoutPass(data)
        context['data'] = data
        return context
class CampaignsForm(ModelForm):
    class Meta:
        model = Campaigns
        fields = ['name', 'subject', 'body', 'user_guid']

        widgets = {
            'name': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Name'
            }),
            'subject': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'Subject'
            }),
            'body': Textarea(attrs={
                'class': 'form-control',
                'placeholder': 'Body'
            }),
            'user_guid': TextInput(attrs={
                'class': 'form-control',
                'placeholder': 'User GuID'
            }),
        }

CodePudding user response:

You can use self.object.user_guid to get the data of user_guid field so:

class CampaignEditor(UpdateView):
    model = Campaigns
    template_name = 'mailsinfo/add_campaign.html'
    form_class = CampaignsForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        data = list(Emails.objects.values()) # you may want to further filter for update purposes
        data = MailsTableWithoutPass(data)
        context['data'] = data
        context['user_guid_field'] = self.object.user_guid
        return context
  • Related