I have a modelForm where I overwritte the init method to provide a predefined value from a FK. However when validating the form with the method is_valid() it fails as it says "Palabras" already exists but is not taking in consideration the FK "fk_funcion" as both are PK.
Models.py
class Palabras(models.Model):
fk_funcion = models.ForeignKey(Funcion, related_name='funcion', on_delete=models.CASCADE)
palabra = models.CharField(max_length=30, unique=True)
porcentaje = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)])
class Meta:
unique_together = ("fk_funcion", "palabra"),
def __str__(self):
return self.palabra
Forms.py
class PalabraForm(forms.ModelForm):
class Meta:
model = Palabras
fields = ('palabra','porcentaje', "fk_funcion")
def __init__(self, *args, **kwargs):
fk_funcion = kwargs.pop('fk_funcion','')
super(PalabraForm, self).__init__(*args, **kwargs)
self.fields['fk_funcion']=forms.ModelChoiceField(queryset=Funcion.objects.filter(id=fk_funcion))
Views.py
def create_palabra(request, pk_funcion):
data = dict()
if request.method == 'POST':
form = PalabraForm(request.POST,fk_funcion=pk_funcion,,initial={'fk_funcion':pk_funcion}) #I have tried with and without the initial value
if form.is_valid():
#Some action
What do I have to modify in order to make the form to validate both "palabra" and "fk_funcion" in the modelForm.
Thanks
You've marked palabra
as unique=True
. If you only want it to be unique together with the fk_function
, then remove that and rely on the unique_together
constraint.
(Also it doesn't make sense for fk_function
to be both a parameter to the form and a field on that form. You should probably remove it from the list of fields.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.