faijan memon
faijan memon

Reputation: 203

how can i get id of one class object, in another class and store in the database - Django

** urls.py file **

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 file **

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 file **

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 file **

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 file , when I hit the submit button, I want not only to pass the user written pargraph but also the stored paragraph id to the store_user_para model **

{% 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 %}

** this is the output in backend ** image of admin site **how to submit the pre defined pargraph here **

Upvotes: 1

Views: 431

Answers (1)

Ahmed Eid
Ahmed Eid

Reputation: 144

you need to add the id to the fields list in forms.py

fields = ('id', 'user_paragraph')

then you can return it the same way as the paragraph

Upvotes: 1

Related Questions