Django Inlineformset

Hi, I wanted to create a blog where some one a button to add titles and subtitles. I also wanted to create a dynamic form where one can interact with it and can add multiple images and videos
Here is the models.py file

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from taggit.managers import TaggableManager
from django.urls import reverse


class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager, self).get_queryset().filter(status='published')


class Article(models.Model):
    state = (
        ('draft', 'Draft'),
        ('published', 'Published')
    )
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=1000, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    status = models.CharField(max_length=11, choices=state, default="draft")
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    objects = models.Manager() 
    published = PublishedManager() 
    tags = TaggableManager()
    
    class Meta:
        ordering = ('-publish',)
        
    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('Article:Article_list', kwargs={"pk": self.pk})
        
class Add_image(models.Model):
    image = models.ImageField(upload_to='images/', null=True, blank=True)
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.article.title
        
class Add_body(models.Model):
    body = models.TextField()
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.article.title
        
class Add_video(models.Model):
    video = models.FileField(upload_to='video/')
    article = models.ForeignKey(Article, on_delete = models.CASCADE)
    
    def __str__(self):
        return self.article.title
       

this is the forms.py file

from django import forms
from django.forms import ModelForm, inlineformset_factory
from .models import Article, Add_image, Add_video, Add_body

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = '__all__'
        exclude = ('publish',)
        
class Add_imageMetaForm(forms.ModelForm):
    class Meta:
        model = Add_image 
        fields = '__all__'
        
class Add_videoMetaForm(forms.ModelForm):
    class Meta:
        model = Add_video
        fields = '__all__'
        
class Add_bodyMetaForm(forms.ModelForm):
    class Meta:
        model = Add_body
        fields = '__all__'

Add_imageFormSet = inlineformset_factory(
        Article,
        Add_image,
        form = Add_imageMetaForm,
        extra=1,
)

Add_videoFormSet = inlineformset_factory(
        Article,
        Add_video,
        form = Add_videoMetaForm,
        extra=1,
)

Add_bodyFormSet = inlineformset_factory(
        Article, 
        Add_body,
        form=Add_bodyMetaForm,
        extra=1,
)

This is the views.py

from django.shortcuts import render, get_object_or_404, redirect
from django.forms import modelformset_factory
from django.views.generic import UpdateView, ListView, CreateView, TemplateView, DetailView
from django.views.generic.edit import ContextMixin
from django.urls import reverse
from django.utils.text import slugify

from .models import Article, Add_video,Add_image, Add_body
from .forms import ArticleForm, Add_imageFormSet, Add_videoFormSet, Add_bodyFormSet

class ArticleListView(ListView):
    model = Article
    template_name = 'home.html'

class ArticleDetailView(DetailView):
    form_class = ArticleForm
    model = Article
    template_name = 'article_detail.html'
    # add_image_meta_formset = Add_imageFormSet(instance=self.get_object())
    # formset = BlogFormSet( instance=Blog')
    
    def get_form(self, form_class, **kwargs):
        form = super(ArticleDetailView, self).get_form(**kwargs)
        add_image_meta_formset = Add_imageFormSet().get_form()
        return form
    
    def get_context_data(self, **kwargs):
        context = super(ArticleDetailView, self).get_context_data(**kwargs)
        # print(add_image_meta_formset)
        context.update({ 
            'article':self.form_class(instance=self.get_object()),
            # 'image':Add_imageFormSet(instance=self.form_class),
            'image':Add_imageFormSet(instance=self.form_class(pk=self.get_object())),
            'body':Add_bodyFormSet(instance=self.get_object()),
            'video':Add_videoFormSet(instance=self.get_object()),
            'object_name': self.object.title,
            'object_nam': self.object.author,
        })
        return context
        

class ArticleCreateView(CreateView):
    form_class = ArticleForm
    template_name = 'article.html'
    
    def get_context_data(self, **kwargs):
        context = super(ArticleCreateView, self).get_context_data(**kwargs)
        
        
        context['add_image_meta_formset'] = Add_imageFormSet()
        context['add_body_meta_formset'] = Add_bodyFormSet()
        context['add_video_meta_formset'] = Add_videoFormSet()
        return context
        
    def post(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        form.slug = slugify(form['title'])
        add_image_meta_formset = Add_imageFormSet(self.request.POST, self.request.FILES)
        add_body_meta_formset = Add_bodyFormSet(self.request.POST)
        add_video_meta_formset = Add_videoFormSet(self.request.POST, self.request.FILES)
        if form.is_valid() and add_image_meta_formset.is_valid() and add_body_meta_formset.is_valid() and add_video_meta_formset.is_valid():
            print(self.request.POST)
            return self.form_valid(form, add_image_meta_formset, add_body_meta_formset, add_video_meta_formset)
        else :
            print(self.request.POST)
            return self.form_invalid(form, add_image_meta_formset, add_body_meta_formset, add_video_meta_formset)
            
    def form_valid(self, form, add_image_meta_formset, add_body_meta_formset, add_video_meta_formset):
        self.object = form.save(commit=False)
        self.object.save()
        
        print(self.request.POST)
        images_meta = add_image_meta_formset.save(commit=False)
        for img in images_meta:
            img.article = self.object
            img.save()
        bodys_meta = add_body_meta_formset.save(commit=False)
        for bod in bodys_meta:
            bod.article = self.object
            bod.save()
        videos_meta = add_video_meta_formset.save(commit=False)
        for vid in videos_meta:
            vid.article = self.object
            vid.save()
        return redirect(reverse("article:Article_list"))
        
    def form_invalid(self, form, add_image_meta_formset, add_body_meta_formset, add_video_meta_formset):
        return self.render_to_response(
            self.get_context_data(form=form,
                                  add_image_meta_formset=add_image_meta_formset,
                                  add_body_meta_formset=add_body_meta_formset,
                                  add_video_meta_formset=add_video_meta_formset,
                                  )
            )


class ArticleUpdateView(UpdateView):
    model = Article
    template_name = 'update_article.html'
    form_name = ArticleForm
    object = None
    
    def get_object(self, queryset=None):
        self.object = super(ArticleUpdateView, self).get_object()
        return self.object
        
    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        add_image_meta_formset = Add_imageFormSet(self.object)
        return self.render_to_response(
                self.get_context_data( form = ArticleForm(instance=self.object),
                                       add_image_meta_formset = add_image_meta_formset,
                                    )
                            )
    def post(self, request, *args, **kwargs):
        
        self.object = self.get_object()
        form = ArticleForm(data=self.request.POST, instance=self.object)
        add_image_meta_formset = Add_imageFormSet(data=self.request.POST, instance=self.object)
        if form.is_valid() and add_image_meta_formset.is_valid():
            return self.form_valid(form, add_image_meta_formset)
        else :
            return self.form_invalid(form, add_image_meta_formset)
            
    def form_valid(self, form, add_image_meta_formset):
        self.object = form.save()
        images_meta = add_image_meta_formset.save(commit=False)
        for img in add_image_meta_formset:
            img.creator = self.profile
            img.article = self.object
            img.save()
        return reverse(redirect("article:Article_list"))
        
    def form_invalid(self, form, add_image_meta_formset):
        return self.render_to_response(
                        self.get_context_data(  form=form,
                                                add_image_meta_formset=add_image_meta_formset,
                                            )
                                )

Pls, help me out

Note: When posting code here, enclose the blocks of code between lines of three backtick - ` characters. That means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep the code properly formatted. (You don’t need to repost your code - you can edit your code and insert the ``` before and after each chunk of code.)

So what specifically do you need assistance with? What is the problem you are having?

I want to build a blog where you can insert images, videos and text bodies at different points. Like medium, when you are writing there, you can insert many things like codes, images, videos.

Cool.

But what question do you have, or what is the issue that you are facing?

Have you written a “blog” project before that you are extending? Or is this something you’re starting from scratch?

So yes, I have been able to create the Create view view section. So, I am having issues with the DetailView. When I try, error comes as Model no attributed pk. What should I do?
Here is the GitHub link

Please post the text of the entire traceback message including the error.

Here is it

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/detail/1/view

Django Version: 3.1.13
Python Version: 3.9.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'article',
 'taggit']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\django\views\generic\detail.py", line 107, in get
    context = self.get_context_data(object=self.object)
  File "C:\Users\hp\Desktop\Comm\article\views.py", line 39, in get_context_data
    'video':Add_videoFormSet(instance=self.form_class),
  File "C:\Users\hp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\django\forms\models.py", line 900, in __init__
    if self.instance.pk is not None:

Exception Type: AttributeError at /detail/1/view
Exception Value: type object 'ArticleForm' has no attribute 'pk'

I’m sorry, this error message doesn’t match either the code you posted here or what’s checked into your repo.

So I guess your first step is to ensure you’re running what you think you’re running.