Recall djangoManytoManyField value from View

Asked 2 years ago, Updated 2 years ago, 47 views

ProfileCategoryForm is used to receive and save ProfileCategory model values from html in POST format. Here, I would like to load each extras_profile_text and extras_category_text of the Profile and Category model into view. (In html template, the contents of extra_profile_text, extra_category_text are not included, and only the values of the name are exposed.)

models.py

class Profile(models.Model):
    name = models.CharField(max_length = 255, blank = False)
    extra_profile_text = models.CharField(max_length = 50, blank = False)

class Category(models.Model):
    name = models.CharField(max_length = 50, blank = False)
    extra_category_text = models.CharField(max_length = 50, blank = False)

class ProfileCategory(models.Model):
    profile = models.ManyToManyField(Profile)
    category = models.ManyToManyField(Category)

forms.py

class ProfileCategoryForm(forms.ModelForm):

    class Meta:
        model = ProfileCategory)
        fields = ('profile', 'category',)

views.py

def task(request): 

    if request.method == "POST":
        form = ProfileCategoryForm(request.POST)

        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            # I want to retrieve the extra_category_text value of Category class in this area.

            post.save()
            form.save_m2m() #ManitoManifieldSave

            return redirect('somewhere')

    else:
        form = ProfileCategoryForm()

    context = {'form': form }


    return render(request, 'some_app/somewhere.html', context)

django python

2022-09-21 20:05

1 Answers

I don't know the purpose of the above code, Can't you add two sentences to views.py as below?


post.save()
form.save_m2m() #ManitoManifieldSave

extra_category_texts = [category.extra_category_text for category in post.category.all()]
print(extra_category_texts)


2022-09-21 20:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.