ubuntuuber
ubuntuuber

Reputation: 732

How to auto-populate database field using data from other fields in the same model

I have a model called Coverletter with 4 fields: company, role, job_posting, content.

I am trying to use the data from the first 3 fields to populate data in the 4th field.

Right now, the user inputs values for 3 fields in a form: (company, role, job_posting) using a class based view CreateView.

class CoverletterCreateView(LoginRequiredMixin, CreateView):
model = Coverletter
fields = ['company', 'role', 'job_posting']
template_name = 'coverletter/coverletter_create_form.html'

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


def get_success_url(self):
    return reverse('coverletter:coverletter-create-content',
                   kwargs={'pk': self.object.pk,}
                   )

The user is then redirected to another class based view UpdateView via get_success_url, where the first three fields are showing with populated values.

class CoverletterCreateContentView(LoginRequiredMixin, UpdateView):
model = Coverletter
fields = ['company', 'role', 'job_posting', 'content']
template_name = 'coverletter/coverletter_create_content_form.html'

Right now the 4th field (content) is blank, but I am trying to populate the content field when the user submits the data from the first CreateView.

The data is an html string that would look something like this:

<p>Dear {{ company }} I am excited to be applying for the {{ role }} role.</p>

I am very new to Django and web development, and am struggling to understand how to do this. I am unsure where in the app to put this logic. Any guidance is appreciated!

Upvotes: 0

Views: 119

Answers (1)

user1600649
user1600649

Reputation:

First off, get intimate with ccbv.

Second, you're using a UpdateView, which - as you can determine above - implements, among others:

  • get_initial()
  • get_object()

Inside, get_initial(), you can get the model instance you're trying to update using get_object(). Once you have the instance, you can compose your string. Then add it to the initial data.

Result:


class CoverletterCreateContentView(LoginRequiredMixin, UpdateView):
    ... # fields
    def get_initial(self):
        if not hasattr(self, 'object'):
            self.object = self.get_object(self.get_queryset())
        initial = super().get_initial()
        opening_sentence = (
           f"Dear {self.object.company} I am excited to"
           f" be applying for the {self.object.role} role."
        )
        initial['content'] = opening_sentence  # initial[field_name] (dict)
        return initial

Upvotes: 1

Related Questions