0

I have a Django form that is is generated from a model

model.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    telephone = models.CharField(max_length=15, blank=True)
    email_address = models.CharField(max_length=30, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)

enter image description here

The user Dropbox is populated (automatically) from the users

How can I pre-populate the form from the Profile model when I select user?

Psionman
  • 3,084
  • 1
  • 32
  • 65
  • Can you give more details about what you're trying to do? You could mean selecting a user and the other fields populating based on some user or other model, the other case I can think of is that you're trying to update a profile and the fields aren't populating. – schillingt Mar 04 '20 at 16:51
  • @schillingt Question updated. Is that clearer? – Psionman Mar 04 '20 at 16:56
  • So you're updating existing profiles? The only way is to make an ajax request each time the user changes the value of the dropdown to fetch the profile of the corresponding user and if it exists, update the fields in javascript. Look up ajax + django. – dirkgroten Mar 04 '20 at 16:59

1 Answers1

0

You can do this either by submitting the form whenever the user field is changed or you can use Ajax to do this asynchronously. Both require a bit of JavaScript code. The first option requires that you use a modelform. The steps are pretty standard.

  1. Submit the user data
  2. Find the user in your database
  3. Load the user instance into your modelform
  4. Pass your form to the context variable

For Ajax, search for tutorials on Ajax and see this answer on SO.

In your HTML:

<select name="user_selector" id="userDropDown" class=" whatever-custom-css-class" autofocus onChange="this.form.submit();">

Then, inside your get requet, you can

user_name = self.request.GET.get('user_selector', None)
if user_name:
    try:
        selected_user = User.objects.get(username = user_name)

    except ObjectDoesNotExist:
        # No such user. 
        selected_user = None

if selected_user:
    contact_form = ContactForm(instance = selected_user)
    ...
    context.update({'form': contact_form})
    return render(request, self.template_name, context)
EarlyCoder
  • 1,213
  • 2
  • 18
  • 42