如何在另一个类中获取一个类对象的 id 并存储在数据库中 - Django

Posted

技术标签:

【中文标题】如何在另一个类中获取一个类对象的 id 并存储在数据库中 - Django【英文标题】:how can i get id of one class object, in another class and store in the database - Django 【发布时间】:2021-02-20 10:25:18 【问题描述】:

** urls.py 文件 **

from django.urls import path
from main import views

app_name = 'main'

urlpatterns = [

    path('', views.home, name='home'),
    path('submit/', views.submit, name='submit'),
    path('error-log/', views.error_log, name='error_log'),

]

**views.py 文件**

from django.shortcuts import render, get_object_or_404, redirect
import socket
from main.models import Paragraphs, Store_user_para
from main.forms import Store_user_para_forms
import random


global paragraph

def home(request):
    ''' to get the ip of user'''
    hostname = socket.gethostname()
    ip_address = socket.gethostbyname(hostname)

    '''code to pass the pre defined paragraphs to the user '''
    paragraphs = Paragraphs.objects.filter(active=True)

    ''' code to generate random paragraph '''
    len_paragraphs = len(paragraphs)
    number = random.randint(1, len_paragraphs-1)
    paragraph = get_object_or_404(Paragraphs, id=number)
    form = Store_user_para_forms()
    return render(request, 'main/home.html', 'ip_address':ip_address, 'paragraph':paragraph, 'form':form)

def submit(request):
    if request.method == "POST":     
        try:
            global paragraph
            form = Store_user_para_forms(request.POST)
            data = form.save(commit=False)
            data.paragraph_Id = request.POST.get('hidden_value', '')
            data.user = request.user
            data.save()
            return redirect('main:submit')
        except (ValueError):
            form = Store_user_para_forms(request.POST)
            print(form)
            return render(request, 'main/submit.html', 'error':'Bad data passed in. Try again.')
    else:
        data = Store_user_para.objects.filter()
        return render(request, 'main/submit.html', 'data':data)


def error_log(request ):
    return render(request, 'main/error_log.html')

** model.py 文件 **

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Paragraphs(models.Model):
     ''' this class will store the pre defined paragraphs in backend '''
    objects = models.Manager()
    paragraph = models.TextField(blank=False, null=False)
    created = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)

    class Meta:
        verbose_name = 'Paragraph'
        verbose_name_plural = 'Paragraphs'
    
    def __str__(self):
        return self.paragraph.split()[0]+ ' ' + self.paragraph.split()[1] + '...'

class Store_user_para(models.Model): 
    ''' this class will store the users entered paragraph ''' 
    objects = models.Manager()
    paragraph_Id = models.ForeignKey('Paragraphs', on_delete=models.SET_NULL, null=True)
    user_paragraph = models.TextField(null=False, blank=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    submitted = models.DateTimeField(auto_now_add=True)
    Errors = models.IntegerField(null=True)

    def __str__(self):
        return self.user.username

** form.py 文件 **

from django import forms
from main.models import Store_user_para

class Store_user_para_forms(forms.ModelForm):
    class Meta:
        model = Store_user_para
        ''' field to display on form '''
        fields = [ 'user_paragraph']

** Home.html 文件,当我点击提交按钮时,我不仅想将用户编写的段落传递给 store_user_para 模型,还希望将存储的段落 id 传递给 store_user_para 模型**

% extends 'main/base.html' %
% load static %

% block title % | Home | % endblock %

% block content %


<form action="% url 'main:submit' %" method="POST">
    % csrf_token %
    <div class="unselectable" style="margin: 50px; margin-bottom: 20px;">
        <div style="border: .1em solid green;">
            <div style="font-size:20px; padding: 20px;">

                <!--  this will bring the paragraphs from backend -->    
                 paragraph.paragraph 
                <input type="hidden" name='hidden_value' value=" paragraph.paragraph " >
            </div>
        </div>
    </div>

   <div style="margin: 50px; margin-top:15px ;">
      <label for="id_user_paragraph"> </label>
       <textarea name="user_paragraph" cols="40" rows="12" required="" id="id_user_paragraph"
        placeholder="Start writing here" style="width: 100%; height:300px; font-size: 20px; padding: 5px; border: solid green 1px; "></textarea>
        <button id="submit" type="submit" style="display: none;">Complete</button>
        </div>


    </form>

    <div class="text-center">
        <p class="btn btn-info disabled">Your IP:  ip_address </p>
    </div>

    <div class="row">
        <div class="col-12 col-md-6 col-lg-6 col-sm-6 ">
            <form action="">
            <div class="text-right">
                <button type="button" style="-ms-text-underline-position: none;" class="btn btn-outline-success" onclick="$('#submit').click()">
                   submit and check 
                </button> 
            </div>
            </form>
        </div>

        <div class="col-12 col-md-6 col-lg-6 col-sm-6 ">

            <div class="text-left">
                <a href="% url 'main:error_log' %" style="-ms-text-underline-position: none;" class="btn btn-outline-danger mr-3">
                    view error log 
                 </a> 
            </div>

        </div>
    </div>


    <div style="margin-left: 10px; margin-top: 10px;">
        <h4>work and payment details </h4>
    </div>

    <div style="margin-top: 10px; margin-left: 10px; margin-bottom: 50px;">
        <h6>Target : n Paragraphs</h6>
        <h6>Time : 00:00 - 00:00 </h6>
    </div>

% endblock %

** 这是后端的输出 ** image of admin site **如何在这里提交预定义的段落**

【问题讨论】:

【参考方案1】:

你需要将id添加到forms.py中的字段列表中

fields = ('id', 'user_paragraph')

那么你可以和段落一样的方式返回它

【讨论】:

先生,请您再解释一下,我尝试了您所说的,但仍然收到“错误数据传入”,非常感谢您的帮助,我真的很感谢您 您可以添加另一个带有 id 值的输入:

以上是关于如何在另一个类中获取一个类对象的 id 并存储在数据库中 - Django的主要内容,如果未能解决你的问题,请参考以下文章

如何在另一个类中调用一个类中的函数对象?

如何在另一个插入存储过程期间调用一个插入存储过程并获取其返回的ID?

如何在另一个类中调用列表对象

如何在另一个类中调用类类型的向量?

如何获取已存储在另一个模型中的名称 ID,并使用名称 ID 在 laravel 的数据透视表数据库中存储值?

c# Unity - 如何在另一个类中调用结构对象数组