首页 > 解决方案 > 如何在 django 模型和模板中设置和使用 id 字段

问题描述

我需要能够访问我的模型的自增整数字段并在我的模板中使用它。有没有办法做到这一点?

我的代码接受来自用户的投诉,因此对于每个投诉,我需要将 id 从 0、1、2、3、4 等递增,然后我需要在模板中访问这些以便能够相应地使用它

模型.py:

class Complaint(models.Model):
   user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True)
   id = models.AutoField(blank=False, primary_key=True)
   reportnumber = models.CharField(max_length=500 ,null = True, blank= False)
   eventdate = models.DateField(null=True, blank=False)
   event_type = models.CharField(max_length=300, null=True, blank=True)
   device_problem = models.CharField(max_length=300, null=True, blank=True)
   manufacturer = models.CharField(max_length=300, null=True, blank=True)
   product_code = models.CharField(max_length=300, null=True, blank=True)
   brand_name = models.CharField(max_length = 300, null=True, blank=True)
   exemption = models.CharField(max_length=300, null=True, blank=True)
   patient_problem = models.CharField(max_length=500, null=True, blank=True)
   event_text = models.TextField(null=True, blank= True)
   document = models.FileField(upload_to='static/documents', blank=True, null=True)

   def __str__(self):
       return self.reportnumber

表格.py:

class DateInput(forms.DateInput):
   input_type = 'date'

class ComplaintForm(ModelForm):
   class Meta:
       model = Complaint
       fields = '__all__'
       widgets = {
           'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}),
           'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}),
           'eventdate': DateInput(),
           'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}),
           'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}),
           'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}),
           'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}),
           'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}),
           'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}),
           'patient_problem': forms.TextInput(attrs={'placeholder': 'Enter Patient Problem'}),
       } 
    
   def clean(self):
       cleaned_data = super(ComplaintForm, self).clean()
       reportnumber = cleaned_data.get('reportnumber')
       event_text = cleaned_data.get('event_text')
       if not reportnumber and not event_text:
           raise forms.ValidationError('You have to write something!')
       return cleaned_data

模板:

{%for c in complaint %}
        <a href="new.html" style="color:black;">
            <div class="container comp-con-{{c.id}}"> -> I need to access the id here for css purpose
                <p style="color: #D37A19; margin-left: -130px; margin-top: -5px;">Report number:</p>
                <p class="history-level-1">{{c.reportnumber}}</p>
                <p class="comp-title-1">{{c.event_type}}</p>
                <p class="comp-sub-1">{{c.event_text}}</p>
            </div>
        </a> {%endfor%}
    </div>

视图.py:

def History(request):
  complaint_data = Complaint.objects.filter(user=request.user) 
  context = { 'complaint':complaint_data }
  return render(request, 'myHistory.html', context)

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


您不需要在模板使用中的示例中添加字段forloop.counterforloop.counter0

{%for c in complaint %}
        <a href="new.html" style="color:black;">
            <div class="container comp-con-{{ forloop.counter0 }}">
                <p style="color: #D37A19; margin-left: -130px; margin-top: -5px;">Report number:</p>
                <p class="history-level-1">{{c.reportnumber}}</p>
                <p class="comp-title-1">{{c.event_type}}</p>
                <p class="comp-sub-1">{{c.event_text}}</p>
            </div>
        </a> {%endfor%}
    </div>

推荐阅读