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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…