加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Django框架:对象不显示在特定pk的网页上

发布时间:2020-12-20 11:04:41 所属栏目:Python 来源:网络整理
导读:我正在尝试使用Django Framework将特定项目从数据库导入到网页中.当我提取所有记录但是当我尝试通过主键选择单个记录时,我已设法执行此操作. 这是显示页面和数据库字段的html: {% extends "base.html" %}{% load static %}{% block content %} br h3Adheren
我正在尝试使用Django Framework将特定项目从数据库导入到网页中.当我提取所有记录但是当我尝试通过主键选择单个记录时,我已设法执行此操作.

这是显示页面和数据库字段的html:

{% extends "base.html" %}
{% load static %}
{% block content %}
    <br>
    <h3>Adherence agreement for authorized access to data and biospecimens in the RD-Connect Genome-Phenome Analysis Platform (RDC-GPAP)<sup><a href="#fn1" id="ref1">1</a></sup><small class="text-muted"> to be used together with the <span class="text-info">Code of Conduct</span> for integrated user access to RDC-GPAP for health-related information and human biological samples.</small></h3>
    <hr>

    {% for item in items %}

    <p>I,<span class="text-success">{{ item.first_name }} {{ item.last_name }}</span>,acting on behalf of the <span class="text-success">{{ item.department }}</span>,and holding the position <span class="text-success">{{ item.job_title }}</span>,herewith declare:</p>
    <ol type="1">
        <li>I have the authority to represent and engage the <span class="text-success">{{ item.department }}</span> for the purpose of the project,<span class="text-success">[project name]</span>. For this project we ask for access to data and/or biospecimens in accordance with our research interests as set out in our completed <span class="text-info">User Verification Form</span> (previous page).</li>
        <br>
        <li>The <span class="text-success">{{ item.department }}</span> agrees to fully endorse and adhere to the <span class="text-info">Code of Conduct</span> for integrated user access to the RDC-GPAP for health-related information and human biological samples,version 2,3rd November 2017. It shall apply to all data and biospecimen processing activities carried out within the project <span class="text-success">[project name]</span>. The personal data protection framework is thus in part formalized through this Code.</li>
        <br>
        <li>The <span class="text-success">{{ item.department }}</span> will ensure the implementation of all measures required by the provisions of this Code.</li>
        <br>
        <li>The <span class="text-success">{{ item.department }}</span> will ensure compliance with this Code by all staff and personnel working within the project on behalf of the <span class="text-success">{{ item.department }}</span>.</li>
        <br>
        <li>In addition to the rules laid out by the Code,the following project specific rules shall apply:</li>
        <br>
        <ol type="a">
            <li>There will be no attempt to try to identify or contact data or donor subjects.</li>
            <li>Accessed data and biospecimens will not be redistributed.</li>
            <li>Access codes and user logins are specific to the identified user and are strictly non-transferable.</li>
            <li>Accessed datasets will be destroyed once they are no longer used.</li>
            <li>Biospecimens will be handled in accordance with specifications in a Material Transfer Agreement.</li>
            <li>Publications using any form of data accessed through the RDC-GPAP will contain an acknowledgment and a reference of the RDC-GPAP as appropriate.
            Where a publication makes use of individual-level datasets and enriched phenotypic data,authors should consider whether the intellectual contribution of the original contributors of the datasets qualifies for authorship positions in line with standard publication practice.</li>
            <li>Results of analyses of accessed data and biospecimens will be returned to the platform. Published work will also be sent to RD-Connect.</li>
            <li>In case of misconduct access to the platform will be withdrawn.</li>
        </ol>
    </ol>
    <hr>
    <p>Signed on behalf of the <span class="text-success">{{ item.department }}</span> on <span class="text-success">{% now "jS F Y" %}</span> by <span class="text-success">{{ item.first_name }} {{ item.last_name }}</span>:</p>

    {% endfor %}

    <br>
    <br>
    <p>…………………………………………………</p>
    <p>Signature</p>
    <hr>
    <sup id="fn1">1. This adherence agreement is based on the Personal Data Directive,Directive95/46/EC,implying that all personal data shall be handled in accordance with Secrecy law.<a href="#ref1" title="Jump back to footnote 1 in the text.">?</a></sup>
    <br>
    <br>
</div>
<div class="container">
    <input type="button" class="save btn btn-success btn-lg" onclick="printDiv('printable')" value="Print" />
    <br>
</div>
{% endblock %}

urls.py:

urlpatterns = [
    path('adherence_agreement/',views.adherence_agreement,name='adherence_agreement'),]

然后,当我在views.py中使用以下代码时,我通过使用{%for items in items%}迭代数据并选择单个字段来获取网页中的相关字段. {{item.first_name}}:

def adherence_agreement(request):
    try:
        data = UserInfo.objects.all()
    except UserInfo.DoesNotExist:
        raise Http404('User does not exist')
    return render(
        request,'adherence_agreement.html',{
            'items': data
        }
    )

但是,如果我想通过将urlpattern更改为路径来引入特定记录的信息(‘adherence_agreement /< int:id>‘…并且像这样更改views.py:

def adherence_agreement(request,id):
    try:
        data = UserInfo.objects.get(pk=id)
    except UserInfo.DoesNotExist:
        raise Http404('User does not exist')
    datum = data._meta.get_fields()
    return render(
        request,{
            'items': datum
        }
    )

然后网页加载(没有错误),但没有任何字段被拉过…

仅供参考,UserInfo的models.py:

class UserInfo(models.Model):
    first_name              = models.CharField(max_length=20,verbose_name='First Name',help_text='Your given name. *REQUIRED**')
    last_name               = models.CharField(max_length=100,verbose_name='Last Name',help_text='Your family name. *REQUIRED*.')
    office_address          = models.CharField(max_length=200,verbose_name='Office address',help_text='The address where you can be reached rather than your institution’s head office. *REQUIRED*')
    research_interest       = models.CharField(max_length=1000,verbose_name='Short summary of your research interests',help_text='In one or two sentences please describe your research interests and how access to the RD-Connect platform is relevant for you. *REQUIRED*' )
    institution             = models.CharField(max_length=50,verbose_name='Name of institution',help_text='The institution (university,hospital etc.) with which you have your primary affiliation. *REQUIRED*')
    institute_website       = models.URLField(max_length=100,null=True,blank=True,default="",verbose_name='Institute website',help_text='Your institution’s main website.')
    job_title               = models.CharField(max_length=100,verbose_name='Position within institution',help_text='Your job title within your institution.')
    email                   = models.EmailField(max_length=100,verbose_name='Institutional email address',help_text='Use of an institutional email address issued by your place of work is part of our validation procedure. If you do not have one please contact help@rd-connect.eu to explain your circumstances')
    department              = models.CharField(max_length=50,verbose_name='Name of your department',help_text='Your department within your institution (e.g. Neurology,Genetics,etc.')
    orcid_profile           = models.URLField(max_length=100,verbose_name='ORCID profile',help_text='If you have an ORCID profile,please paste the link here.')
    linkedin_profile        = models.URLField(max_length=100,verbose_name='LinkedIn profile',help_text='If you have a LinkedIn profile,please paste the link here.')
    publications            = models.URLField(max_length=100,verbose_name='Three recent publications',help_text='Please paste links to three recent representative publications of which you are an author (link to the article on the journal website or to the PubMed page).')
    researchgate_profile    = models.URLField(max_length=100,verbose_name='ResearchGate profile',help_text='If you have a ResearchGate profile,please paste the link here.')
    departmentweb_profile   = models.URLField(max_length=100,verbose_name='Department web profile',help_text='If you or your group has a profile on your university or departmental website please paste the link here.')
    adherence_agreement     = models.FileField(verbose_name='Adherence Agreement',help_text='I confirm that I have read the Code of Conduct and signed the Adherence Agreement and agree to abide by the rules therein. In confirmation of this I upload a signed copy of the Adherence Agreement here.')
    photo_scan              = models.FileField(verbose_name='Photo ID scan',help_text = 'As part of our verification procedure we require a recognised form of ID such as your passport,national ID card or driving licence. Please scan,save and upload here as a JPEG or PDF.')
    confirm_listing         = models.BooleanField(verbose_name='I agree that my name can be listed as a user of the platform on the RD-Connect official website (https://rd-connect.eu)',help_text='All users will be stored in internal RD-Connect records for internal purposes and may be presented in reports to the European Commission as our funding organisation. We would also like to list users in a dedicated section of the platform website. If you do not wish your name to be listed publicly,do not tick the box.')
    newsletter_subscribed   = models.BooleanField(verbose_name='I would like to be subscribed to the RD-Connect Newsletter',help_text='We would like to register all users for our monthly newsletter in order to keep you updated about news of interest to rare disease researchers and platform updates. If you do not wish to receive the newsletter,please tick the box.')
    created                 = models.BooleanField(default=False)
    date                    = models.DateTimeField(auto_now_add=True,verbose_name='Date')

    def __str__(self):
        """
        String for representing the Model object
        """
        return self.last_name

    def get_absolute_url(self):
        """
        Returns the url to access a detail record for this user
        """
        return reverse('user-detail',args=[str(self.id)])

解决方法

我不明白为什么你在视图中做datum = data._meta.get_fields().这将获得您根本不想要的类级别字段对象.不要那样做;将对象直接传递给模板.

您还需要删除模板中的循环并直接将对象作为项目传递.

作为进一步优化,您可以使用get_object_or_404而不是捕获DoesNotExist异常并手动引发404.

def adherence_agreement(request,id):
    item = get_object_or_404(UserInfo,pk=id)
    return render(request,{'item': item})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读