我正在学习Django并创建一个生物序列数据库,包含使用模型的数百个序列,模型有两个字段,“Seq_ID”和“序列”。我正在尝试编写一个视图,以便它可以在主页上呈现所有序列的ID,并单击特定的ID,它将显示相关的序列。
更新了观看次数和网址:
型号:
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class FastaSeq(models.Model):
Seq_ID = models.CharField(max_length=20)
Sequense = models.TextField()
def __unicode__(self):
return self.Seq_ID
查看:
from django.shortcuts import render
from django.conf import settings
from .models import FastaSeq
def home(request):
data = FastaSeq.objects.all()
context = {'data':data}
template = 'home.html'
return render(request, template, context)
def single(request,Seq_ID):
data = FastaSeq.objects.get(Seq_ID=Seq_ID)
return render(request,template,{'data':data})
网址:
from django.conf.urls import url
from django.contrib import admin
from new_app import views as new_app_view
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^home/', new_app_view.home, name='home'),
url(r'^User/(?P<Seq_ID>\d+)/$', new_app_view.single, name='single'),
]
Example_Data:
Seq_ID:
>01_sequence
Sequence:
LARALLLCAAVVCGAANPCCSHPCQNRGVCMSVGFDQYKCDCTRTGFYGENCTTPEFLTRIKLLLKPTP
DTVHYILTHFKGVWNIVNKISFLRNMIMRYVLTSRSHLIESPPTYNVHYSYKSWEAFSNLSYYTRALPPV
PDDCPTPMGVKGRKELPDSKEVVKKVLLRRKFIPDPQGTNLMFAFFAQHFTHQFFKTDIERGPAFTKGKN
HGVDLSHVYGESLERQHNRRLFKDGKMKYQMINGEMYPPTVKDTQVEMIYPPHIPEHLKFAVGQEVFGLV
使用这个模型我已经在数据库中添加了大约50个Demo序列,但是无法编写一个可以在主页上显示序列ID并且点击ID的视图将使您获得序列数据。
已更新:
显示一些错误:
No return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/home/jai/.virtualenvs/env1/local/lib/python2.7/site-packages/django/urls/resolvers.py", line 389, in _reverse_with_prefix
(lookup_view_s, args, kwargs, len(patterns), patterns)
NoReverseMatch: Reverse for 'single' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['User/(?P<Seq_ID>\\d+)/$']
[06/Jul/2017 06:46:13] "GET /home/ HTTP/1.1" 500 133824
答案 0 :(得分:2)
from .models import FastaSeq
def home(request):
data = FastaSeq.objects.all()
context = {'data':data}
template = 'home.html'
return render(request, template, context)
模板中的
{% for d in data %}
<a href="{% url 'single' d.Seq_ID %}">{{ d.Seq_ID }}</a>
{% endfor %}
在urls.py中
url(r'^User/(?P<Seq_ID>[\w{}.-]{1,40})/$', 'views.single', name='single'),
创建另一个视图
def single(request,Seq_ID):
data = FastaSeq.objects.get(Seq_ID=Seq_ID)
return render(request,template,{'data':data})
在single
功能模板`
{{ data.Seq_ID }}
{{ data.Sequense }}
答案 1 :(得分:1)
将seq_id
添加到上下文中:
context = {'seq_ids': FastaSeq.objects.all()}
然后在模板中迭代它们。
{% for id in seq_ids %}
<your html here>
{% endfor %}