0
votes

Every time I try to edit any entry through a form, it gives Attribute Error. I have only one model that is BlogPost models.py

from django.db import models

# Create your models here.

class BlogPost(models.Model):
    """ A title and text for a blog entry"""
    title = models.CharField(max_length=200)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """ return a string representation of the model."""
        return self.title

This is views file views.py

from django.shortcuts import render, redirect

from .models import BlogPost
from .forms import BlogPostForm
def edit_post(request, post_id):
    """ edit an entry"""

    title = BlogPost.objects.get(id=post_id)
    post = title.text

    if request.method != 'POST':
        form = BlogPostForm(instance=post)
    else:
        form = BlogPostForm(instance=post, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('blogs:index', post_id=title.id)

    context = {'title': title, 'post': post, 'form': form}
    return render(request, 'blogs/edit_post.html', context)

This is edit post file edit_post.html

{extends 'blogs/base.html'}


{% block content %}
  <p>Edit Form:</p>
  <p>{{ title }}:</p>
  <form action="{% url 'blogs:edit_post' title.id %}" method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button name="submit">Save changes</button>
  </form>
{% endblock content %}

forms.py

from django import forms

from .models import BlogPost

class BlogPostForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'text']
        labels = {'title':'Title', 'text': 'Post'}
        widgets = {'text': forms.Textarea(attrs={'cols': 80})}

urls.py

# defines urls patterns for the blogs app

from django.urls import path

from . import views

app_name = 'blogs'
urlpatterns = [
    # Home page
    path('', views.index, name='index'),

    # To add new post
    path('new_post/', views.new_post, name='new_post'),

    # To edit post
    path('edit_post/<int:post_id>/', views.edit_post, name='edit_post'),
   ]

I'm using Django 2.2.6 and python 3.7.4.

I guess there is a problem with my URL patterns or with the paths of the request.

This is the error it generates

TypeError at /edit_post/1/

edit_post() got an unexpected keyword argument 'post_id'

Request Method: GET Request URL: http://localhost:8000/edit_post/1/ Django Version: 2.2.6 Exception Type: TypeError Exception Value:

edit_post() got an unexpected keyword argument 'post_id'

Exception Location: C:\Users\nouma\Desktop\blog_folder\ll_env\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 Python Executable: C:\Users\nouma\Desktop\blog_folder\ll_env\Scripts\python.exe Python Version: 3.7.4 **

1
Can you give forms.py as well? You can remove base.html, index.html codes - pissall
I have updated the question. Please review it now @pissall - Nouman Javed
show your urls.py code - rahul.m
I agree that the urls.py is key here. It seems likely that you used the name post_id in your URL, but called it blog_id in the view function. If you make them the same it should fix this. - Robin Zigmond
You're passing post as the instance argument, but you've defined it as a string - the value of the text attribute. If you need this as a separate variable then call it something else so that post remains as the actual model instance that the form needs. - Robin Zigmond

1 Answers

0
votes

I've got my answer. The problem was that in views file I was giving unnecessary argument. i-e return redirect('blogs:index', post_id=title.id) this second argument was not needed