how to render django forms manually? - django

am new in Django. Does anybody know how to implement manual?
I have newsletter app:
newsletter/views.py
from django.shortcuts import render
from .forms import NewsUserForm
from . models import NewsUsers
# Create your views here.
def newsletter_subscribe(request):
if request.method == 'POST':
form = NewsUserForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
instance = form.save(commit=False)
if NewsUsers.objects.filter(email=instance.email).exists():
print('your email Already exists in our database')
else:
instance.save()
print('your email has been submitted to our database')
else:
form = NewsUserForm()
context = {'form':form}
template = "home/base.html"
return render(request, template, context)
newsletter/models.py
from django.db import models
# Subscribe models.
class NewsUsers(models.Model):
name = models.CharField(max_length = 30)
last_name = models.CharField(max_length = 30)
email = models.EmailField()
date_added = models.DateField(auto_now_add=True)
class Meta:
verbose_name = "NewsUser"
verbose_name_plural = "NewsUsers"
def __str__(self):
return self.email
newslettter/urls.py
from django.urls import path
from .views import newsletter_subscribe
app_name = 'newsletter'
urlpatterns = [
path('subscribe', newsletter_subscribe, name='subscribe'),
]
How to render this django forms manually, from third app to home template?
And i have in home app base template with following code:
home/templates/base.html
How to use this form on this template?

Related

When adding a new query in Django, the foreign key gets the value NULL

I am still learning programming and currently experimenting with Django.
Currently I am trying to build a task manager but when I try to add a new Tasks(def new_tasks) it should be related to TaskGroup, instead the task_group_id is related to NULL and I can't seem to figure out why. I believe the reason is some where in the views.py -> def new_tasks. Any help is gratefully appreciated.
The structure:
Project 1
Task Group 1
Tasks 1
Task 1
Task 2
Task 3
Tasks 2
Task 4
Task 5
Task Group 2
Tasks 3
Task 6
Project 2
Task Group 3
Tasks 4
Task 7
Task 8
Relating the Task Group to Project works but relating the Tasks to Task Group gives the value NUll.
image of database
Models.py
from django.db import models
from django.contrib.auth.models import User
class Project(models.Model):
"""A project the user is working on."""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
"""Return a string representation of the model."""
return self.text
class TaskGroup(models.Model):
""" Title of a group of tasks """
project = models.ForeignKey(Project, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=100, blank=True, default='')
desc = models.CharField(max_length=300, default='')
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
""" Return a string representation of the model. """
return self.title
class Tasks(models.Model):
""" Will be the title/segment that will contain the task items """
task_group = models.ForeignKey(TaskGroup, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=100, default='')
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
""" Return a string representation of the model. """
return self.title
views.py
from django.shortcuts import render, redirect
from .models import Project, TaskGroup, Task, Tasks
from .forms import ProjectForm, TasksForm, TaskGroupForm
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.contrib import messages
# Delete
from django.core.exceptions import PermissionDenied
from django.urls import reverse
#login_required
def taskgroup(request, task_id):
"""Show a single task"""
taskgroup = TaskGroup.objects.get(id=task_id)
tasks = taskgroup.tasks_set.all()
# Make sure the task belongs to the current user.
project = taskgroup.project
if project.owner != request.user:
raise Http404
context = {'taskgroup':taskgroup, 'tasks': tasks}
return render(request, 'tasks/taskgroup.html', context)
#login_required
def task(request, task_id):
"""Show a single task"""
tasks = Task.objects.get(id=task_id)
# Make sure the task belongs to the current user.
project = tasks.project
if project.owner != request.user:
raise Http404
context = {'tasks':tasks}
return render(request, 'tasks/task.html', context)
#login_required
def new_project(request):
"""Add new project"""
if request.method != 'POST':
# No data submitted; create a blank form.
form = ProjectForm()
else:
# POST data submitted; process data.
form = ProjectForm(data=request.POST)
if form.is_valid():
new_project = form.save(commit=False)
new_project.owner = request.user
new_project.save()
return redirect('tasks:projects')
# Display a blank or invalid form.
context = {'form': form}
return render(request, 'tasks/new_project.html', context)
#login_required
def new_taskgroup(request, project_id):
""" Add new task """
project = Project.objects.get(id=project_id)
# Make sure the task belongs to the current user.
if project.owner != request.user:
raise Http404
if request.method != 'POST':
# No data submitted; create a blank form.
form = TaskGroupForm()
else:
# POST data submitted; process data.
form = TaskGroupForm(data=request.POST)
if form.is_valid():
new_taskgroup = form.save(commit=False)
new_taskgroup.project = project
new_taskgroup.save()
return redirect('tasks:project', project_id=project_id)
# Display a blank or invalid form.
context = {'project': project, 'form': form}
return render(request, 'tasks/new_taskgroup.html', context)
#login_required
def new_tasks(request, taskgroup_id):
""" Add new task """
taskgroup = TaskGroup.objects.get(id=taskgroup_id)
# Make sure the task belongs to the current user.
project = taskgroup.project
if project.owner != request.user:
raise Http404
if request.method != 'POST':
# No data submitted; create a blank form.
form = TasksForm()
else:
# POST data submitted; process data.
form = TasksForm(data=request.POST)
if form.is_valid():
new_tasks = form.save(commit=False)
new_tasks.taskgroup = taskgroup
new_tasks.save()
return redirect('tasks:taskgroup', task_id=taskgroup_id)
# Display a blank or invalid form.
context = {'taskgroup': taskgroup, 'form': form}
return render(request, 'tasks/new_tasks.html', context)
Forms.py
from django import forms
from .models import Project, TaskGroup, Task, Tasks
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['text']
labels = {'text': ''}
class TaskGroupForm(forms.ModelForm):
class Meta:
model = TaskGroup
fields = ['title', 'desc']
labels = {'desc': 'Description:','title': 'Title:'}
widgets = {'desc': forms.Textarea(attrs={'cols':80})}
class TasksForm(forms.ModelForm):
class Meta:
model = Tasks
fields = ['title']
labels = {'title': 'title:'}
urls.py
"""Defines URL patterns for tasks"""
from django.urls import path
from . import views
app_name = 'tasks'
urlpatterns = [
# Home page
path('', views.index, name='index'),
# Page that shows all projects.
path('taskmanager/', views.projects, name='projects'),
# Detail page for a single project.
path('taskmanager/<int:project_id>/', views.project, name='project'),
# Detail page for a single taskgroup.
path('taskmanager/task/<int:task_id>/', views.taskgroup, name='taskgroup'),
# Detail page for a single task.
path('taskmanager/task/<int:task_id>/', views.task, name='task'),
# Page for adding a new project
path('new_project/', views.new_project, name='new_project'),
# Page for adding new task group
path('new_taskgroup/<int:project_id>/', views.new_taskgroup, name='new_taskgroup'),
# Page for adding new task
path('new_tasks/<int:taskgroup_id>/', views.new_tasks, name='new_tasks'),
# Page for editing task
path('edit_task/<int:task_id>/', views.edit_task, name='edit_task'),
]
urlpatterns.extend(
[
path('delete/<int:task_id>/', views.delete_task, name='delete_task'),
]
)
Made a Mistake, fixed it.
new_tasks.taskgroup = taskgroup => new_tasks.task_group = taskgroup
thanks to Iain!

Django ImageField does not validate image

I can upload the code, however it is a very basic form that has an ImageField and a Model with and ImageField, however I can upload any file type. I have installed PIL and I am successfully writing the uploaded files to the media directory but as I stated, they can be whatever I like as no validation appears to be happening.
Update has been added, sorry I didn't do this earlier.
Views.
from django.shortcuts import render
from .forms import QuoteForm, ImageForm
from django.http import HttpResponse
from django.core.mail import EmailMessage
from django.shortcuts import redirect
from django.template.loader import get_template
from .models import Quote, Image, Job
from django.forms import modelformset_factory
from django.contrib import messages
from django.http import HttpResponseRedirect
def job_index(request):
jobs = Job.objects.all()
context = {
'jobs':jobs
}
return render (request, 'about.html', context)
def quote(request):
if request.method == 'POST':
form = QuoteForm(request.POST)
files = request.FILES.getlist('image')
if form.is_valid():
quote_form = form.save(commit=False)
quote_form.save()
messages.success(request, 'Form submission successful')
HttpResponse('image upload success')
form=QuoteForm()
for f in files:
Image.objects.create(quote=quote_form, image = f)
else:
print("Oh Know")
else:
form = QuoteForm()
context ={
'form': form,
}
return render (request, 'quote.html', context)
Form
from django import forms
from .models import Quote, Image
from django.core.exceptions import ValidationError
from django.core import validators
from django.utils.translation import gettext_lazy as _
import csv
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, ButtonHolder, Submit
SERVICES = [
('lawn', 'Lawn Mowing'),
('hedge', 'Hedge Triming'),
]
# def check_size(value):
# if len(value)<6:
# raise ValidationError("You fucked it")
class QuoteForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Post Code to check if we service your area"}))
message = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Title"}))
date_call = forms.CharField(widget=forms.TextInput(attrs={"id":"datetimes"}))
service = forms.ChoiceField(choices=SERVICES)
class Meta:
model = Quote
fields = ('title', 'message', 'email', 'date_call', 'service')
def clean_title(self):
with open("/Users/Mitch/Desktop/Work/Website/db_landscaping/db_landscaping/static/postcodes.csv", mode = "r") as csvDataFile:
csvReader = csv.reader(csvDataFile)
title = self.cleaned_data.get("title")
for row in csvReader:
if title not in row:
raise ValidationError('Postcode invalid or we do not service your area')
return title
class ImageForm(forms.ModelForm):
image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta (QuoteForm.Meta):
fields = QuoteForm.Meta.fields + ('image',)
Models
from django.db import models
from django.db.models.signals import pre_save
from db_landscaping import settings
import os
from django.template.defaultfilters import slugify
class Quote (models.Model):
title = models.CharField(null=True, max_length=100)
message = models.TextField(null=True,blank=True)
email = models.EmailField( null=True)
slug = models.SlugField(null=True ,unique=True )
service = models.CharField(max_length=100, null=True)
date_call = models.TextField(null=True)
created_date = models.DateTimeField(null=True, auto_now_add=True)
last_modified = models.DateTimeField(null=True, auto_now=True)
class Job (models.Model):
title = models.CharField(null=True, max_length=100)
message = models.TextField(null=True,blank=True)
image = models.ImageField(upload_to="images/job",null=True,blank=True)
class Image (models.Model):
quote = models.ForeignKey(Quote, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to="images/",null=True,blank=True)
def __str__(self):
return self.quote.title + "Image"
Pretty sure am late here, but maybe in case anyone has the same issue, I think you would have had to create your own validator or use Djangos: Django.core.validators.validate_image_file_extension
and add this to your model field i.e
image = models.ImageField(upload_to="images/",null=True,blank=True, validators=[validate_image_file_extension])
That way, your uploaded files would be validated and incase there not an image, a validation error would be raised.

How to save url of the image in database with Django

i am new in Django, how to save url of the image in db using django. Thank you very much, sorry my english, i am learning too.
views.py
from django.shortcuts import render
from django.views.decorators.http import require_POST
from .models import Cad_component
from django import forms
from django.views.decorators.http import require_http_methods
class register_data(forms.ModelForm):
class Meta:
model = Cad_component
fields = ('title','slug','description','start_date','imagviewe')
def home(request):
imagesData = Cad_component.objects.all()
template_name = 'index.html'
context = {
'imagesData': imagesData
}
return render(request, template_name, context)
def register(request):
if request.method == "POST":
form = register_data(request.POST)
print (form)
if form.is_valid():
datas = form.save(commit=True)
#datas.image.save(request.read['title'],request.read['image'])
datas.save()
else:
form = register_data()
return render(request, 'register.html', {'form': form})
models.py
from django.db import models
import datetime
class ComponentManager(models.Manager):
def search(self, query):
return self.get_queryset().filter(
models.Q(name__icontains=query) | \
models.Q(description__icontains=query)
)
class Cad_component(models.Model):
title = models.CharField('Title', max_length=100)
slug = models.SlugField('Link')
description = models.TextField('Description', blank=True)
start_date = models.DateField('Data: ', null=True, blank=True)
image = models.ImageField(upload_to='img', verbose_name='Imagem', null=True, blank=True)
created_at = models.DateTimeField('Criado em ', auto_now_add=True)
updated_at = models.DateTimeField('Atualizado em', auto_now=True)
objects = ComponentManager()
def __str__(self):
return self.title
I was able to solve this problem, with a configuration that Django does in the HTML file. Just add: enctype = "multipart / form-data" in the FORM tag.
Follow:
<form class="needs-validation" method="post" enctype="multipart/form-data">
Any doubts I am available.
from django.core.files.storage import FileSystemStorage
//inside the view function
myfile = request.FILES['files']
f = FileSystemStorage()
filename = f.save(myfile.name, myfile)
url = f.url(filename)
Now you can store this url.
Give an up if it worked... I am new to stackoverflow.

Django - Save forms in the same data table

I'm having problem in saving selected choices in the same row of data table for each participant).
I have 2 forms. The first form is for some data and a multiple-choice question. The second form is another multiple-choice question. It also means I have 2 pages, after submit answers for page 1, it will redirect to page 2 for question 2.
When I try to be a participant and choose answers, the selected choices are saved in different data table. Pictures and code are displayed below.
forms.py
from django import forms
from .models import Survey
class SurveyForm(forms.ModelForm):
BAT='Batman'
SUPER='Superman'
IRON='Ironman'
WHATMOVIE1 = [
(BAT, 'Batman'),
(SUPER, 'Superman'),
(IRON, 'Ironman'),
]
movie_1 = forms.ChoiceField(choices=WHATMOVIE1, widget=forms.RadioSelect())
class Meta:
model = Survey
fields = ["location", "age",
"marital_status", "education", 'movie_1']
class SurForm(forms.ModelForm):
APP='Apple'
BAN='Banana'
LEM='Lemon'
WHATMOVIE2 = [
(APP, 'Apple'),
(BAN, 'Banana'),
(LEM, 'Lemon'),
]
movie_2 = forms.ChoiceField(choices=WHATMOVIE2, widget=forms.RadioSelect())
class Meta:
model = Survey
fields = [ 'movie_2']
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .forms import SurveyForm, SurForm
def homepage(request):
if request.method == 'POST':
title = "Questionnaire"
form = SurveyForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return HttpResponseRedirect(reverse('nextpage'))
else:
form = SurveyForm()
return render(request, "homepage.html", {"form": form})
def nextpage(request):
title = "Next page"
form = SurForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
context = {
"form": form,
}
return render(request, "nextpage.html", context)
admin.py
from django.contrib import admin
from .forms import SurveyForm, SurForm
from .models import Survey, Sur
class SurAdmin(admin.ModelAdmin):
form = SurForm
class SurveyAdmin(admin.ModelAdmin):
list_display = ["location", "age",
"marital_status", "education",
"movie_1"]
form = SurveyForm
admin.site.register(Survey, SurveyAdmin)
admin.site.register(Sur, SurAdmin)
What should I do to save all selected answers in the same row for each participant?
You are using two different models, that is why they are getting separated. You need to create a relation between them, using a OneToOneField can solve the problem. Something like this:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__(self): # __unicode__ on Python 2
return "%s the place" % self.name
class Restaurant(models.Model):
place = models.OneToOneField(Place, primary_key=True)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
def __str__(self): # __unicode__ on Python 2
return "%s the restaurant" % self.place.name
Optionally, you can just combine the two models.

Question On Django Form Models

I am working on form models and get this error:
global name 'AdForm' is not defined
In my view I have:
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django import forms
#login_required
def create(request):
if request.POST:
ad = AdForm(request.POST)
if ad.is_valid():
test = 'valid'
else:
test = 'invalid'
else:
test = 'none'
template = loader.get_template('ads/create.html')
context = RequestContext(request, {
'test': test
})
return HttpResponse(template.render(context))
However it is not picking up my model. My model in my view is:
from django.db import models
from django.forms import ModelForm
TYPE_CHOICES = (
'Image',
'Code',
)
SIZE_CHOICES = (
'Leaderboard',
'Banner',
'Skyscraper',
'Square',
)
class Ad(models.Model):
title = models.CharField(max_length=40)
type = models.CharField(max_length=7)
size = models.CharField(max_length=16)
clicks = models.IntegerField()
media = models.ImageField(upload_to='ads')
link = models.URLField(null=True)
created = models.DateTimeField(auto_now_add=True)
expires = models.DateTimeField(null=True)
def __unicode__(self):
return self.name
class AdForm(ModelForm):
class Meta:
model = Ad
Does anyone know why it is not picking up the form model?
Thanks from a noob.
At the top of your view, you need:
from .models import AdForm
Also, forms usually go in forms.py, not with the models.