I have imported my MySQL DB to Django. In this DB, I have an intermediate table called GroupUsers which links User and GroupName .
I would like to make a form where I can fill in the user attributes and add it directly to a selected group.
So basically we have an user form with an extra field corresponding to the groups that I need to select among three categories: family, friends, pro.
I’m not able to make it work.
#models.py class GroupUsers(models.Model): group = models.ForeignKey(GroupName, on_delete=models.CASCADE) user = models.ForeignKey('User', on_delete=models.CASCADE) class Meta: managed = False db_table = 'group_users' unique_together = (('group', 'user'),) def __str__(self): return self.group.name class User(models.Model): email = models.CharField(unique=True, max_length=180) last_name = models.CharField(max_length=32) first_name = models.CharField(max_length=32) class Meta: managed = False db_table = 'user' verbose_name = "user" def __str__(self): return self.first_name class GroupName(models.Model): group_id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) description = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'group_name' verbose_name = 'Group' def __str__(self): return self.name #forms.py class UserCreateForm(forms.ModelForm): class Meta: model = User fields = ('first_name','last_name', 'email') def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) self.fields['group'] = forms.ModelChoiceField(queryset=GroupName.objects.all()) #view.py class UserCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView): template_name = 'dashboard/users/user_create_form.html' model = User form_class = UserCreateForm def get_object(self, queryset=None): obj = super().get_object(queryset) return obj def get_success_url(self): messages.success(self.request, "The user %s was added successfully" % ( self.object.first_name)) return reverse_lazy('dashboard:user') def form_valid(self, form): group = form.cleaned_data['group'] return super().form_valid(form)
At this point, I’m stuck. I don’t know how can I save the GroupUser because it is composed of two objects : an user and a group name. I don’t have access to the group id.
I tried with the inline formset factory approach but I’m not able to obtain the result.
What I would like to do maybe is to do the following (pseudo code)
def form_valid(self, form): group = form.cleaned_data['group'] user = getUser() group_user = GroupUser.objects.create(user=user, groupName=group) group_user.save() return super().form_valid(form)
The things here is I don’t know how to get the Object since for example the Group, I have just access to the char field and not the ID.
Could you please help me ? I’m sure, it’s not that difficult. Thank