i have this issue "django.db.utils.IntegrityError: NOT NULL constraint failed: Eid_Post_name.massenger_name "
and these my codes
views.py
from .models import Name
# Create your views here.
def Home(request):
name_input = request.POST.get('user_name')
name_in_model = Name(massenger_name=name_input,)
name_in_model.save()
return render(request , 'index.html')
and this models.py
from datetime import datetime
# Create your models here.
class Name(models.Model):
massenger_name = models.CharField(max_length=50)
action_time = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.massenger_name
and this index.html
<!DOCTYPE html>
<html lang="en" dir="rtl">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X R7YkIZDRvuzKMRqM OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
{% load static %}
<link rel="stylesheet" href="{% static 'CSS/style.css' %}">
</head>
<body>
<div id="form">
<form method="POST">
<div >
<input type="textarea" placeholder="أكتب أسمك (مثلا/أخوكم عبدالله العتيبي)" id="text_name" name="user_name">
</div>
<div >
<button type="submit" id="button">حمل الصورة</button>
</div>
</form>
</div>
</body>
</html>
CodePudding user response:
You are trying to create a Name
row without a messager_name
which is a required field by default when using CharField
. You need to make this field nullable:
massenger_name = models.CharField(max_length=50, null=True)
You need to makemigrations
and migrate
to apply your changes. This will allow you to have a Name
row without a messager_name
.
CodePudding user response:
Please do not use .get(…)
[Django-doc], it silences an error when the key is missing, which is the case here.
You should check what method is used and in case of a POST request, handle it properly:
from django.shortcuts import redirect
from .models import Name
# Create your views here.
def Home(request):
if request.method == 'POST':
Name.objects.create(massenger_name=request.POST['user_name'])
return redirect(Home)
return render(request , 'index.html')
In the model, it makes more sense to use auto_now_add=True
[Django-doc] for the action_time
:
class Name(models.Model):
massenger_name = models.CharField(max_length=50)
action_time = models.DateTimeField(auto_now_add=True)
# …
Note: In case of a successful POST request, you should make a
redirect
[Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.
Note: Functions are normally written in snake_case, not PascalCase, therefore it is advisable to rename your function to
home
, not.Home