How to pass data from HTML form to Database in Django - python

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! :)

Related

How can upload word or pdf file in django

I am trying to upload word/pdf file but it's not working. My form submit successfully but file not store in document field. It show empty field and it also not show any error during submit the form, i don't know where is the issue and how can i fix the issue. I add the MEDIA URL in setting and also define the path in urls
View.py
class SaloonRegistration(TemplateView):
template_name = 'saloonRegistration.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
def post(self, request):
saloon = SaloonRegister(
saloon_name=self.request.POST.get('saloon_name'),
owner_name=self.request.POST.get('owner_name'),
address=self.request.POST.get('address'),
contact_no=self.request.POST.get('contact_no'),
document=self.request.POST.get('document')
)
saloon.save()
return redirect('menu')
Model.py
class SaloonRegister(models.Model):
saloon_name = models.CharField(max_length=50)
owner_name = models.CharField(max_length=30)
address = models.CharField(max_length=30)
contact_no = models.BigIntegerField()
document = models.FileField(upload_to='doc/')
is_active = models.BooleanField(default=False)
Template
{% extends 'home.html' %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="saloon_name">Saloon Name
<input type="text" name="saloon_name" placeholder="Enter Your first name">
</label>
<label for="owner_name">Owner Name
<input type="text" name="owner_name" placeholder="Enter Your last_name">
</label>
<label for="address">Address
<input type="text" name="address" placeholder="Enter email address">
</label>
<label for="contact_no">Contact No
<input type="number" name="contact_no" placeholder="Enter your username">
</label>
<label for="document"> upload Doc
<input type="file" name="document" id="document">
</label>
<button type="submit">Submit</button>
</form>
{% endblock%}
Check file upload in the documentation

Using django form within custom html template

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")

django models not accept the email?

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>

My form gets Submitted but no data is being added in database django

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')

Django: may not be NULL when submitting a form

I'm trying to submit a form with just the date(and now time), but when I go to submit it I get the error incidents_incident.incident_date_time_occurred may not be NULL even when I enter an actual date in the input field. Why do I get that error when I enter in a date?
models.py
class Incident(models.Model):
incident_date_time_occurred = models.DateTimeField('incident occurred', default=timezone.now, blank=True)
class Meta:
verbose_name_plural="Incident"
forms.py
class IncidentForm(forms.ModelForm):
class Meta:
model = Incident
fields = ('incident_date_time_occurred',)
report.html
{% extends "base.html" %}
{% block content %}
<div class="container-fluid">
<form action="{% url 'incidents:report' %}" method="POST">{% csrf_token %}
{% csrf_token %}
<div class="row">
<div class="form-group col-md-4">
<label for="date" class="col-sm-4 control-label">{{ form.incident_date_time_occurred.label }}</label>
<input type="datetime-local" name= "incident_date_time_occurred" class="form-control" id="date">
</div>
</div>
<input type="submit" value="Inschrijven!" class="btn btn-primary" />
</form>
</div>
{% endblock %}
Can you check your solution by using default form created from incident? As I remember Django's dateTimeField requires two fields: date and time.
https://docs.djangoproject.com/en/1.7/ref/models/fields/#datetimefield
You are missing the name attribute on the date input. Try that:
<input type="date" class="form-control" id="date" name="incident_date_time_occurred">

Categories