django Submit function does not save data in database - python

I just started using django and this is my first app.
i created "contact form" depending on several tutorials i'v seen, but it doesn't save data to database nor direct me to the "Thank you" html page.
tried many scenarios but none worked
can anyone help?
i'm open to change any thing in the code just to make it work and save the data that i need to save.
setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
# 'crispy_forms',
'widget_tweaks',
models.py
from django.db import models
from django.conf import settings
from datetime import date
class Snippet(models.Model):
MALE = 'MA'
FEMALE = 'FE'
GENDER_CHOICES = [
(MALE, 'Male'),
(FEMALE, 'Female'),
]
LOCAL = 'SA'
NONE_LOCAL = 'NS'
NAT_CHOICES = [
(LOCAL, 'Local'),
(NONE_LOCAL, 'Non_Local'),
]
RIYADH = 'RH'
JEDDAH = 'JH'
CITY_CHOICES = [
(RIYADH, 'Riyadh'),
(JEDDAH, 'Jeddah'),
]
DIPLOMA = 'DP'
BACHELOR = 'BA'
HIGHEREDU = 'HE'
OTHER = 'OT'
EDU_CHOICES = [
(DIPLOMA, 'Diploma'),
(BACHELOR, 'Bachelor'),
(HIGHEREDU, 'Higer Edu'),
(OTHER, 'Other'),
]
ONE = 'On'
FIVE = 'Fi'
OTHER = 'Ot'
INC_CHOICES = [
(ONE, '100-500'),
(FIVE, '500-1000'),
(OTHER, 'Other'),
]
name = models.CharField(max_length=100)
email = models.EmailField()
mobile = models.IntegerField(default=None)
gender = models.CharField(
max_length=2, choices=GENDER_CHOICES, default=MALE)
nat = models.CharField(
max_length=2, choices=NAT_CHOICES, default=LOCAL)
city = models.CharField(
max_length=2, choices=CITY_CHOICES, default=RIYADH)
dob = models.DateField(default=None)
edu = models.CharField(
max_length=2, choices=EDU_CHOICES, default=OTHER)
major = models.CharField(max_length=100)
inc = models.CharField(max_length=2, choices=INC_CHOICES, default=ONE)
def __str__(self):
return '{} {} {} {} {} {} {} {} {} {}'.format(self.name, self.email, self.mobile, self.gender in {self.MALE, self.FEMALE}, self.dob, self.nat in {self.LOCAL, self.NONE_LOCAL}, self.city in {self.RIYADH, self.JEDDAH}, self.edu in {self.DIPLOMA, self.BACHELOR, self.HIGHEREDU, self.OTHER}, self.major, self.inc in {self.ONE, self.FIVE, self.OTHER})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
path('form/', views.contact),
path('home/', views.home),
path('thank/', views.thank),
path('about/', views.about),
forms.py
from django import forms
from .models import Snippet
from django.core.validators import RegexValidator
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField(label='Email')
mobile = forms.IntegerField(label='Mobile', required=True)
gender = forms.ChoiceField(
choices=[('select', 'Select'), ('male', 'Male'), ('female', 'female')])
dob = forms.DateField(required=False)
nat = forms.ChoiceField(label='Nationality',
choices=[('select', 'Select'), ('Local', 'Local'), ('non-Local', 'Non-Local')])
city = forms.ChoiceField(label='City',
choices=[('select', 'Select'), ('riyadh', 'Riyadh'), ('jeddah', 'Jeddah')])
edu = forms.ChoiceField(label='Education',
choices=[('select', 'Select'), ('diploma', 'Diploma'), ('bachelor', 'Bachelor'), ('higher edu', 'Higher Edu'), ('other', 'Other')])
major = forms.CharField(label='Major', required=False)
inc = forms.ChoiceField(label='Income', choices=[('select', 'Select'), (
'1000-5000', '1000-5000'), ('5000-10000', '5000-10000'), ('other', 'Other')])
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class SnippetForm(forms.ModelForm):
class Meta:
model = Snippet
fields = ('name', 'email', 'mobile', 'gender', 'dob',
'nat', 'city', 'edu', 'major', 'inc',)
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import ContactForm, SnippetForm
from .models import Snippet
from django.db import models
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
mobile = form.cleaned_data['mobile']
gender = form.cleaned_data['gender']
dob = form.cleaned_data['dob']
nat = form.cleaned_data['nat']
city = form.cleaned_data['city']
edu = form.cleaned_data['edu']
major = form.cleaned_data['major']
inc = form.cleaned_data['inc']
form.save()
print(name, email, mobile, gender, dob, nat, city, edu, major, inc)
return snippet_detail(request.POST)
else:
form = ContactForm(request.POST)
return render(request, 'myapp/form.html', {'form': form})
def snippet_detail(request):
if (request.method == 'POST') and ("submit" in request.POST):
form = SnippetForm(request.POST)
if form.is_valid():
form.save()
form = SnippetForm()
return render(request, 'myapp/form.html', {'form': form})
def home(request):
return render(request, 'myapp/home.html')
def about(request):
return render(request, 'myapp/about.html')
def thank(request):
return render(request, 'myapp/thank.html')
form.html
{% extends 'myapp/main.html' %}</em>
{% load widget_tweaks %}
<em><!DOCTYPE html></em>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registeration</title>
<body>
{% block content %}
{% csrf_token %}
<div class="Container">
<h3>
Registeration Form
</h3>
<hr>
</div>
<section class="section">
<div class="Container">
<div class="Columns">
<div class="Column is-half is-offset-one-quarter">
<div class="field">
<p>
<label class="label">Name</label>
<div class="control">
{% render_field form.name class="input" placeholder="Your name" %}
</div>
</p>
</div>
<p>
<div class="field">
<label class="label">Email</label>
<div class="control">
{% render_field form.email class="input" placeholder="Your#email.com" %}
</div>
</div>
</p>
<p>
<div class="field">
<label class="label">Mobile</label>
<div class="control">
{% render_field form.mobile class="input" placeholder="Your Mobile" %}
</div>
</div>
</p>
<p>
<div class="field">
<label class="label">Gender</label>
<div class="control">
<div class="select">
{% render_field form.gender %}
</div>
</div>
</div>
</p>
<p>
<div class="field">
<label class="label">Date of Birth</label>
<div class="control">
{% render_field form.dob class="input" placeholder="Please Select" %}
</div>
</div>
</p>
<p>
<div class="field">
<label class="label">Nationality</label>
<div class="control">
<div class="select">
{% render_field form.nat %}
</div>
</div>
</div>
</p>
<p>
<div class="field">
<label class="label">City</label>
<div class="control">
<div class="select">
{% render_field form.city %}
</div>
</div>
</div>
</p>
<p>
<div class="field">
<label class="label">Edu</label>
<div class="control">
<div class="select">
{% render_field form.edu %}
</div>
</div>
</div>
</p>
<p>
<div class="field">
<label class="label">Major</label>
<div class="control">
<div class="select">
{% render_field form.major class="input" placeholder="Your Major" %}
</div>
</div>
</div>
</p>
<p>
<div class="field">
<label class="label">Income</label>
<div class="control">
<div class="select">
{% render_field form.inc %}
</div>
</div>
</div>
</p>
<p>
<div class="field is-grouped">
<div class="control">
<button class="button" is-link="thank.html">Submit</button>
</div>
</div>
</p>
</div>
</div>
</div>
</div>
</section>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</html>
{% endblock %}

Related

NoReverseMatch at /blog Reverse for 'single_blog' with no arguments not found. 1 pattern(s) tried: ['single_blog/(?P<id>[0-9]+)/$']

I tried many times but the page not rendering , i am not understanding where i did wrong? could you please let me know , where i did wrong?
models.py
class Post(models.Model):
head = models.CharField(blank=False, unique=True, max_length=250)
date_time = models.DateTimeField(blank=True, null=True, default=None)
description = models.TextField(blank=False, max_length=1000)
by_name = models.CharField(blank=False, null=True, unique=True, max_length=250)
by_img = models.ImageField(null=True, blank=True)
def __str__(self):
return self.head
views.py
def blog(request):
blogs = Post.objects.all()
return render(request, 'blog.html', {'blogs': blogs})
def blog(request):
blogs = Post.objects.all()
return render(request, 'blog.html', {'blogs': blogs})
def dynamicblog(request, id):
obj = Post.objects.get(id=id)
return render(request, 'single_blog.html', {'obj': obj})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('contact', views.contact, name='contact'),
path('shop', views.shop, name='shop'),
path('service', views.service, name='service'),
path('blog', views.blog, name='blog'),
path('single_blog/<int:id>/', views.dynamicblog, name='single_blog'),
path('single_service', views.single_service, name='single_service'),
blog.html
{% for blog in blogs %}
<div class="col-lg-4 col-md-6 col-sm-12 news-block">
<div class="news-block-two news-block-three wow fadeInLeft" data-wow-delay="300ms" data-wow-duration="1500ms">
<div class="inner-box">
<div class="image-holder">
<figure class="image-box"><img src="{{blog.by_img.url}}" alt=""></figure>
</div>
<div class="lower-content">
<h4>{{blog.head}}</h4>
<div class="post-info">by {{blog.by_name}} on {{blog.date_time}}</div>
<div class="text">{{blog.description}}</div>
<div class="link-btn">Read More<i class="flaticon-slim-right"></i></div>
</div>
</div>
</div>
</div>
{% endfor %}
single_blog.html
<div class="col-lg-4 col-md-12 col-sm-12 sidebar-side">
{% for blog in obj %}
<div class="sidebar blog-sidebar">
<div class="contact-widget sidebar-widget wow fadeInLeft" data-wow-delay="00ms" data-wow-duration="1500ms">
<div class="widget-content">
<h4>{{blog.head}}</h4>
<div class="text">Our industrial plant services keep your generator up</div>
<div class="btn-box"><i class="fas fa-angle-right"></i>Contact Agent</div>
</div>
</div>
</div>
{% endfor %}
</div>
Your single_blog path expect some arguments. So pass it :
blog.html
{% for blog in blogs %}
<div class="col-lg-4 col-md-6 col-sm-12 news-block">
<div class="news-block-two news-block-three wow fadeInLeft" data-wow-delay="300ms" data-wow-duration="1500ms">
<div class="inner-box">
<div class="image-holder">
<figure class="image-box"><img src="{{blog.by_img.url}}" alt=""></figure>
</div>
<div class="lower-content">
<!-- | Here -->
<!-- v -->
<h4>{{blog.head}}</h4>
<div class="post-info">by {{blog.by_name}} on {{blog.date_time}}</div>
<div class="text">{{blog.description}}</div>
<div class="link-btn">
<!-- | Here -->
<!-- v -->
<a href="{% url 'single_blog' id=blog.id %}">Read More<i class="flaticon-slim-right"></i>
</a>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Refs

How to filter draft contents from django website?

I have two options for my articles in my django website: "draft" and "published"
I wrote sth that helps me show only the articles that are on "published" status in admin page.
But the code doesn't work. when I click on the specified category for each article, even the draft ones show up. How can I fix it?
#################
#models.py
from django.db import models
from django.utils import timezone
# my managers
class ArticleManager(models.Manager):
def published(self):
return self.filter(status='Published')
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length=300, verbose_name="Category Topic")
slug = models.SlugField(max_length=100, unique=True, verbose_name="Category Address")
status = models.BooleanField(default=True, verbose_name="Do you want to show?")
position = models.IntegerField(verbose_name="position")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['position']
def __str__(self):
return self.title
class Article(models.Model):
STATUS_CHOICES = (
('Draft', 'Draft'),
('Published', 'Published')
)
title = models.CharField(max_length=300)
slug = models.SlugField(max_length=100, unique=True)
category = models.ManyToManyField(Category, verbose_name="Category", related_name="articles")
description = models.TextField()
thumbnail = models.ImageField(upload_to="images")
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES)
class Meta:
ordering = ['-publish']
def __str__(self):
return self.title
def category_published(self):
return self.category.filter(status=True)
objects = ArticleManager()
############
#Views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse, Http404
from .models import Article, Category
# Create your views here.
def home(request):
context = {
"articles": Article.objects.published()
}
return render(request, 'website/home.html', context)
def detail(request, slug):
context = {
"article": get_object_or_404(Article.objects.published(), slug=slug)
}
return render(request, 'website/detail.html', context)
def article(request):
context = {
"articles": Article.objects.filter(status="Published"),
"category": Category.objects.filter(status=True)
}
return render(request, 'website/article.html', context)
def category(request, slug):
cat = get_object_or_404(Category, slug=slug, status=True)
context = {
"category": cat.articles.all()
}
return render(request, 'website/category.html', context)
###########
#Category.html page
{% extends 'website/base.html' %}
{% load static %}
{% block main %}
<main id="main">
<!-- ======= Breadcrumbs ======= -->
<section id="breadcrumbs" class="breadcrumbs">
<div class="container">
<div class="d-flex justify-content-between align-items-center">
<h2>Blog</h2>
<ol>
<li>Home</li>
<li>Blog</li>
</ol>
</div>
</div>
</section><!-- End Breadcrumbs -->
<!-- ======= Blog Section ======= -->
<section id="blog" class="blog">
<div class="container">
<div class="row">
<div class="col-lg-8 entries">
{% for article in category %}
<article class="entry" data-aos="fade-up">
<div class="entry-img">
<img src="{{ article.thumbnail.url }}" alt="" class="img-fluid">
</div>
<h2 class="entry-title">
{{ article.title }}
</h2>
<div class="entry-meta">
<ul>
<li class="d-flex align-items-center"><i class="icofont-user"></i>
John Doe</li>
<li class="d-flex align-items-center"><i class="icofont-wall-clock"></i>
<time>{{ article.publish }}</time></li>
<li class="d-flex align-items-center"><i class="icofont-tags"></i>
<ul class="tags">
{% for cat in article.category_published %}
#{{ cat.title }}
{% endfor %}
</ul>
</li>
<li class="d-flex align-items-center"><i class="icofont-comment"></i>
12 Comments</li>
</ul>
</div>
<div class="entry-content">
{{ article.description|truncatewords:30}}
<div class="read-more">
Read More
</div>
</div>
</article><!-- End blog entry -->
{% endfor %}
<div class="blog-pagination">
<ul class="justify-content-center">
<li class="disabled"><i class="icofont-rounded-left"></i></li>
<li>1</li>
<li class="active">2</li>
<li>3</li>
<li><i class="icofont-rounded-right"></i></li>
</ul>
</div>
</div><!-- End blog entries list -->
<div class="col-lg-4">
<div class="sidebar" data-aos="fade-left">
<h3 class="sidebar-title">Search</h3>
<div class="sidebar-item search-form">
<form action="">
<input type="text">
<button type="submit"><i class="icofont-search"></i></button>
</form>
</div><!-- End sidebar search formn-->
{# <h3 class="sidebar-title">Categories</h3>#}
{# <div class="sidebar-item categories">#}
{# <ul>#}
{# {% for cat in category %}#}
{# <li class="active"><a href="{% url 'website:category' cat.slug %}">#{{ cat.title
}}</a></li>#}
{# {% endfor %}#}
{# </ul>#}
{##}
{# </div><!-- End sidebar categories-->#}
<h3 class="sidebar-title">Recent Posts</h3>
<div class="sidebar-item recent-posts">
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-1.jpg" alt="">
<h4>Nihil blanditiis at in nihil autem</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-2.jpg" alt="">
<h4>Quidem autem et impedit</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-3.jpg" alt="">
<h4>Id quia et et ut maxime similique occaecati ut</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-4.jpg" alt="">
<h4>Laborum corporis quo dara net para</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-5.jpg" alt="">
<h4>Et dolores corrupti quae illo quod dolor</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
</div><!-- End sidebar recent posts-->
<h3 class="sidebar-title">Tags</h3>
<div class="sidebar-item tags">
<ul>
<li>App</li>
<li>IT</li>
<li>Business</li>
<li>Business</li>
<li>Mac</li>
<li>Design</li>
<li>Office</li>
<li>Creative</li>
<li>Studio</li>
<li>Smart</li>
<li>Tips</li>
<li>Marketing</li>
</ul>
</div><!-- End sidebar tags-->
</div><!-- End sidebar -->
</div><!-- End blog sidebar -->
</div>
</div>
</section><!-- End Blog Section -->
</main><!-- End #main -->
{% endblock %}
Your category view is returning all articles, if you just want published articles in the category you need to filter them.
def category(request, slug):
# filter only published articles
cat = get_object_or_404(Category, slug=slug, status=True)
context = {
"published_articles_in_category": cat.articles.filter(status='Published')
}

Django form doesn't appear on template

I'm currently working on a project that require Django Forms but I ended up with some issues. My form doesn't display at all ... No field appear on my template.
So my code :
models.py
class Place(models.Model):
name = models.CharField(max_length=255)
longitudeMax = models.DecimalField(max_digits=8, decimal_places = 4 ,blank=True)
longitudeMin = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
latitudeMax = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
latitudeMin = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
datasetPath = models.CharField(max_length=255)
isActive = models.BooleanField(default=True)
def __str__(self):
return self.name
def get_place(self, name):
return None
forms.py
class NewPlaceForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder" : "Name",
"class": "form-control"
}
))
longMax = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Longitude Max",
"class": "form-control"
}
))
longMin = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Longitude Min",
"class": "form-control"
}
))
latMax = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Latitude Max",
"class": "form-control"
}
))
latMin = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Latitude Min",
"class": "form-control"
}
))
class Meta:
model = Place
fields = ('name', 'longitudeMax', 'longitudeMin', 'latitudeMax', 'latitudeMin')
views.py
def upload(request):
msg = None
if request.method == "POST":
form = NewPlaceForm(request.POST)
if form.is_valid():
form.save()
msg = 'Place created'
else:
msg = 'Form is not valid'
else:
form = NewPlaceForm()
return render(request, "pages/place_upload.html", {"form": form, "msg" : msg})
urls.py
from django.urls import path, re_path
from app import views
urlpatterns = [
#Data modification page
path('pages/place_modification.html', views.modification, name="place_modification"),
#New place adding page
path('pages/place_upload.html', views.upload, name="place_upload"),
# Matches any html file
re_path(r'^.*\.html', views.pages, name='pages'),
# The home page
path('', views.index, name='home'),
]
html file
<form method="post" action="">
{% csrf_token %}
<div class="card-body">
<div class="row">
<div class="col-md-6 col-lg-4">
<div class="form-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.name }}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-lg-4">
<div class="form-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.longMax }}
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.longMin }}
</div>
</div >
<div class="col-md-6 col-lg-4">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.latMax }}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.latMin }}
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="form-group form-floating-label">
<small id="emailHelp2" class="form-text text-muted">Use negative numbers for South and positive numbers for North</small>
</div>
<div class="form-group form-floating-label">
<small id="emailHelp2" class="form-text text-muted">Use negative numbers for West and positive numbers for East</small>
</div>
</div>
</div>
</div>
<div class="card-action">
<button type="submit" class="btn btn-success">Submit</button>
<button class="btn btn-danger">Cancel</button>
</div>
</form>
I don't see why it doesn't work and it's been several days that I try to make it work ... Did I do something wrong ? Have I forgot something ? Because I don't feel like I did and it's getting on my nerve ahaha
Django handles the form rendering out of the box, to display a basic form, try:
<form method="POST" action="{% url 'namespaced:url' %}">
{ csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit">
</form>
That said, it looks like you're using bootstrap in your template, you might find the package django-bootstrap4 useful (https://github.com/zostera/django-bootstrap4).
Quick example:
pip install django-bootstrap4
and add bootstrap4 to your installed apps.
Then in your template:
{% load bootstrap4 %}
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
<form action="{% url 'namespaced:url' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">
Submit
</button>
{% endbuttons %}
</form>
If you want, you can render each field manually using:
{% bootstrap_field field %}, so you can do things like <div class="col-md-6">{% bootstrap_field my_field %}</div>, to manually arrange your form fields on the page.

Keep data in the form after submit

I am implementing search by two fields in form in Django.
I want to keep input data after search.
For example I input "C++" and chose "IT"
then I received Default values
I tried to parse request variable --- e.g. data = request.POST.copy()
but did not achieved result. What is the reason of this problem?
How can I solve this problem?
This is my code:
models.py
class Company(models.Model):
name = models.CharField(max_length=200)
about = models.TextField()
def __str__(self):
return self.name
class Vacancy(models.Model):
company_key = models.ForeignKey(Company, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
salary = models.CharField(max_length=200, default='40.000')
text = models.TextField(default="The text about vacancy")
city = models.CharField(max_length=200, default='Москва')
date_str = models.CharField(max_length=50, default='12 сентября')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
CHOICES = [
('ALL', 'ALL'),
('IT', 'IT'),
('FINANCE', 'FINANCE'),
('OTHER', 'OTHER'),
]
department = models.CharField(
max_length=20,
choices=CHOICES,
default='ALL',
)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('', HomePageView.as_view(), name='vacancy_list'),
path('search/', SearchResultsView.as_view(), name='search_results'),
path('vacancy/<int:pk>/', views.vacancy_detail, name='vacancy_detail'),
path('accounts/login/', BBLoginView.as_view(), name='login'),
path('accounts/profile/', profile, name='profile'),
path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
views.py
class HomePageView(ListView):
model = Vacancy
template_name = 'vacancy_list/vacancy_list.html'
paginate_by = 2
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def vacancy_detail(request, pk):
vacancy = get_object_or_404(Vacancy, pk=pk)
return render(request, 'vacancy_list/vacancy_detail.html', {'vacancy': vacancy})
class SearchResultsView(ListView):
model = Vacancy
template_name = 'vacancy_list/search_results.html'
paginate_by = 2
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['query'] = self.request.GET.get('q')
# added param
context['query2'] = self.request.GET.get('q2')
return context
def get_queryset(self): # new
query = self.request.GET.get('q')
query2 = self.request.GET.get('q2')
object_list = Vacancy.objects.filter(
Q(title__icontains=query) and Q(department__icontains=query2)
)
return object_list
vacancy_list.html
{% block content %}
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-8">
<h1>{{vacancy.title}}</h1>
</div>
<div class="col-md-4 text-right">
<p> {{ vacancy.salary}} </p>
</div>
</div>
</div>
....
{% endfor %}
search_result.html
{% extends 'vacancy_list/base.html' %}
{% block content %}
<h1> {{request}}</h1>
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
...
{% endfor %}
{% endblock %}
In your search results template, you should use {{ query }} and {{ query2 }} and a little bit of logic to populate the text and drop-down boxes.

IntegrityError: null value in column "image" violates not-null constraint

When I register a new user the website was creating a profile automatically and was using default.jpg image. Suddenly it stopped working. And the error says that I have a problem with my 'image' field. This is the error I get:
IntegrityError at /accounts/register/
null value in column "image" violates not-null constraint
DETAIL: Failing row contains (20, pbkdf2_sha256$150000$72dkND5yT5M0$+/chH/5Vu76KM7oNMjU694EWFZ/p+B..., null, f, kazanda, f, 2019-04-21 17:41:29.969889+00, Andreas, Swarchft, Germany, Frankfurt, andreas_sw#gmail.com, t, null).
This is my models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True)
def __str__(self):
return self.user.username
def save(self, force_insert=False, force_update=False, using=None):
super().save()
img = Image.open(self.image.path)
if img.height > 250 or img.width > 250:
output_size = (250, 250)
img.thumbnail(output_size)
img.save(self.image.path)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
my views.py
class UserRegistrationView(SuccessMessageMixin, CreateView):
form_class = UserCreationModelForm
model = User
success_url = reverse_lazy('login')
success_message = "Account for %(first_name)s was created successfully. You will get email notification when admin will activate your account!"
template_name = 'users/registration.html'
def get_success_message(self, cleaned_data):
return self.success_message % dict(cleaned_data)
#login_required
def profile(request):
if request.method == 'POST':
uform = UserUpdateForm(request.POST, instance=request.user)
pform = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
posts = Post.objects.filter(author=request.user)
if uform.is_valid() and pform.is_valid():
uform.save()
pform.save()
messages.success(request, 'Your account has been updated!')
return redirect('users:cabinet')
else:
uform = UserUpdateForm(instance=request.user)
pform = ProfileUpdateForm(instance=request.user.profile)
posts = Post.objects.filter(author=request.user)
context = {
'uform': uform,
'pform': pform,
'posts': posts
}
return render(request, 'users/user_detail.html', context)
#login_required
def cabinet(request):
profile = Profile.objects.all()
context = {
'profile': profile
}
return render(request, 'users/user_detail.html', context)
my registration.html
which is a form to create a user:
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section mt-5 pl-5 p-4">
<form method="post">
{% csrf_token %}
<fieldset class="form-group pr-4">
<legend class="mb-4">Join Today</legend>
<div class="form-row">
<div class="form-group col-md-3 mb-0">
{{ form.first_name|as_crispy_field }}
</div>
<div class="form-group col-md-3 mb-0">
{{ form.last_name|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.username|as_crispy_field }}
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.country|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.city|as_crispy_field }}
</div>
<div class="form-row">
<div class="form-group col-md-12 mb-0">
{{ form.email|as_crispy_field }}
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
{{ form.password1|as_crispy_field }}
</div>
<div class="form-group col-md-6 mb-0">
{{ form.password2|as_crispy_field }}
</div>
<!-- <div class="form-check">
{{ form.access_challenge }}
<label class="form-check-label" for="Checkbox"> Access Challenge Country</label>
</div> -->
</fieldset>
<div class="form-group">
<button style="border-radius: 0; width: 200px; padding-left: 4px;" class="btn btn-info btn-block" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock %}
Here is my post_form.html
{% extends 'shared/base.html' %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section mt-5 pl-5 p-4">
<form method="post" id="personForm" data-cities-url="{% url 'users:ajax_load_cities' %}" novalidate>
{% csrf_token %}
<fieldset class="form-group">
<legend class="mb-4">Church Info</legend>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.area|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.country|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.name|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.city|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.email|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.website|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ form.address|as_crispy_field }}
</div>
<div class="form-group col-md-3 small">
{{ form.phone|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3 small">
{{ date_posted }}
</div>
<div class="form-group col-md-3 small">
{{ author }}
</div>
</div>
<div class="form-group">
<button style="border-radius: 0; width: 200px; padding-left: 4px;" class="btn btn-info btn-block" type="submit">Submit</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_area").change(function () {
var url = $("#personForm").attr("data-cities-url");
var areaId = $(this).val();
$.ajax({
url: url,
data: {
'area': areaId
},
success: function (data) {
$("#id_country").html(data);
}
});
});
</script>
{% endblock %}
Here is my forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth import get_user_model
from .models import Profile, Post, User, Country
class UserCreationModelForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'country', 'city', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
username = forms.CharField()
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'country', 'city', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('name', 'area', 'country', 'city', 'address', 'email', 'phone', 'website')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['country'].queryset = Country.objects.none()
if 'area' in self.data:
try:
area_id = int(self.data.get('area'))
self.fields['country'].queryset = Country.objects.filter(area_id=area_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['country'].queryset = self.instance.area.country_set.order_by('name')

Categories

Resources