“contact_contact”关系中的”名字”列的空值违反了非空约束。

huangapple go评论68阅读模式
英文:

null value in column "name" of relation "contact_contact" violates not-null constraint

问题

# DETAIL:  Failing row contains (9, null, miarisoa00@yahoo.de, , null).

IntegrityError at /contact/contact/
null value in column "name" of relation "contact_contact" violates not-null constraint
DETAIL:  Failing row contains (9, null, miarisoa00@yahoo.de, , null).
Request Method: POST
Request URL: http://127.0.0.1:8000/contact/contact/
Django Version: 3.2.15
Exception Type: IntegrityError
Exception Value:
null value in column "name" of relation "contact_contact" violates not-null constraint
DETAIL:  Failing row contains (9, null, miarisoa00@yahoo.de, , null).
Exception Location: D:\MKSD_SITE\MKSD_WEB\site\lib\site-packages\django\db\backends\utils.py, line 84, in _execute
Python Executable: D:\MKSD_SITE\MKSD_WEB\site\Scripts\python.exe
Python Version: 3.9.13
Python Path:
['D:\\MKSD_SITE\\MKSD_WEB\\site\\src',
 'C:\\Program Files\\Python39\\python39.zip',
 'C:\\Program Files\\Python39\\DLLs',
 'C:\\Program Files\\Python39\\lib',
 'C:\\Program Files\\Python39',
 'D:\\MKSD_SITE\\MKSD_WEB\\site',
 'D:\\MKSD_SITE\\MKSD_WEB\\site\\lib\\site-packages']
Server time: Sun, 04 Jun 2023 16:39:42 +0000

**views.py**
def Kontact(request):

    if request.method == 'POST':
        contact = Contact()
        message_name     = request.POST.get('message-name')
        from_email       = request.POST.get('from-email')
        ville            = request.POST.get('ville')
        message          = request.POST.get('message')

        contact.name = message_name
        contact.email = from_email
        ville            = ville
        contact.subject = message

        contact.save()

        message = f"""

        Name: {message_name}
        From: {from_email}
        Stadt: {ville}

        New message: \n\n{message}

        """

        # Send email
        send_mail(
            message_name, #subject
            message, #message
            from_email, #from email
            ['kontakt.mksd@gmail.com'], #to email
            fail_silently=False,

            )


        return render(request, 'contact.html', {'message_name': message_name})

    else:
        return render(request, 'contact.html', {})

**models.py**
class Contact(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=50)
    ville = models.CharField(max_length=100)
    subject = models.TextField(max_length=355)

    def __str__(self):
        return self.name

**Template - HTML**
<div class="row">
    <form method="post" class="was-validated">
        {% csrf_token %}

        <div class="col-lg-6">Email (erforderlich):
            <input type="email" name="from-email" class="form-control mb-30" placeholder="Your Email" required>
        </div>

        <div class="col-lg-6">Phone
            <input type="phone" name="phone" class="form-control mb-30" placeholder="yours">
        </div>

        <div class="col-lg-6">Name (erforderlich):
            <input type="name" name="name" class="form-control mb-30" placeholder="Name" required>
        </div>

        <div class="col-lg-6">Stadt
            <input type="stadt" name="stadt" class="form-control mb-30" placeholder=" City">
        </div>

        <br><br><br>
        <div class="col-12">
            <textarea name="text" class="form-control mb-30" placeholder="text">
            </textarea>
        </div>

        <div class="col-12 my-3">
            <button type="submit" class="btn btn-success">
                Send
            </button>
        </div>

    </form>
</div>
英文:

DETAIL: Failing row contains (9, null, miarisoa00@yahoo.de, , null).

IntegrityError at /contact/contact/
null value in column &quot;name&quot; of relation &quot;contact_contact&quot; violates not-null constraint
DETAIL:  Failing row contains (9, null, miarisoa00@yahoo.de, , null).
Request Method:	POST
Request URL:	http://127.0.0.1:8000/contact/contact/
Django Version:	3.2.15
Exception Type:	IntegrityError
Exception Value:	
null value in column &quot;name&quot; of relation &quot;contact_contact&quot; violates not-null constraint
DETAIL:  Failing row contains (9, null, miarisoa00@yahoo.de, , null).
Exception Location:	D:\MKSD_SITE\MKSD_WEB\site\lib\site-packages\django\db\backends\utils.py, line 84, in _execute
Python Executable:	D:\MKSD_SITE\MKSD_WEB\site\Scripts\python.exe
Python Version:	3.9.13
Python Path:	
[&#39;D:\\MKSD_SITE\\MKSD_WEB\\site\\src&#39;,
 &#39;C:\\Program Files\\Python39\\python39.zip&#39;,
 &#39;C:\\Program Files\\Python39\\DLLs&#39;,
 &#39;C:\\Program Files\\Python39\\lib&#39;,
 &#39;C:\\Program Files\\Python39&#39;,
 &#39;D:\\MKSD_SITE\\MKSD_WEB\\site&#39;,
 &#39;D:\\MKSD_SITE\\MKSD_WEB\\site\\lib\\site-packages&#39;]
Server time:	Sun, 04 Jun 2023 16:39:42 +0000

views.py

def Kontact(request):

	if request.method == &#39;POST&#39;:
		contact = Contact()
		message_name 	= request.POST.get(&#39;message-name&#39;)
		from_email 		= request.POST.get(&#39;from-email&#39;)
		ville 			= request.POST.get(&#39;ville&#39;)
		message 		= request.POST.get(&#39;message&#39;)

		contact.name = message_name 
		contact.email = from_email
		ville 			= ville
		contact.subject = message  

		contact.save()

		message = f&quot;&quot;&quot;  

		Name: {message_name}
		From: {from_email}
		Stadt: {ville}

		New message: \n\n{message}

		&quot;&quot;&quot;

		# Send email
		send_mail(
			message_name, #subject
			message, #message
			from_email, #from email
			[&#39;kontakt.mksd@gmail.com&#39;], #to email
			fail_silently=False, 

			)


		return render(request, &#39;contact.html&#39;, {&#39;message_name&#39;: message_name})

	else:
		return render(request, &#39;contact.html&#39;, {})

models.py

class Contact(models.Model):
	name = models.CharField(max_length=50)
	email = models.EmailField(max_length=50)
	ville = models.CharField(max_length=100)
	subject = models.TextField(max_length=355)

	def __str__(self):
		return self.name

Template - HTML

&lt;div class=&quot;row&quot;&gt;
	&lt;form method=&quot;post&quot; class=&quot;was-validated&quot;&gt;
		{% csrf_token %}

		&lt;div class=&quot;col-lg-6&quot;&gt;Email (erforderlich):
			&lt;input type=&quot;email&quot; name=&quot;from-email&quot; class=&quot;form-control mb-30&quot; placeholder=&quot;Your Email&quot; required&gt;
		&lt;/div&gt;

		&lt;div class=&quot;col-lg-6&quot;&gt;Phone
			&lt;input type=&quot;phone&quot; name=&quot;phone&quot; class=&quot;form-control mb-30&quot; placeholder=&quot;yours&quot;&gt;
		&lt;/div&gt;	

		&lt;div class=&quot;col-lg-6&quot;&gt;Name (erforderlich):
			&lt;input type=&quot;name&quot; name=&quot;name&quot; class=&quot;form-control mb-30&quot; placeholder=&quot;Name&quot; required&gt;
		&lt;/div&gt;

		&lt;div class=&quot;col-lg-6&quot;&gt;Stadt
			&lt;input type=&quot;stadt&quot; name=&quot;stadt&quot; class=&quot;form-control mb-30&quot; placeholder=&quot; City&quot;&gt;
		&lt;/div&gt;									

		&lt;br&gt;&lt;br&gt;&lt;br&gt;
		&lt;div class=&quot;col-12&quot;&gt;
			&lt;textarea name=&quot;text&quot; class=&quot;form-control mb-30&quot; placeholder=&quot;text&quot;&gt;
			&lt;/textarea&gt;
		&lt;/div&gt;
		
		&lt;div class=&quot;col-12 my-3&quot;&gt;
			&lt;button type=&quot;submit&quot; class=&quot;btn btn-success&quot;&gt;
				Send
			&lt;/button&gt;
		&lt;/div&gt;

	&lt;/form&gt;
&lt;/div&gt;

答案1

得分: 2

输入元素的名称是 name,而不是 message-name,与 ville(即 stadt)和 message(即 text)在你的HTML表单中相同,因此你可以使用以下方式:

# views.py:
def kontakt(request):
    if request.method == 'POST':
        message_name = request.POST['name']
        from_email = request.POST['from-email']
        ville = request.POST['stadt']
        message = request.POST['text']
        Contact.objects.create(
            name=message_name, email=from_email, ville=ville, subject=message
        )
        message = f"""

        Name: {message_name}
        From: {from_email}
        Stadt: {ville}

        New message: \n\n{message}

        """

        # 发送电子邮件
        send_mail(
            message_name,  # 主题
            message,  # 消息
            from_email,  # 发件人电子邮件
            ['kontakt.mksd@gmail.com'],  # 收件人电子邮件
            fail_silently=False,
        )
        return redirect('<em>name-of-some-view</em>')

    else:
        return render(request, 'contact.html', {})

同时使用多种(自然)语言通常是一个不好的想法。你似乎同时使用英语、德语和法语,这会使一切变得非常混乱。

注意:请在request.POST[&#39;ville&#39;]上使用 request.POST.get(&#39;ville&#39;)。使用.get(...) 通常只是消除错误,但不能解决问题:如果键丢失,则确实会起作用。但如果确实需要该键的值,那么后续过程中可能会带来更多麻烦。

注意:最好使用Form而不是手动验证和清理数据。Form不仅会简化在HTML中渲染表单,还会更方便地验证输入并清理数据到更方便的类型。

注意:在成功的POST请求的情况下,应进行重定向以实现Post/Redirect/Get模式。这可以避免在用户刷新浏览器时再次进行相同的POST请求。

英文:

The name of the input element is name, not message-name, the same with ville which is stadt and message which is text in your HTML form, so you use:

<pre><code># views.py:
def kontakt(request):
if request.method == 'POST':
message_name = request.POST[<b>'name'</b>]
from_email = request.POST['from-email']
ville = request.POST[<b>'stadt'</b>]
message = request.POST[<b>'text'</b>]
Contact.objects.create(
name=message_name, email=from_email, ville=ville, subject=message
)
message = f&quot;&quot;&quot;

    Name: {message_name}
    From: {from_email}
    Stadt: {ville}

    New message: \n\n{message}

    &amp;quot;&amp;quot;&amp;quot;

    # Send email
    send_mail(
        message_name,  # subject
        message,  # message
        from_email,  # from email
        [&#39;kontakt.mksd@gmail.com&#39;],  # to email
        fail_silently=False,
    )
    return redirect(&#39;&lt;em&gt;name-of-some-view&lt;/em&gt;&#39;)

else:
    return render(request, &#39;contact.html&#39;, {})&lt;/code&gt;&lt;/pre&gt;

It is often a bad idea to use multiple (natural) languages concurrently. You seem to partly English, German and French, making it all very confusing.


> Note: Please use request.POST[&#39;ville&#39;] over request.POST.get(&#39;ville&#39;). Using <code>.get(&hellip;)</code> often only silences the error, but not the problem: indeed it will work if the key is missing. But if the value for that key is really required, it will only result in more trouble later in the process.


> Note: It is better to use a Form&nbsp;<sup>[Django-doc]</sup>
> than to perform manual validation and cleaning of the data. A Form will not
> only simplify rendering a form in HTML, but it also makes it more convenient
> to validate the input, and clean the data to a more convenient type.


> Note: In case of a successful POST request, you should make a redirect
> <sup>[Django-doc]</sup>

> to implement the Post/Redirect/Get pattern&nbsp;<sup>[wiki]</sup>.
> This avoids that you make the same POST request when the user refreshes the
> browser.

huangapple
  • 本文由 发表于 2023年6月5日 00:58:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定