简体   繁体   中英

how do i pre fill a form field with a models object in django

i have two pages profile and add notes. i want to fill the patient field in the add notes form with the users first name whenever i click add notes on any users profile will i need to change the url path? if yes, how do i get the data from the url and fill it in the form.

urls.py

urlpatterns = [
    path('', dashboard, name='dashboard'),
    path('profile/', profile, name='profile'),
    path('profile/<str:slug>/<int:pk>', profile, name='profilepk'),
    path('edit_profile/<int:id>/', edit_profile, name='editprofile'),
    path('addnotes/', addnotes, name='addnote'),
  
]

views.py

def addnotes(request):
    profile = Profile.objects.get(user_id=id)
    form = PatientNotesForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect(f'/dashboard/profile/{user.profile.slug}/{user.pk}')

    return render(request, 'core/addnotes.html', {'form': form})

def profile(request, slug, pk):
    profil = Profile.objects.get(slug=slug)
    profile = Profile.objects.get(pk=pk)
    context = {'profile': profile, 'profil': profil}
    return render(request, 'dashboard/profile.html', context)

models.py

class Note(models.Model):
    illness = models.CharField(max_length=1000, blank=True)
    patient = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='patientnote', null=True)
    Doctor = models.CharField(max_length=100, blank=True)
    Description = models.CharField(max_length=10000, blank=True)
    created = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        return f"{self.illness}"

forms.py

class PatientNotesForm(ModelForm):
    illness = forms.CharField(max_length=100, help_text='First Name')
    patient = forms.CharField(max_length=100, help_text='Last Name')
    doctor = forms.CharField(max_length=100, help_text='address')
    description =  forms.CharField(max_length=100,widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['illness'].widget.attrs.update(
            {'placeholder': ('illness')})
        self.fields['doctor'].widget.attrs.update(
            {'placeholder': ("Doctor's name")})
        self.fields['patient'].widget.attrs.update(
            {'placeholder': ("Patient's name")})
        self.fields['description'].widget.attrs.update(
            {'placeholder': ("Description")})
        self.fields['illness'].widget.attrs.update({'class': 'log'})
        self.fields['doctor'].widget.attrs.update({'class': 'log'})
        self.fields['patient'].widget.attrs.update({'class': 'log'})
        self.fields['description'].widget.attrs.update({'class': 'textarea'})

    class Meta:
        model = Note
        fields = ('illness', 'patient', 'doctor', 'description')

addnotes.html

   <form method="post" class="fum"> {%csrf_token%}{{form.illness}}{{form.patient}}{{form.doctor}}{{form.description}}
            <li class="btnn "><button type="submit " class="conf ">Confirm</button></li>
        </form>

profile.html

     <ul class="main-menu">
            <li>
                <a href="#"><img class="nav-items" src="{% static 'images/home.svg'%}" alt=""><span>Home</span></a>
            </li>
            <li>
                <a href="#"><img class="nav-items" src="{% static 'images/male.svg'%}" alt=""><span>Patients</span></a>
            </li>
            <li>
                <a href="#"><img class="nav-items" src="{% static 'images/doctor.svg'%}" alt=""><span>Add notes</span> </a>
            </li>
            <li>
                <a href="#"><img class="nav-items" src="{% static 'images/lab.svg'%}" alt=""><span>Edit profile</span>
                </a>
            </li>
        </ul>
    </div>

It is not clear if the form should contain a field for patient in the first place. If the URL is constructed for a specific patient.

You should add this value somehow. For example in the path:

urlpatterns = [
    # &hellip;
    path('addnotes/', addnotes, name='addnote'),
]

Next we can decide to either prefill this in the form, or just omit the field.

Option 1: omit the patient field

So in that case it means that the ModelForm looks like:

class PatientNotesForm(ModelForm):
    # …
    
    class Meta:
        model = Note
        #                 no patient ↓
        fields = ('illness', 'doctor', 'description')

In that case you can spec

from django.shortcuts import get_object_or_404

def addnotes(request, id):
    profile = get_object_or_404(Profile.objects.get, user_id=id)
    if request.method == 'POST':    
        form = PatientNotesForm(request.POST)
        if form.is_valid():
            form
            form.save()
            return redirect(f'/dashboard/profile/{user.profile.slug}/{user.pk}')
    else:
        form = PatientNotesForm()
        form.instance.patient = profile
    return render(request, 'core/addnotes.html', {'form': form})

Option 2: Prefill it in the form

An alternative is to still allow to modify this in the form, but specify an intial=… parameter [Django-doc] . In that case the PatientNotesForm remains the same but we pass an initial value.

def addnotes(request, id):
    if request.method == 'POST':    
        form = PatientNotesForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect(f'/dashboard/profile/{user.profile.slug}/{user.pk}')
    else:
        form = PatientNotesForm()
    return render(request, 'core/addnotes.html', {'form': form})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM