python-3.xdjangobackendweb-deploymentweb-deployment-project

How to return an HttpResponse object instead of None


can you help me out through this problem?, I'm a beginner and trying to learn django..even tho i tried so many other ways but it just wont work out. i hope you can help me

models.py

from django.db import models
from django.db.models.fields import CharField , IntegerField, EmailField


class Member(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=50) 
    email = models.EmailField()
    age = models.IntegerField()
    password =  models.CharField(max_length=100,null=True)


    def __str__(self):
        return self.first_name + " " + self.last_name

form.py

from django.db.models import fields
from django.forms import ModelForm
from django import forms
from .models import Member



class MemberForm(forms.ModelForm):
    class Meta:
        model = Member
        fields = ["first_name", "last_name", "age", "email", "password"]

views.py

from django.shortcuts import  render
from .models import Member
from .form import MemberForm
# Create your views here.




def join(request):
    if request.method == "POST":
        form = MemberForm(request.POST or None)
        if form.is_valid():
            form.save()
            return render(request, "HTML/join.html",{})

    else:
        form = MemberForm()
        return render(request, "HTML/join.html",{})

error

The view myapp.views.join didn't return an HttpResponse object. It returned None instead.

Solution

  • If the form is not valid, your view must return a response:

    def join(request):
        if request.method == "POST":
            form = MemberForm(data=request.POST)
            if form.is_valid():
                form.save()
                return render(request, "HTML/join.html",{})
            else:
                return HttpResponse(status=400) # Replace with what makes sense to you
        else:
            form = MemberForm()
            return render(request, "HTML/base.html", {})
    

    In your urls write something like:

    urlpatterns = [
        path('', join)
    ]
    

    Note also that you should pass the form in the context parameter of render like: render(request, "HTML/base.html", {'form': form}).