trying to setting up a small website,a newbie in django . when i create a newsletter setup in django, but the email not saving the admin panel. here is my codes. take a look .
models.py
class Newsletter(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
views.py
def Newsletter(request):
if request.method=="POST":
email = request.POST.get("email")
email = email(email=email)
email.save()
message.success(request, "email Successfully added")
return render(request, 'index.html')
urls.py
path('newsletter', views.Newsletter, name="newsletter"),
template
<div id="mc_embed_signup" class="subscribe-form subscribe-form-dec subscribe-mrg">
<form id="Newsletter" class="validate subscribe-form-style" novalidate="" name="Newsletter" method="post" action="/Newsletter">
<div id="mc_embed_signup_scroll" class="mc-form">
<input class="email" type="email" required="" placeholder="Your email address…" name="Newsletter" value="" id="Newsletter">
<div class="mc-news" aria-hidden="true">
<input type="text" value="" tabindex="-1" name="Subscribers">
</div>
<div class="clear">
{% csrf_token %}
<input id="mc-embedded-subscribe" class="button" type="submit" name="subscribe" value="Subscribe">
</div>
</div>
models.py
class Newsletter(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
views.py:
Here maybe you are overriding the name of the view with the name of Model, try this:
from .models import Newsletter
def adding_email_to_newsletter(request):
if request.method=="POST":
email = request.POST.get("email")
Newsletter.objects.get_or_create(email=email)
message.success(request, "email Successfully added")
return render(request, 'index.html')
the urls.py
path("adding_email_to_newsletter", views.adding_email_to_newsletter, name="adding_email_to_newsletter"),
template:
Here you miss the csrf_token that is required for post submits by default docs and the using of the tag url for best practices.
<div id="mc_embed_signup" class="subscribe-form subscribe-form-dec subscribe-mrg">
<form id="Newsletter" class="validate subscribe-form-style" novalidate="" name="Newsletter" method="post" action="{% url 'adding_email_to_newsletter' %}">
{% csrf_token %}
<div id="mc_embed_signup_scroll" class="mc-form">
<input class="email" type="email" required="" placeholder="Your email address…" name="Newsletter" value="" id="Newsletter">
<div class="mc-news" aria-hidden="true">
<input type="text" value="" tabindex="-1" name="Subscribers">
</div>
<div class="clear">
{% csrf_token %}
<input id="mc-embedded-subscribe" class="button" type="submit" name="subscribe" value="Subscribe">
</div>
</div>
</form>
</div>
Related
I have Tried some patterns which are suggested by some Stackoverflow users. They are like : date:'jS M Y' & date:'c' But not working in my case.
Also referred this article : django update view not showing date input (previous) values
Models.py
from tkinter import CASCADE
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Ticket2(models.Model):
ticketholder = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
ticket_id = models.CharField(max_length=8, default='NS000001')
server_details = models.CharField(max_length=100)
send_date = models.DateTimeField(default=timezone.now)
license_no = models.CharField(max_length=25)
file = models.FileField(upload_to='documents/%Y%m%d/')
def __str__(self):
return self.ticket_id
edit.html
{% extends 'base.html' %}
{% block content %}
<h3 class="row justify-content-around">Edit Form</h3>
<div class="row justify-content-around" class="modal-body">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputEmail1">Ticket ID</label>
<input type="text" value="{{ticketdata.ticket_id}}" name="ticket_id" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Server Details</label>
<input type="text" value="{{ticketdata.server_details}}" name="server_details" class="form-control" id="exampleInputPassword1" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Send Date</label>
<input type="datetime-local" value="{{ ticketdata.send_date.value|date:'jS M Y' }}" name="send_date" class="form-control" id="exampleInputPassword1" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">License No</label>
<input type="text" value="{{ticketdata.license_no}}" name="license_no" class="form-control" id="exampleInputPassword1" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Files</label>
<input type="file" value="{{ticketdata.file}}" name="file" class="form-control" id="exampleInputPassword1" required>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
</div>
{% endblock %}
views.py
from django.shortcuts import render, redirect
from .models import Ticket2
from tmsapp.forms import SaveTicket
from django.contrib import messages
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def Index(request):
ticketdata = Ticket2.objects.filter(ticketholder = request.user)
if request.method == "POST":
form = SaveTicket(request.POST,request.FILES or None)
if form.is_valid():
form.save(commit=False).ticketholder = request.user
form.save()
messages.success(request,("Data has been added successfully !!"))
print(form)
return redirect('index')
else:
form = SaveTicket()
return render(request, 'index.html', {'ticketdata':ticketdata})
#login_required
def Delete(request, id):
ticketdata = Ticket2.objects.get(pk=id)
ticketdata.delete()
messages.success(request,("Data has been deleted successfully !!"))
return redirect('index')
#login_required
def Edit(request, id):
if request.method == "POST":
ticketdata = Ticket2.objects.get(pk=id)
form = SaveTicket(request.POST,request.FILES or None, instance=ticketdata)
if form.is_valid():
form.save()
messages.success(request,("Data has been updated successfully !!"))
print(form)
return redirect('index')
else:
ticketdata = Ticket2.objects.get(pk=id)
print(ticketdata.file)
return render(request, 'edit.html', {'ticketdata':ticketdata})
I have a html file that I wanna use this template to render my form and save it to my database
How to do this?
HTML code:
<div class="container-contact100">
<div class="wrap-contact100">
<form class="contact100-form validate-form" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<span class="contact100-form-title">
Add Item!
</span>
<div class="wrap-input100 validate-input" data-validate="Name is required">
<span class="label-input100">Title</span>
<input class="input100" type="text" name="name" placeholder="Enter food name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
<span class="label-input100">Price</span>
<input class="input100" type="number" name="price" placeholder="Enter food price">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Message is required">
<span class="label-input100">Description</span>
<textarea class="input100" name="message" placeholder="Your description here..."></textarea>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Image is required">
<input type="file" class="custom-file-input" id="customFile" name="filename">
<label class="custom-file-label" for="customFile">Choose file</label>
<span class="focus-input100"></span>
</div>
<div class="container-contact100-form-btn">
<div class="wrap-contact100-form-btn">
<div class="contact100-form-bgbtn"></div>
<button class="contact100-form-btn" type="submit">
<span>
Add
<i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i>
</span>
</button>
</div>
</div>
</form>
</div>
</div>
<div id="dropDownSelect1"></div>
and here is my forms.py :
from django import forms
from .models import Product
class AddItemForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
even you can access my project from this link via github:
https://github.com/imanashoorii/FoodMenu.git
You have to set the name attributes in your form in your html according to field names of your Porudct model like this (using data from your GitHub link):
add_product.html
<form method="post" enctype="multipart/form-data"> # here define enctype attribute so your form can accept images
{% csrf_token %}
<input type="text" name="title">
<input type="text" name="description">
<input type="number" name="price">
<input type="file" name="image">
<button type="submit">Submit</button>
</form>
Or instead of manually defining each field you can just pass a {{ form.as_p }} to your html to render each field inside a <p> tag like this:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Then here is how you would save it in a view:
views.py
def add_product(request):
if request.method == 'POST':
form = AddItemForm(request.POST, request.FILES) # request.FILES is so your form can save images
if form.is_valid()
form.save()
return redirect('home') # redirect to a valid page
else:
form = AddItemForm()
return render(request, 'add_product.html', {'form': form})
I have fixed my problem by changing views.py to this and fix it :
if form.is_valid():
title = request.POST.get('title')
description = request.POST.get('description')
price = request.POST.get('price')
image = request.POST.get('image')
form.save()
return redirect("food:home")
I am trying to make a website's contact page using django where client enters data and it gets submitted in database, the form gets submitted the project runs without errors and yet no data gets added in the db.
Here's my views.py file
from datetime import datetime
from firstapp.models import Contact
# Create your views here.
def index(request):
return render(request,'index.html',)
def apply(request):
return render(request,'apply.html')
def about(request):
return render(request,'about.html')
def socials(request):
return render(request,'social.html')
def contact(request):
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
subject = request.POST.get("subject")
message= request.POST.get("message")
contact=Contact(name=name,email=email,subject=subject,message=message,date=datetime.today())
contact.save
return render(request,'contact.html')
here is my contact.html
{% block title %}Contact {% endblock title %}
{% block body %}
<h2 align="center">CONTACT US </h2>
<div class="container-md">
<form method="POST" action="/contact/">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlInput1">Name</label>
<input type="text" class="form-control" id="exampleFormControlInput1" name="name" placeholder="John Smith">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" name="email" placeholder="name#example.com">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Subject</label>
<input type="text" class="form-control" id="exampleFormControlInput1" name="subject" placeholder="Business
| Suggestions | Query | Complaint | Other">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Message</label>
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
{% endblock body%}
And here's my models.py
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=50)
email =models.EmailField(max_length=254)
subject=models.CharField(max_length=10)
message=models.CharField(max_length=1000)
date=models.DateField()
As I wrote at the comments before, you have forgotten to type brackets following the save: contact.save() instead of contact.save.
It would be better and more beautiful if you do it like this:
def contact(request):
if request.method == "POST":
Contact.objects.create(**request.POST)
return render(request,'contact.html')
I'm learning django now, and i'm facing a problem, I create a form to submite data in my database, but the problem is when i click on submit button, postgres isn't receiving data, I cant understand the problem.
This is my contact form
This is my database
This is my html code
<form action="." method='post' class="p-5 bg-white">
<h2 class="h4 text-black mb-5">Contact Form</h2>
{% csrf_token %}
<div class="row form-group">
<div class="col-md-6 mb-3 mb-md-0">
<label class="text-black" for="fname">First Name</label>
<input type="text" id="fname" class="form-control rounded-0">
</div>
<div class="col-md-6">
<label class="text-black" for="lname">Last Name</label>
<input type="text" id="lname" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="email">Email</label>
<input type="email" id="email" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="subject">Subject</label>
<input type="subject" id="subject" class="form-control rounded-0">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="message">Message</label>
<textarea name="message" id="message" cols="30" rows="7" class="form-control rounded-0" placeholder="Leave your message here..."></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<input type="submit" value="Send Message" class="btn btn-primary mr-2 mb-2">
</div>
</div>
</form>
This is my models.py
from django.db import models
class Form(models.Model):
fname=models.CharField(max_length=300)
lname=models.CharField(max_length=300)
email=models.EmailField()
subject=models.CharField(max_length=300)
message=models.TextField()
This is my views.py
from django.shortcuts import render
from .models import Form
def test(request):
if request.method == 'POST':
request.POST.get('fname')
request.POST.get('lname')
request.POST.get('email')
request.POST.get('subject')
request.POST.get('message')
post=Form()
post.fname= request.POST.get('fname')
post.lname= request.POST.get('lname')
post.email= request.POST.get('email')
post.subject= request.POST.get('subject')
post.message= request.POST.get('message')
post.save()
else:
return render(request,'test.html')
1st. In the form action="." is not necessary as if action is empty it will be sent to the current view itself.
2nd. I suggest using Model Forms which are a lot easier.
Let's say the model name is M1.
models.py
from django.db import models
class M1(models.Model):
fname = models.CharField(max_length=300)
lname = models.CharField(max_length=300)
email = models.EmailField()
subject = models.CharField(max_length=300)
message = models.TextField()
forms.py
from django import forms
M1Form(forms.modelForm):
class Meta:
model = M1
views.py
from django.shortcuts import render
from .models import M1
from .forms import M1Form
def test(request):
if request.method == "POST":
form = M1Form(request.POST)
if form.is_valid():
form.save()
else:
return render(request, "test.html")
else:
return render(request, "test.html")
3rd. If you look at the Templates:
<input type="email" id="email" class="form-control rounded-0">
it does not have an attribute "name" in it. If you want email in request.POST It should be written like
<input type="email" id="email" name="email" class="form-control rounded-0">
Please keep in mind that the name should be the same as the model name (Since we are not overwitting the Form).
For more Documentation:
https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/
Can you help me with this issue? I want to pass data from HTML form to Database.
This is my HTML form:
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% if user.is_authenticated %}
<label for="username">Username: </label>
<input id="username" type="text" name="username" value="{{ user.username }}" disabled><br>
<label for="image">Image: </label>
<input id="image" type="file" name="image">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Save Changes</button>
</div>
</div>
{% endif %}
</form>
And this is my Views.py
class CreateProfile(CreateView):
template_name = 'layout/add_photo.html'
model = Profile
fields = ['image', 'user']
success_url = reverse_lazy('git_project:index')
When I fill in the form (username is equal to logged in username, and chose an image) and when I click "Save Changes", the data has to be passed in Database in table Profile. Here is class Profile in models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.FileField()
I know this is basic, but I don't know how to fix it up, so please, help! :)