Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Method Not Allowed (POST) I'm stuck

I have been trying to fix this for hours. I can’t seem to see what’s causing the error 🙁

views.py

@login_required
def create_brand(request):
    template_name = "poc/brand_add.html"
    context = {}
    context["form"] = forms.BrandForm()
    
    if request.method == "POST":
        form = forms.BrandForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            form.save()
            return render(request, template_name, context=context)

    else:
        return render(request, template_name, context=context)

forms.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class BrandForm(forms.ModelForm):
    class Meta:
        model = models.Brand
        fields = ('brand_id' , 'brand_name', 'company')

models.py

class Brand(models.Model):
    brand_id = models.AutoField(primary_key=True)
    brand_name = models.CharField(max_length=255)
    company = models.ForeignKey('Company', models.DO_NOTHING)
    date_created = models.DateTimeField(auto_now_add=True, blank=True)

    class Meta:
        managed = False
        db_table = 'brand'

    def __str__(self):
        return f"{self.brand_name}"

template: brand_add.html

{% extends 'base.html' %}

<body>
    {% block content %}
    <div class="container">

        <h1>Create new Brand</h1>
        <form action="{% url 'poc:list_brand' %}" method="post">
            {% csrf_token %}
            {{form.as_p}}

            <input type="submit" value="Create">
        </form>
    </div>
    {% endblock %}

</body>

urls.py

    path('brand/', views.BrandListView.as_view(), name='list_brand'),
    path('brand_add/', views.create_brand, name='create_brand'),
    path('brand/<int:pk>', views.BrandDetailView.as_view(), name='detail_brand'),

Still can’t add a ‘brand’
Is it because of using function based views instead of CBV?

>Solution :

You are submitting the form to the list view address: action="{% url 'poc:list_brand' %}" and the list view may not receive a POST request!

If you are willing to redirect to the list view, you should do the redirection, inside the view code, by returning a RedirectResponse.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading