Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

python - django ModelForm extra field

i will like to have extra field in modelForm. From this extra field i will like to pass the value to field in model when save. this is example what i want to get

will like to generate name in random name field, and save to database as name

models.py

from django.db import models


class Test2App(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

forms.py

from django import forms
from .models import test2App


class TestForm(forms.ModelForm):
    class Meta:
        model = Test2App
        fields = ['name']

Views.py

def add_name(request):
    if request.method == 'POST':
        form = TestForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('test_name')
    else:
        form = TestForm()

    return render(request, 'test/add.html', {'form': form})

html

  <form method="post">
    {% csrf_token %}
    <label for="name">Random Name</label>
    <button>Generate</button>
                    <input id="name" name="name_test">
    {{ form}}

    <input type="submit" value="Submit">
</form>
question from:https://stackoverflow.com/questions/66055767/django-modelform-extra-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
def add_name(request):
if request.method == 'POST':
    form = TestForm(request.POST)
    name1 = request.POST.get('name_test')

    print(name1)
    if form.is_valid():
        form.instance.name = name1
        form.save()
        return redirect('test_name')
else:
    form = TestForm()

return render(request, 'test/add.html', {'form': form})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...