Home > database >  How to assign model form field to a current logged in user in Django's class based views
How to assign model form field to a current logged in user in Django's class based views

Time:06-14

I am trying to save a form with the current logged in user's username, but the error "Cannot assign "'Neshno_Games2'": "League.host" must be a "Manager" instance." occurs

Views.py

class CreateLeaguesView(generic.CreateView):
    model = League
    template_name = "leagues/create-league.html"
    form_class = LeaguesCreationForm
    success_url = "/leagues/leagues"

    def get_context_data(self, **kwargs):
        context = super().get_context_data( **kwargs)
        context['leagues'] = League.objects.all()
        return context

    def form_valid(self, form):
        manager = self.request.user.username
        League.objects.create(
            host = manager,
        )
        return super(CreateLeaguesView, self).form_valid(form)

Model.py

class League(models.Model):
    name = models.CharField(max_length=30)
    no_players = models.IntegerField(default=20)
    start_date = models.DateField(blank=False, null=False)
    end_date = models.DateField(blank=False, null=False)
    prize = models.CharField(max_length=300)
    host = models.ForeignKey(Manager, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

forms.py

class LeaguesCreationForm(forms.ModelForm):
    class Meta:
        model = League
        fields = (
            "name",
            "no_players",
            "start_date",
            "end_date",
            "prize",
        )

CodePudding user response:

You can try like this:

class CreateLeaguesView(generic.CreateView):
    model = League

    def form_valid(self, form):
        form.instance.host= self.request.user.manager  # accessing one to one data
        return super().form_valid(form)

More information can be found here in this documentation: https://docs.djangoproject.com/en/4.0/topics/db/examples/one_to_one/

  • Related