问题
I'm trying to get my table to load, but am getting this error, most likely because my primary key is a uuid.
Here is my url paths.
path('results/', views.results, name='results'),
path('results/<uuid:pk>/', views.genre_book, name='books_genre_table'),
Here is my views.py If there is one observation, we load the price table. If not, then we load a table with service descriptions. The user can then pick the service they are most interested and click through to the price table for that service. This is not working. The first view "results" works, but the second view book_genre does not.
def results(request):
query_string = ''
found_entries = None
if ('s' in request.GET) and request.GET['s'].strip():
query_string = request.GET['s']
entry_query = get_query(query_string,['service__desc_us', 'com_desc'])
_objs = Price.objects.filter(entry_query).values('service__join').distinct()
num_obj = Price.objects.filter(entry_query).values('service__join').distinct().count()
if num_obj == 1:
Price_objs = Price.objects.filter(entry_query).order_by("price_offer")
table = PriceTable(Price_objs)
RequestConfig(request).configure(table)
if num_obj > 1:
model = Service
entry_query = get_query(query_string,['desc_us', 'price__com_desc'])
serv_obj = Service.objects.filter(entry_query).distinct()
table = ServiceTable(serv_obj)
RequestConfig(request).configure(table)
return render(request, 'results.html', {'table': table})
def genre_book(request, pk):
serv_obj = Service.objects.get(pk=pk)
price_obj = Price.objects.filter(service=serv_obj).values("join")
table = PriceTable(price_obj)
RequestConfig(request).configure(table)
return render(request, 'results.html', {'table': table})
Here is my tables.py file
class PriceTable(tables.Table):
class Meta:
model = Price
template_name = 'django_tables2/bootstrap4.html'
sequence = ('service', 'price_offer')
exclude = ('priceid', 'com_desc', "comments")
attrs = {"class": "darkblue"}
class ServiceTable(tables.Table):
desc_us = tables.LinkColumn('books_genre_table', args=[A('pk')])
class Meta:
model = Service
...
Here is my model for service:
class Service(models.Model):
serviceid = models.UUIDField(default=uuid.uuid4, primary_key=True,
help_text='Unique ID for this particular service in database', editable=False)
desc_us = models.TextField(blank=True)
join = models.IntegerField(default= 10000) #foreign key with price model
class Meta:
ordering = ['serviceid']
def __str__(self):
"""String for representing the Model object."""
return self.desc_us
class Price(models.Model):
priceid = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular service in database')
com_desc = models.CharField(max_length = 200, blank = True, null = True)
service = models.ForeignKey("Service", on_delete=models.SET_NULL, null=True)
price_offer = models.DecimalField(max_digits=8, decimal_places=2, blank=True)
class Meta:
ordering =['service']
def __str__(self):
return f'{self.service.desc_us} ({self.price_offer})'
FULL ERROR printout
Error during template rendering
In template
projects/hosproject/venv/lib/python3.7/site-packages/django_tables2/templates/django_tables2/bootstrap4.html, error at line 26
badly formed hexadecimal UUID string
16 {{ column.header }}
17 {% endif %}
18 </th>
19 {% endfor %}
20 </tr>
21 </thead>
22 {% endif %}
23 {% endblock table.thead %}
24 {% block table.tbody %}
25 <tbody {{ table.attrs.tbody.as_html }}>
#below row highlighted
26 {% for row in table.paginated_rows %}
27 {% block table.tbody.row %}
28 <tr scope="row" {{ row.attrs.as_html }}>
29 {% for column, cell in row.items %}
30 <td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
31 {% endfor %}
32 </tr>
33 {% endblock table.tbody.row %}
34 {% empty %}
35 {% if table.empty_text %}
36 {% block table.tbody.empty_text %}
Here is the beginning of the traceback:
File "projects/hosproject/venv/lib/python3.7/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "projects/hosproject/venv/lib/python3.7/site-packages/django/template/defaulttags.py" in render
166. len_values = len(values)
File "/projects/hosproject/venv/lib/python3.7/site-packages/django_tables2/rows.py" in __len__
335. length = len(self.data)
File "/projects/hosproject/venv/lib/python3.7/site-packages/django/db/models/query.py" in __len__
250. self._fetch_all()
File "projects/hosproject/venv/lib/python3.7/site-packages/django/db/models/query.py" in _fetch_all
1186. self._result_cache = list(self._iterable_class(self))
File "/projects/hosproject/venv/lib/python3.7/site-packages/django/db/models/query.py" in __iter__
63. for row in compiler.results_iter(results):
File "/projects/hosproject/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py" in apply_converters
1009. value = converter(value, expression, connection)
File "/projects/hosproject/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/operations.py" in convert_uuidfield_value
263. value = uuid.UUID(value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/uuid.py" in __init__
160. raise ValueError('badly formed hexadecimal UUID string')
Exception Type: ValueError at /results/
Exception Value: badly formed hexadecimal UUID string
Here is what pulls up this error in the source code, uuid.py
if hex is not None:
hex = hex.replace('urn:', '').replace('uuid:', '')
hex = hex.strip('{}').replace('-', '')
if len(hex) != 32:
raise ValueError('badly formed hexadecimal UUID string')
int = int_(hex, 16)
来源:https://stackoverflow.com/questions/55130764/badly-formed-hexadecimal-uuid-error-string-for-a-uuid-primary-key