【问题标题】:how do i pre fill a form field with a models object in django我如何在 django 中使用模型对象预先填写表单字段
【发布时间】:2020-10-31 11:26:46
【问题描述】:

我有两页个人资料并添加注释。每当我单击任何用户配置文件上的添加注释时,我都想在添加注释表单中填写患者字段,我需要更改 url 路径吗?如果是,我如何从 url 中获取数据并将其填写到表单中。

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>

【问题讨论】:

  • user_id=id 中的id 来自哪里。由于那不是参数,它将使用id 内置函数,这将不起作用。
  • @WillemVanOnsem 该行无关紧要。我忘了摆脱它。
  • 但我说的不是editprofile,而是addnotes

标签: python django


【解决方案1】:

不清楚表单是否应该首先包含patient 的字段。如果 URL 是为特定患者构建的。

您应该以某种方式添加此值。例如在路径中:

urlpatterns = [
    # &hellip;
    path('addnotes/<int:pk>', addnotes, name='addnote'),
]

接下来,我们可以决定在表单中预填此字段,或者直接省略该字段。

选项 1:省略 patient 字段

所以在这种情况下,这意味着ModelForm 看起来像:

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

在这种情况下,您可以指定

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.instance.patient = profile
            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})

选项 2:在表格中预填

另一种方法是仍然允许在表单中修改它,但指定intial=… parameter [Django-doc]。在这种情况下,PatientNotesForm 保持不变,但我们传递了一个初始值。

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(initial={'patient': id})
    return render(request, 'core/addnotes.html', {'form': form})

【讨论】:

  • 我需要患者字段,以便我可以按用户过滤笔记(列出属于用户的笔记)。目前我使用了选项 2,但它没有保存它一直说无法分配“'navabe'”:“Note.patient”必须是“Profile”实例。 navabe 是用户名
  • @blockhead: 那是因为你使用了CharField,而不是ModelChoiceField
  • @blockhead: 如果你希望能够输入查询,你可以使用django-select2:django-select2.readthedocs.io/en/latest 作为小部件,但表单字段仍然是ModelChoiceField,因为那是ForeignKey 期望。
猜你喜欢
  • 1970-01-01
  • 2018-07-25
  • 2019-10-22
  • 2012-04-21
  • 2014-04-03
  • 2010-11-11
  • 1970-01-01
  • 2020-02-09
相关资源
最近更新 更多