TKngDisuke
@TKngDisuke (大輔 徳永)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

[Django]DetailViewでの固有id取得、idに紐づけられているデータを取りpythonプログラムとして作成したい。

解決したいこと

DetailViewでのページ内の固有id取得、またそのidに紐づけられているtextデータを読み取りそれをpythonプログラムとして新規ファイルで作成したいです。

[現在の状況]
DjangoでTextにグラフのデータのプログラムを入れ、それを実行するアプリを開発中です。
そこでDetailViewでのデータ取得、実行が分からず、どのサイトを調べてもなかなか良い解決策が浮かびませんでした。
解決方法を教えて下さい。

参考サイト、こちらの第4回まで作成し、そこから変更を加えて開発中です。
https://rightcode.co.jp/blog/become-engineer/django-diary-app-make-list-detail-screen
viewでのファイル新規作成の参考サイトです。うまくいきませんでした。
https://blog.codecamp.jp/python-file-data
[環境]
anaconda22.9.0 Python 3.9.12 Django3.1.2 SQlite 3.38.2

変更するべき箇所

views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from django.views.generic import CreateView
from .forms import DiaryForm
from django.views.generic import ListView
from django.urls import reverse_lazy
from .models import Diary
from .application import sample 
from django.views.generic import DetailView
class IndexView(TemplateView):
    template_name = 'index.html'
    def get_context_data(self, **kwargs): # 追加
        x = sample.sum()
        context = super().get_context_data(**kwargs)
        context['sum'] = x
        return context
class DiaryCreateView(CreateView):
    template_name = 'diary_create.html'
    form_class = DiaryForm
    success_url = reverse_lazy('diary:diary_create_complete')
class DiaryListView(ListView):
    template_name = 'diary_list.html'
    model = Diary
class DiaryCreateCompleteView(TemplateView):
    template_name = 'diary_create_complete.html'


class DiaryDetailView(DetailView):
    template_name = 'diary_detail.html'
    model = Diary
    ctx = {}
    ctx = Diary.objects.get(pk=pk)#Detail viewにあるpk値と一致しているデータを取り出す
    b=ctx[id]
    f = open('b.py','w')
    a=ctx[text]
    f.write(a)
    f.close()
#ここの上の部分

エラー内容

  File "/Users/tokut/Desktop/a/djangotutorial/mydiaryproject/diary/views.py", line 32, in <module>
    class DiaryDetailView(DetailView):
  File "/Users/tokut/Desktop/a/djangotutorial/mydiaryproject/diary/views.py", line 36, in DiaryDetailView
    ctx = Diary.objects.get(pk=pk)#Detail viewにあるpk値と一致しているデータを取り出す
NameError: name 'pk' is not defined

IndexViewは、Homeとしての機能に追加でapplication内に入れた実行プログラムが作動するか確認をしています。
スクリーンショット 2022-12-07 3.33.53.png
合計7.0 がapplicationで行われた実行結果を表示しています。

これをDetailView内でもuuidに紐づけられるtextデータを用いて計算をしてほしいのですが、textデータに保存されている内容をpythonプログラムとして作成して実行することができず、その方法を知りたいです。
現在はresultのデータ(初期値0)を表示させていますが、将来的には実行したデータをresultに入れ表示させたいと考えています。

スクリーンショット 2022-12-07 3.42.17.png

ソースコード全容はこちら

models.py
from django.db import models
from django.utils import timezone
import uuid
class Diary(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    date = models.DateField(verbose_name='日付', default=timezone.now)
    title = models.CharField(verbose_name='タイトル', max_length=40)
    text = models.TextField(verbose_name='本文')
    created_at = models.DateTimeField(verbose_name='作成日時', default=timezone.now)
    updated_at = models.DateTimeField(verbose_name='編集日時', blank=True, null=True)
    result =models.PositiveIntegerField(verbose_name='計算結果',default=0)
urls.py
from django.urls import path
from . import views

app_name = 'diary'
urlpatterns = [
    path('index/', views.IndexView.as_view(), name='index'),
    path('diary/create/', views.DiaryCreateView.as_view(), name='diary_create'),
    path('diary/create/complete/', views.DiaryCreateCompleteView.as_view(), name='diary_create_complete'),
    path('diary/list/', views.DiaryListView.as_view(), name='diary_list'), # 追記
    path('diary/detail/<uuid:pk>/', views.DiaryDetailView.as_view(), name='diary_detail'),
]

diary_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% for diary in diary_list %}
<p>
    {{ diary.date }}
    <a href="{% url 'diary:diary_detail' diary.pk %}">{{ diary.title }}</a>
</p>
{% endfor %}
<a href="{% url 'diary:index' %}">戻る</a>
</body>
</html>
diary_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>実行日  {{ diary.date }}</p>
<p>タイトル  {{ diary.title }}</p>
<p>本文  [{{ diary.text }}]</p>
<p>結果A  {{ diary.result }}</p>
<p>結果B  {{ diary.result }}</p>
<p>結果C  {{ diary.result }}</p>
<a href="{% url 'diary:index' %}">戻る</a>
</body>
</html>
forms.py
from django import forms
from .models import Diary
class DiaryForm(forms.ModelForm):
    class Meta:
        model = Diary
        fields = ('date', 'title', 'text',)

application内の実行sample

sample.py
import numpy as np
import networkx as nx
import scipy as sp

G1 = nx.Graph()
G1.add_nodes_from([("userinfo", {"attribute":"entity"}),
("store", {"attribute":"entity"}),
("product", {"attribute":"entity"}),
("Order_document", {"attribute":"entity"}),
("cart", {"attribute":"entity"}),
("Owner", {"attribute":"human"}),
("login1", {"attribute":"boundary"}),
("menu1", {"attribute":"boundary"}),
("Cart_confirm", {"attribute":"boundary"}),                                                                                                                
("loginCO", {"attribute":"control"}),
("store_product_CRUD", {"attribute":"control"}),
("order_RECEIVE", {"attribute":"control"})])

G1.add_edges_from([("Owner", "login1"),("Owner", "Cart_confirm"),
("Owner","menu1"), ("loginCO", "login1"),
("loginCO","menu1"), ("menu1", "store_product_CRUD"),("Cart_confirm", "store_product_CRUD"),
("Cart_confirm", "order_RECEIVE"),
("loginCO","userinfo"), 
("store_product_CRUD","store"), ("store_product_CRUD", "product"),
("order_RECEIVE","Order_document")]) 

G2 = nx.Graph()
G2.add_nodes_from([("Owner", {"attribute":"human"}),
("login1", {"attribute":"boundary"}),
("menu1", {"attribute":"boundary"}),                                                                                                              
("loginCO", {"attribute":"control"}),
("artist_workCRUD", {"attribute":"control"}),
("userinfo", {"attribute":"entity"}),
("artist", {"attribute":"entity"}),
("work", {"attribute":"entity"}),
("playlist2", {"attribute":"entity"})])

G2.add_edges_from([("Owner", "login1"),("Owner", "menu1"),
("loginCO", "login1"),
("loginCO","menu1"), ("menu1", "artist_workCRUD"),
("artist_workCRUD", "artist"),("artist_workCRUD", "work"),
("loginCO","userinfo")]) 
import numpy as np
import networkx as nx
import scipy as sp

G1 = nx.Graph()
G1.add_nodes_from([("userinfo", {"attribute":"entity"}),
("store", {"attribute":"entity"}),
("product", {"attribute":"entity"}),
("Order_document", {"attribute":"entity"}),
("cart", {"attribute":"entity"}),
("Owner", {"attribute":"human"}),
("login1", {"attribute":"boundary"}),
("menu1", {"attribute":"boundary"}),
("Cart_confirm", {"attribute":"boundary"}),                                                                                                                
("loginCO", {"attribute":"control"}),
("store_product_CRUD", {"attribute":"control"}),
("order_RECEIVE", {"attribute":"control"})])

G1.add_edges_from([("Owner", "login1"),("Owner", "Cart_confirm"),
("Owner","menu1"), ("loginCO", "login1"),
("loginCO","menu1"), ("menu1", "store_product_CRUD"),("Cart_confirm", "store_product_CRUD"),
("Cart_confirm", "order_RECEIVE"),
("loginCO","userinfo"), 
("store_product_CRUD","store"), ("store_product_CRUD", "product"),
("order_RECEIVE","Order_document")]) 

G2 = nx.Graph()
G2.add_nodes_from([("Owner", {"attribute":"human"}),
("login1", {"attribute":"boundary"}),
("menu1", {"attribute":"boundary"}),                                                                                                              
("loginCO", {"attribute":"control"}),
("artist_workCRUD", {"attribute":"control"}),
("userinfo", {"attribute":"entity"}),
("artist", {"attribute":"entity"}),
("work", {"attribute":"entity"}),
("playlist2", {"attribute":"entity"})])

G2.add_edges_from([("Owner", "login1"),("Owner", "menu1"),
("loginCO", "login1"),
("loginCO","menu1"), ("menu1", "artist_workCRUD"),
("artist_workCRUD", "artist"),("artist_workCRUD", "work"),
("loginCO","userinfo")]) 
def sum():
  x=	nx.graph_edit_distance(G1,G2)
  return x

if __name__ == "__main__":
	sum()

追記:試したところ、クラスベースではなく、関数ベースでの記述へ(理由はpk値が取れないから)
参考サイトhttps://itc.tokyo/django/objects-all-get/

views.py
def DiaryDetailView(request, pk):
    template_name = 'diary_detail.html'
    model = Diary
    ctx = {}
    ctx = Diary.objects.get(pk=pk)#Detail viewにあるpk値と一致しているデータを取り出す
    f = open('nx.py','w')#nx.pyファイルを作成
    f.write(ctx.text)#ここでなぜかbの文字列が入ってしまう
    f.close()
    context = {'ctx': ctx}

    f = open('nx.py','a')#nx.pyファイル
    b='あああ    いいい'
    f.write(b)#ここでなぜかbの文字列が入ってしまう
    f.close()
    
    return render(request, template_name, context)
urls.py
from django.urls import path
from . import views

app_name = 'diary'
urlpatterns = [
    path('index/', views.IndexView.as_view(), name='index'),
    path('diary/create/', views.DiaryCreateView.as_view(), name='diary_create'),
    path('diary/create/complete/', views.DiaryCreateCompleteView.as_view(), name='diary_create_complete'),
    path('diary/list/', views.DiaryListView.as_view(), name='diary_list'), # 追記
  #  path('diary/detail/<uuid:pk>/', views.DiaryDetailView.as_view(), name='diary_detail'),
  path('diary/detail/<uuid:pk>/', views.DiaryDetailView, name='diary_detail'),
]

エラー内容は無くなりました。

うまくいきました。
→今度はファイルが作成された場所が
スクリーンショット 2022-12-08 16.51.59.png

プロジェクト直下のせいでdiary の applicationで実行フォルダを読み込むつもりでしたが、読み込むことができませんでした。
ファイルを移動させるか、そのまま読み込めるようにしたいです。

0

1Answer

Comments

  1. @TKngDisuke

    Questioner

    こちらがエラーになります。正直、viewsのdetailでのプログラミングは自身で見ても自信がないので新たな解決策を現在、探しています。

    '''
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
    File "/Users/tokut/opt/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
    File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
    File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
    File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
    File "<frozen importlib._bootstrap_external>", line 850, in exec_module
    File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
    File "/Users/tokut/Desktop/a/djangotutorial/mydiaryproject/diary/urls.py", line 2, in <module>
    from . import views
    File "/Users/tokut/Desktop/a/djangotutorial/mydiaryproject/diary/views.py", line 34
    f = open('[uuid].py','w')
    ^
    IndentationError: unindent does not match any outer indentation level
    '''

  2. IndentationError はインデントミスじゃないでしょうか?
  3. @TKngDisuke

    Questioner

    そのようですね。変更しました。
    views.py
    class DiaryDetailView(DetailView):
    template_name = 'diary_detail.html'
    model = Diary
    ctx = {}
    ctx = Diary.objects.all()
    b=ctx[id]
    f = open('b.py','w')
    a=ctx[text]
    f.write(a)
    f.close()

    これだとエラーは

    Watching for file changes with StatReloader
    Performing system checks...

    Exception in thread django-main-thread:
    Traceback (most recent call last):
    File "/Users/tokut/opt/anaconda3/lib/python3.9/threading.py", line 973, in _bootstrap_inner
    self.run()
    File "/Users/tokut/opt/anaconda3/lib/python3.9/threading.py", line 910, in run
    self._target(*self._args, **self._kwargs)
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check
    all_issues = checks.run_checks(
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/core/checks/registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 408, in check
    for pattern in self.url_patterns:
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
    File "/Users/tokut/opt/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
    File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
    File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
    File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
    File "<frozen importlib._bootstrap_external>", line 850, in exec_module
    File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
    File "/Users/tokut/Desktop/a/djangotutorial/mydiaryproject/config/urls.py", line 21, in <module>
    path('', include('diary.urls')), # 追加:includeメソッドでurl設定を追加
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/urls/conf.py", line 34, in include
    urlconf_module = import_module(urlconf_module)
    File "/Users/tokut/opt/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
    File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
    File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
    File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
    File "<frozen importlib._bootstrap_external>", line 850, in exec_module
    File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
    File "/Users/tokut/Desktop/a/djangotutorial/mydiaryproject/diary/urls.py", line 2, in <module>
    from . import views
    File "/Users/tokut/Desktop/a/djangotutorial/mydiaryproject/diary/views.py", line 31, in <module>
    class DiaryDetailView(DetailView):
    File "/Users/tokut/Desktop/a/djangotutorial/mydiaryproject/diary/views.py", line 36, in DiaryDetailView
    b=ctx[id]
    File "/Users/tokut/Desktop/a/djangotutorial/.djangoenv/lib/python3.9/site-packages/django/db/models/query.py", line 297, in __getitem__
    raise TypeError(
    TypeError: QuerySet indices must be integers or slices, not builtin_function_or_method.

Your answer might help someone💌