Testing forms and widgets - Python - django

I trying to test the Django forms and widgets but it is returning false instead of true. The test looks right but not sure.I have added the test form, interest form and player class
class TestForm(TestCase):
def test_player_interests_fail(self):
form = PlayerInterestsForm(data={'interests': 'sport'})
self.assertEqual(form.is_valid(), True)
class PlayerInterestsForm(forms.ModelForm):
class Meta:
model = Player
fields = ('interests', )
widgets = {'interests': forms.CheckboxSelectMultiple}
class Player(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
quizzes = models.ManyToManyField(Quiz, through='TakenQuiz')
tournaments = models.ManyToManyField(Tournament, through='TakenTournament')
interests = models.ManyToManyField(Subject, related_name='interested_player')
def get_unanswered_questions(self, quiz):
answered_questions = self.quiz_answers\
.filter(answer__question__quiz=quiz)\
.values_list('answer__question__pk', flat=True)
questions = quiz.questions.exclude(pk__in=answered_questions).order_by('text')
return questions
def get_unanswered_tournament_questions(self, tournament):
answered_questions = self.tournament_answers\
.filter(answer__question__tournament=tournament)\
.values_list('answer__question__pk', flat=True)
questions = tournament.questions.exclude(pk__in=answered_questions).order_by('text')
return questions
def __str__(self):
return self.user.username
class Meta:
verbose_name_plural = "Player"

There are two issues with your code:
Player.interests is a ManyToManyField. That means the form expects the data to be a list of primary keys for the selected Subjects - passing a string value will not work. You have to pass integer IDs of Subject objects.
A CheckboxSelectMultiple allows multiple objects to be selected, which means you have to pass a list, not a single value.
So you need to do something like this:
def test_player_interests_fail(self):
# If you haven't already, you need to create a Subject
# I don't know how your Subject model is defined, but something like this
s = Subject.objects.create(name='Sport')
form = PlayerInterestsForm(data={'interests': [s.pk]})
self.assertEqual(form.is_valid(), True)

Related

Django field choices not properly updating

I have two models, one that loads the other model it's titles in a choice field dynamically. I fixed it so far that if I add a new object to the model which the titles are used from by updating the choice list in the init method, the choice list gets updated immediately. However when I decide to choose it as option and save it I get: Select a valid choice. example is not one of the available choices. When I restart the server it does work, what I did:
model:
class Assessment(models.Model):
title = models.CharField(max_length=200)
SPECIFIC_REQUIREMENTS_CHOICES = ()
SPECIFIC_REQUIREMENTS_CHOICES_LIST = []
for sRequirement in SpecificRequirements.objects.all():
SPECIFIC_REQUIREMENTS_CHOICES_LIST.append((sRequirement.title, sRequirement.title))
SPECIFIC_REQUIREMENTS_CHOICES = SPECIFIC_REQUIREMENTS_CHOICES_LIST
sRequirementChoice = models.CharField(max_length=200, choices=SPECIFIC_REQUIREMENTS_CHOICES,
default='')
forms:
class AssessmentForm(forms.ModelForm):
class Meta:
model = Assessment
fields = ['title', 'sRequirementChoice']
def __init__(self, *args, **kwargs):
super(AssessmentForm, self).__init__(*args, **kwargs)
SPECIFIC_REQUIREMENTS_CHOICES_LIST = []
for sRequirement in SpecificRequirements.objects.all():
SPECIFIC_REQUIREMENTS_CHOICES_LIST.append((sRequirement.title, sRequirement.title))
SPECIFIC_REQUIREMENTS_CHOICES = SPECIFIC_REQUIREMENTS_CHOICES_LIST
self.fields['sRequirementChoice'].choices = SPECIFIC_REQUIREMENTS_CHOICES
That's not how Model choices work. You are not supposed to populate choices dynamically in models.
You should consider using a ForeignKey relation with SpecificRequirements in your model.

Filter queryset between two or more models for search form in django

Im building a search form in django, Im doing it with filter querysets, this form is like a "advance search form", I mean, form could has more than two inputs, but problem is that each input corresponding of a field of different model, I have this and works fine if the form only has one input for one model:
def post(self,request,*args,**kwargs):
buscar_predio = request.POST['nombre_predio']
query1 = InfoPredioGeneral.objects.filter(nombre_predio__iexact=buscar_predio)
if query1:
ctx = {'predio':query1}
return render(request,'resultados_busqueda.html',ctx)
else:
return render(request,'resultados_busqueda.html')
If I have this models:
class InfoPredioGeneral(models.Model):
nombre_predio = models.CharField(max_length=30)
class Propietario(models.Model):
predio = models.ForeignKey(InfoPredioGeneral,blank=True,null=True,related_name='predio_propietario+')
tipo_identificacion = models.ForeignKey(TipoIdentificacion,related_name='tipo identificacion+',blank=True,null=True)
In the post method how can I search in the same form a InfoPredioGeneral and Propietario? For example filter where nombre_predio is exact to "predio proof" and where tipo_identificacion is exacto to "123"? As you can see Propietario has a ForeignKey to InfoPredioGeneral
you are looking for a many-to-one relationship
https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_one/
you already set the related_name to "predio_propietario+" and with the '+' at the end this means there is no backwards relation to this model
there is you example:
queryset = Propietario.objects.filter(predio__nombre_predio__iexact=request.POST['nombre_predio'])
Extra:
class C(models.Model):
c_text = models.CharField(max_length=100)
class B(models.Model):
b_text = models.CharField(max_length=100)
class A(models.Model):
b = models.ForeignKey(B)
c = models.ForeignKey(C)
queryset will look like this:
queryset = A.objects.filter(b_btext__isexact="your b text", c_ctext__isexact="your c text")

formset_factory with forms with different initial data

I am writing a view that uses POST data to display multiple forms with differing prefilled FK's
I have a ModelForm in forms.py
class SurveyForm(forms.ModelForm):
class Meta:
model = Survey
who's model looks like this...
class Survey(models.Model):
student = models.ForeignKey(Student)
surveyset = models.ForeignKey(SurveySet)
cei_0 = models.BooleanField()
cei_1 = models.BooleanField()
My view looks kind of like this so far
# ... after building a list from POST we essentially have:
list_of_studentids = [1,3,2,6,7,45]
students = []
for i in list_of_student_ids:
students.append(Student.objects.filter(id=i))
SurveyFormSet = formset_factory(SurveyForm, extra=6)
formset = SurveyFormSet(initial=[
{'surveyset': SurveySet.create(),
'student': ?????,}
])
How do I return a bunch of forms with different student FK's and the same surveyset FK?
You need to pass an instance attribute to the form:
prefilled_survey = Survey(student=student_instance, surveyset=surveyset_instance)
form = SurveyForm(request.POST or None, instance=prefilled_survey)

Django: Adding property to User model after creating model based on abstract class

I have a normal model and an abstract model like so:
class TaggedSubject(models.Model):
user = models.ForeignKey(User, null=True, blank=True)
category = models.CharField(max_length=200)
foo = models.CharField(max_length=50)
bar = models.CharField(max_length=50)
# etc
content_type = models.ForeignKey(ContentType)
content_object_pk = models.CharField(max_length=255)
content_object = generic.GenericForeignKey("content_type", "content_object_pk")
def __unicode__(self):
if self.user:
return "%s" % (self.user.get_full_name() or self.user.username)
else:
return self.label
class Taggable(models.Model):
tagged_subjects = generic.GenericRelation(TaggedSubject, content_type_field='content_type', object_id_field='content_object_pk')
#property
def tagged_users(self):
return User.objects.filter(pk__in=self.tagged_subjects.filter(user__isnull=False).values("user"))
class Meta:
abstract = True
The Taggable abstract model class then gets used like so:
class Photo(Taggable):
image = models.ImageField(upload_to="foo")
# ... etc
So if we have a photo object:
photo = Photo.objects.all()[0]
I can all the users tagged in the photo with photo.tagged_users.all()
I want to add the inverse relation to the user object, so that if I have a user:
user = User.objects.filter(pk__in=TaggedSubject.objects.exclude(user__isnull=True).values("user"))[0]
I can call something like user.tagged_photo_set.all() and have it return all the photo objects.
I suspect that since TaggedSubject connects to the Taggable model on a generic relation that it won't be possible to use it as a through model with a ManyToMany field.
Assuming this is true, this is the function I believe I'd need to add (somehow) to the User model:
def tagged_photo_set(self):
Photo.objects.filter(pk__in=TaggedSubject.objects.filter(user=self, content_type=ContentType.objects.get_for_model(Photo))
I'm wondering if it's possible to set it up so that each time a new model class is created based on Taggable, it creates a version of the function above and adds it (ideally as a function that behaves like a property!) to User.
Alternatively, if it is somehow possible to do ManyToMany field connections on a generic relation (which I highly doubt), that would work too.
Finally, if there is a third even cooler option that I am not seeing, I'm certainly open to it.
You could use add_to_class and the class_prepared signal to do some post processing when models subclassing your base class are set up:
def add_to_user(sender, **kwargs):
def tagged_FOO_set(self):
return sender.objects.filter(pk__in=TaggedSubject.objects.filter(
user=self,
content_type=ContentType.objects.get_for_model(sender)))
if issubclass(sender, MyAbstractClass):
method_name = 'tagged_{model}_set'.format(model=sender.__name__.lower())
User.add_to_class(method_name, property(tagged_FOO_set))
class_prepared.connect(add_to_user)

field choices() as queryset?

I need to make a form, which have 1 select and 1 text input. Select must be taken from database.
model looks like this:
class Province(models.Model):
name = models.CharField(max_length=30)
slug = models.SlugField(max_length=30)
def __unicode__(self):
return self.name
It's rows to this are added only by admin, but all users can see it in forms.
I want to make a ModelForm from that. I made something like this:
class ProvinceForm(ModelForm):
class Meta:
CHOICES = Province.objects.all()
model = Province
fields = ('name',)
widgets = {
'name': Select(choices=CHOICES),
}
but it doesn't work. The select tag is not displayed in html. What did I wrong?
UPDATE:
This solution works as I wanto it to work:
class ProvinceForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ProvinceForm, self).__init__(*args, **kwargs)
user_provinces = UserProvince.objects.select_related().filter(user__exact=self.instance.id).values_list('province')
self.fields['name'].queryset = Province.objects.exclude(id__in=user_provinces).only('id', 'name')
name = forms.ModelChoiceField(queryset=None, empty_label=None)
class Meta:
model = Province
fields = ('name',)
Read Maersu's answer for the method that just "works".
If you want to customize, know that choices takes a list of tuples, ie (('val','display_val'), (...), ...)
Choices doc:
An iterable (e.g., a list or tuple) of
2-tuples to use as choices for this
field.
from django.forms.widgets import Select
class ProvinceForm(ModelForm):
class Meta:
CHOICES = Province.objects.all()
model = Province
fields = ('name',)
widgets = {
'name': Select(choices=( (x.id, x.name) for x in CHOICES )),
}
ModelForm covers all your needs (Also check the Conversion List)
Model:
class UserProvince(models.Model):
user = models.ForeignKey(User)
province = models.ForeignKey(Province)
Form:
class ProvinceForm(ModelForm):
class Meta:
model = UserProvince
fields = ('province',)
View:
if request.POST:
form = ProvinceForm(request.POST)
if form.is_valid():
obj = form.save(commit=True)
obj.user = request.user
obj.save()
else:
form = ProvinceForm()
If you need to use a query for your choices then you'll need to overwrite the __init__ method of your form.
Your first guess would probably be to save it as a variable before your list of fields but you shouldn't do that since you want your queries to be updated every time the form is accessed. You see, once you run the server the choices are generated and won't change until your next server restart. This means your query will be executed only once and forever hold your peace.
# Don't do this
class MyForm(forms.Form):
# Making the query
MYQUERY = User.objects.values_list('id', 'last_name')
myfield = forms.ChoiceField(choices=(*MYQUERY,))
class Meta:
fields = ('myfield',)
The solution here is to make use of the __init__ method which is called on every form load. This way the result of your query will always be updated.
# Do this instead
class MyForm(forms.Form):
class Meta:
fields = ('myfield',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Make the query here
MYQUERY = User.objects.values_list('id', 'last_name')
self.fields['myfield'] = forms.ChoiceField(choices=(*MYQUERY,))
Querying your database can be heavy if you have a lot of users so in the future I suggest some caching might be useful.
the two solutions given by maersu and Yuji 'Tomita' Tomita perfectly works, but there are cases when one cannot use ModelForm (django3 link), ie the form needs sources from several models / is a subclass of a ModelForm class and one want to add an extra field with choices from another model, etc.
ChoiceField is to my point of view a more generic way to answer the need.
The example below provides two choice fields from two models and a blank choice for each :
class MixedForm(forms.Form):
speaker = forms.ChoiceField(choices=([['','-'*10]]+[[x.id, x.__str__()] for x in Speakers.objects.all()]))
event = forms.ChoiceField(choices=( [['','-'*10]]+[[x.id, x.__str__()] for x in Events.objects.all()]))
If one does not need a blank field, or one does not need to use a function for the choice label but the model fields or a property it can be a bit more elegant, as eugene suggested :
class MixedForm(forms.Form):
speaker = forms.ChoiceField(choices=((x.id, x.__str__()) for x in Speakers.objects.all()))
event = forms.ChoiceField(choices=(Events.objects.values_list('id', 'name')))
using values_list() and a blank field :
event = forms.ChoiceField(choices=([['','-------------']] + list(Events.objects.values_list('id', 'name'))))
as a subclass of a ModelForm, using the one of the robos85 question :
class MixedForm(ProvinceForm):
speaker = ...