I'd like to enter the contents of the model in two classes on one page

Asked 2 years ago, Updated 2 years ago, 74 views

I'm a beginner who just started studying janggo. How can I save the entire model contents as shown below by entering it into a form on one page (HTML)? Class view is being used.

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Entry(models.Model):
    headline = models.CharField(max_length=255)
    body_text = models.TextField()

    def __str__(self):
        return self.headline

Content _____________________

django python

2022-09-22 21:42

1 Answers

create and receive input coming in there the model form save it on the table.

forms.Prepare a py like this.

from django import forms

class AuthorEntryForm(forms.Form):
    name = forms.CharField(label='name', max_length=30)
    email = forms.EmailField(label='email')
    headline = forms.CharField(label='headline', max_length=30)
    body_text = forms.CharField(label='body_text', max_length=100)

views.py separates POST requests and GETs and processes them as follows.

def forms_test(request):
    # For POST
    if request.method == 'POST':
        form = AuthorEntryForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            headline = form.cleaned_data['headline']
            body_text = form.cleaned_data['body_text']
            print(name,email,headline,body_text)
            #The part where you store the information that this brings
            Author(name=name,email=email).save() 
            Entry(headline=headline, body_text=body_text).save() 
            return HttpResponse("Success")
    # If Get, draw a form
    else:
        form = AuthorEntryForm()

    return render(request, 'form_test.html', {'form': form})

In form_test.html, put the following information. This is a code that draws the form received from the render.

<form action="/forms_test/" method="post">
    {% {% csrf_token %}
    {{ {{ form }}
    <input type="submit" value="Submit" />
</form>


2022-09-22 21:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.