【发布时间】:2018-12-28 03:02:45
【问题描述】:
models.py
from django.db import models
from django.urls import reverse
# Create your models here.
class WellInfo(models.Model):
api = models.CharField(max_length=100, primary_key=True)
well_name = models.CharField(max_length=100)
status = models.CharField(max_length=100)
phase = models.CharField(max_length=100)
region = models.CharField(max_length=100)
start_date = models.CharField(max_length=100)
last_updates = models.CharField(max_length=100)
def __str__(self):
return self.well_name
views.py
class ContextualMainView(TemplateView):
template_name = 'contextual_main.html'
class WellList_ListView(ListView):
template_name = 'well_list.html'
context_object_name = 'well_info'
model = models.WellInfo
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# get string representation of field names in list
context['fields'] = [field.name for field in models.WellInfo._meta.get_fields()]
# nested list that has all objects' all attribute values
context['well_info'] = [[getattr(instance, field) for field in context['fields']] for instance in context['well_info']]
return context
html
<thead>
<tr>
{% for field in fields %}
<th>{{ field }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for well in well_info %}
<tr>
{% for value in well %}
<td><a href="{% url 'eric_base:contextual' api=well.api %}">{{ value }}</a></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
app/urls.py
from django.urls import re_path, include
from django.contrib.auth import views as auth_views
from eric_base import views as base_views
app_name = 'eric_base'
urlpatterns = [
re_path(r'^(?P<api>\d+)/$', base_views.ContextualMainView.as_view(), name='contextual'),
]
在我的models.py 中,我将api 设置为主键,并希望使用api 作为唯一的url 标识符,并将其附加到url 的末尾,如下所示:
http://127.0.0.1:8000/well_list/contextual/api_number_1
http://127.0.0.1:8000/well_list/contextual/api_number_2
http://127.0.0.1:8000/well_list/contextual/api_number_3
我想我在views.py 或models.py 中遗漏了一些东西,但我不知道它是什么。我该如何解决这个问题?
【问题讨论】:
标签: django django-models django-views django-urls