Note that there are some explanatory texts on larger screens.

plurals
  1. POPopulating a Django formset using a left join
    primarykey
    data
    text
    <p>I have the following models: Topic, UserProfile, UserSubscribedToTopic</p> <p>The last of these looks like this:</p> <pre><code>class UserSubscribedToTopic(models.Model): topic = models.ForeignKey(Topic) user_profile = models.ForeignKey(UserProfile) start_date = models.DateField(null=True, blank=True) </code></pre> <p>I want to show a list of topics to the user, with a checkbox by each. If the user checks a checkbox then I'll use JavaScript to show the 'start date' text field (so for the purposes of this question I just need to show a text field next to the checkbox). If the user has already saved their selection and is revisiting the page I want to populate the form accordingly when it is first rendered.</p> <p>I've attempted to do this using formsets:</p> <pre><code>class SubscribeToTopicForm(ModelForm): class Meta: model = UserSubscribedToTopic fields = ('topic','start_date') widgets = {'topic': CheckboxInput(attrs={'class': 'topic-checkbox'}), 'start_date': TextInput(attrs={'class': 'date','placeholder': 'Start date'})} SubscribeToTopicFormSetBase = modelformset_factory( UserSubscribedToTopic, form=SubscribeToTopicForm, extra = 0) class SubscribeToTopicFormSet(SubscribeToTopicFormSetBase): def add_fields(self, form, index): super(SubscribeToTopicFormSet, self).add_fields(form, index) </code></pre> <p>I almost get what I want if I add the following to my view:</p> <pre><code>topics_formset = SubscribeToTopicFormSet(queryset=UserSubscribedToTopic.objects.filter(user_profile=user.get_profile())) </code></pre> <p>However, obviously this will only show the topics to which the user has already subscribed. To show all the topics I really need to do is a LEFT JOIN on the Topic table. I can't see how to do this in Django without resorting to raw.</p> <p>My questions:</p> <ul> <li>Am I right in thinking it is not possible to specify a queryset for the formset that is generated from a left join? </li> <li>Would it be better to give up on ModelForm and use a formset that I populate manually? </li> <li>Any better approaches?!</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload