Method Not Allowed (POST) in Django 3.1 - python-3.x

I am new to Django. Practicing in a small project in Dango 3.1 I get the error "Method Not Allowed (POST)".
The error appears when a user presses the Guarder (Save) button.
Method Not Allowed: /pizarra/comunicado/
[30/Jul/2021 09:10:03] "POST /pizarra/comunicado/ HTTP/1.1" 405 0
Everything was working before and I can't understand what I'm doing wrong.
Please if someone can help me.
Thanks in advance.
comunicado_form.html
{% extends 'gestion/base_gestion.html' %}
{% block page_content %}
<form method="POST" class="form-group">
{% csrf_token %}
<div class="col-xl-12 col-md-12 mb-12">
{% if obj %}
<div class="card border-left-warning shadow h-100 py-2">
{% else %}
<div class="card border-left-success shadow h-100 py-2">
{% endif %}
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-success text-uppercase mb-1">
{% if obj %}Editar{% else %}Nuevo{% endif %} Comunicado
</div>
<div class="dropdown-divider"></div>
<div class="col-sm-8">
<div class="col-8">
<div class="form-group">
<label for="id_contenido">Contenido del mensaje:</label>
{{ form.contenido }}
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="id_fecha_vto">Fecha Vto:</label>
{{ form.fecha_vto }}
</div>
</div>
<div class="col-2">
<div class="form-group">
<label for="id_hora_vto">Hora Vto:</label>
{{ form.hora_vto }}
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="id_es_borrador">¿Es Borrador?:</label>
{{ form.es_borrador }}
</div>
</div>
<div class="col-2">
<div class="form-group">
<label for="id_es_borrador">Estado:</label>
{{ form.estado }}
</div>
</div>
<!-- {{ form.as_p }} -->
</div>
<div class="dropdown-divider"></div>
<div class="row">
<div class="col">
<button type="submit" class="btn btn-danger"><span class="fa fa-save"></span> Guardar</button>
<span class="fa fa-undo"></span> Cancelar
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
{% endblock page_content %}
{% block js_page %}
<script>
$(function () {
$("#id_fecha_vto").datetimepicker({
format: 'd-m-Y',
timepicker:false
});
});
$(function () {
$("#id_hora_vto").datetimepicker({
format: 'H:i',
datepicker:false
});
});
</script>
{% endblock js_page %}
urls.py in app
from django.contrib import admin
from django.urls import path, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from blogapp import views
# agregamos estas dos lineas
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('blogapp/',include(('blogapp.urls','blogapp'), namespace='blogapp')),
path('pizarra/', include(('pizarra.urls','pizarra'), namespace='pizarra')),
path('home',include(('blogapp.urls','home'), namespace='home')),
path('login/',auth_views.LoginView.as_view(template_name='blogapp/login.html'),
name='login'),
path('', views.index),
]
urlpatterns += staticfiles_urlpatterns()
urls.py in pizarra
from django.urls import path
from .views import ComunicadoNew, ComunicadoEdit, ComunicadoDel, ComunicadoView
urlpatterns = [
#-------------------- PIZARRA (Comunicados)---------------------------
path('comunicado/',ComunicadoView.as_view(), name='comunicado_list'),
path('comunicado/new',ComunicadoNew.as_view(), name='comunicado_new'),
path('comunicado/edit/<int:pk>',ComunicadoEdit.as_view(), name='comunicado_edit'),
path('comunicado/delete/<int:pk>',ComunicadoDel.as_view(), name='comunicado_del'),
]
views.py in pizzarra
from django.shortcuts import render, redirect
from django.views import generic
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Comunicado
from .forms import ComunicadoForm
# Create your views here.
class ComunicadoView(LoginRequiredMixin,generic.ListView):
model = Comunicado
template_name = "pizarra/comunicado_list.html"
context_object_name = "obj"
login_url = 'blogapp:login'
class ComunicadoNew(LoginRequiredMixin,generic.CreateView):
model = Comunicado
template_name = "pizarra/comunicado_form.html"
context_object_name = "obj"
form_class=ComunicadoForm
success_url=reverse_lazy("pizarra:comunicado_list")
login_url="blogapp:login"
def form_valid(self, form):
form.instance.uc = self.request.user
return super().form_valid(form)
I have defined the static / js as follows:
<!-- Custom fonts for this template-->
<link href="{% static 'blogapp/vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<!-- Custom styles for this template-->
<link href="{% static 'blogapp/css/sb-admin-2.min.css' %}" rel="stylesheet">
<!-- Custom styles for this page -->
<link href="{% static 'blogapp/vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet">
<!-- jquery-confirm -->
<link href="{% static 'blogapp/vendor/jquery_confirm/jquery-confirm.min.css' %}" rel="stylesheet">
<!-- XDSoft DateTimePicker -->
<!-- <link rel="stylesheet" href="{% static 'blogapp/vendor/jquery-datetimepicker/jquery.datetimepicker.min.css" type="text/css"> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.min.css" integrity="sha256-DOS9W6NR+NFe1fUhEE0PGKY/fubbUCnOfTje2JMDw3Y=" crossorigin="anonymous" />
and
<!-- Bootstrap core JavaScript-->
<script src="{% static 'blogapp/vendor/jquery/jquery.min.js' %}"></script>
<script src="{% static 'blogapp/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<!-- Core plugin JavaScript-->
<script src="{% static 'blogapp/vendor/jquery-easing/jquery.easing.min.js' %}"></script>
<!-- Custom scripts for all pages-->
<script src="{% static 'blogapp/js/sb-admin-2.min.js' %}"></script>
<!-- Page level plugins -->
<script src="{% static 'blogapp/vendor/datatables/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'blogapp/vendor/datatables/dataTables.bootstrap4.min.js' %}"></script>
<script src="{% static 'blogapp/vendor/jquery_confirm/jquery-confirm.min.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js" integrity="sha256-FEqEelWI3WouFOo2VWP/uJfs1y8KJ++FLh2Lbqc8SJk=" crossorigin="anonymous"></script>

Related

ValueError: "<User: harry1>" needs to have a value for field "id" before this many-to-many relationship can be used in Django

I need help with Django web Framework I cannot solve this problem or I cannot identify the source of the problem. Please help me with this problem the main problem is written in the title.
Here is my traceback for the error:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Documents\CodingFox\CodingFox_final\CodingFox\Users\views.py", line 37, in registeration_form
form.save()
File "D:\Documents\CodingFox\CodingFox_final\CodingFox\Users\forms.py", line 18, in save
user = super().save(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\forms.py", line 131, in save
user.save()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py", line 536, in __get__
return self.related_manager_cls(instance)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py", line 851, in __init__
raise ValueError('"%r" needs to have a value for field "%s" before '
ValueError: "<User: harry1>" needs to have a value for field "id" before this many-to-many relationship can be used.
Models.py file
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
import cv2
class Profile(models.Model):
user =models.OneToOneField(User, on_delete=models.CASCADE)
cover_img = models.ImageField(default='default.png',upload_to='cover_pics')
image = models.ImageField(default='default.jpg',upload_to='profile_pics')
# bio = models.TextField()
def __str__(self):
return f'{self.user.username} Profile'
def save(self ,*args, **kwargs):
super(Profile, self).save( *args, **kwargs)
img = cv2.imread(self.image.path)
output_size = cv2.resize(img,(300,300))
cv2.imwrite(self.image.path, output_size)
Forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.forms import models
from .models import Profile
class UserRegistrationForm(UserCreationForm):
email=forms.EmailField(required=False)
class Meta:
model = User
fields = ['username','email','password1','password2']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['cover_img','image']
class UserLoginForm(AuthenticationForm):
class Meta:
model = User
fields = ['username','password']
Base.html
{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
{% endblock head %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="title" content="CodingFox: Pre Written Code snippets">
<meta name="description"
content="CodingFox can enhance the speed of programming by giving them pre-written code snippets.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://CodingFox.com/">
<meta property="og:title" content="CodingFox: Pre Written Code snippets">
<meta property="og:description"
content="CodingFox can enhance the speed of programming by giving them pre-written code snippets.">
<meta property="og:image" content="resoures/img/For_website.png">
<meta property="twitter:card" content="summary_large_image">
<meta property="twitter:url" content="https://CodingFox.com/">
<meta property="twitter:title" content="CodingFox: Pre Written Code snippets">
<meta property="twitter:description"
content="CodingFox can enhance the speed of programming by giving them pre-written code snippets.">
<meta property="twitter:image" content="resoures/img/For_website.png">
<link rel="stylesheet" href="{% static 'vendors/css/1.3 grid.css.css' %}">
<link href="https://unpkg.com/ionicons#4.5.10-0/dist/css/ionicons.min.css" rel="stylesheet">
<link rel="stylesheet" href="{% static 'vendors/css/normalize.css' %}">
<link rel="stylesheet" href="{% static 'vendors/css/prism-1.css' %}">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:wght#100;300;400;700;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="apple-touch-icon" sizes="57x57" href="{% static 'favicon/apple-icon-57x57.png' %}">
<link rel="apple-touch-icon" sizes="60x60" href="{% static 'favicon/apple-icon-60x60.png' %}">
<link rel="apple-touch-icon" sizes="72x72" href="{% static 'favicon/apple-icon-72x72.png' %}">
<link rel="apple-touch-icon" sizes="76x76" href="{% static 'favicon/apple-icon-76x76.png' %}">
<link rel="apple-touch-icon" sizes="114x114" href="{% static 'favicon/apple-icon-114x114.png' %}">
<link rel="apple-touch-icon" sizes="120x120" href="{% static 'favicon/apple-icon-120x120.png' %}">
<link rel="apple-touch-icon" sizes="144x144" href="{% static 'favicon/apple-icon-144x144.png' %}">
<link rel="apple-touch-icon" sizes="152x152" href="{% static 'favicon/apple-icon-152x152.png' %}">
<link rel="apple-touch-icon" sizes="180x180" href="{% static 'favicon/apple-icon-180x180.png' %}">
<link rel="icon" type="image/png" sizes="192x192" href="{% static 'favicon/android-icon-192x192.png' %}">
<link rel="icon" type="image/png" sizes="32x32" href="{% static 'favicon/favicon-32x32.png' %}">
<link rel="icon" type="image/png" sizes="96x96" href="{% static 'favicon/favicon-96x96.png' %}">
<link rel="icon" type="image/png" sizes="16x16" href="{% static 'favicon/favicon-16x16.png' %}">
<link rel="manifest" href="{% static 'favicon/manifest.json' %}">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="{% static 'favicon/ms-icon-144x144.png' %}">
<meta name="theme-color" content="#ffffff">
<script src="{% static 'vendors/js/prism-1.js' %}"></script>
</head>
<body>
<nav>
<img src="{% static 'resoures/img/For_website.png' %}" alt="Logo_img" />
<div class="ion-md-menu nav_icon" id="nav_clickable"></div>
{% if user.is_authenticated %}
<div class="nav_icon-link">New Post</div>
<div class="nav_icon-link"><span class="ion-md-search"></span></div>
{% else %}
<div class="nav_icon-link">Login</div>
<div class="nav_icon-highlight">Register</div>
{% endif %}
<div class="clearfix"></div>
<div class="nav_box" id="nav_box">
{% if user.is_authenticated %}
<a href="" class="nav_box-link--person_img"><img src="{{ user.profile.image.url }}" alt="person-img"
srcset="" /></a>
<span class="ion-md-home"></span> {{ user.username }}
{% else %}
{% comment %} Unknown {% endcomment %}
{% endif %}
<span class="ion-md-moon"></span> Theme
<div class="nav_box-theme_box" id="theme_box">
<p>Change the color scheme to Dark colors.</p>
<h4>Toggle Theme</h4>
<input type="checkbox" name="" id="nav_box-theme_box-checkbox" />
</div>
<span class="ion-md-code"></span> Languages
<ul class="nav_box_language_box" id="lang_box">
<li>
<span class="ion-logo-html5"> HTML</span>
</li>
<li>
<span class="ion-logo-css3"> CSS</span>
</li>
<li>
<span class="ion-logo-python"> Python</span>
</li>
<li>
<span class="ion-logo-javascript"> JavaScript</span>
</li>
</ul>
{% if user.is_authenticated %}
<span class="ion-md-options"></span> Settings
<span class="ion-md-save"></span> Saved Posts
{% comment %} <span class="ion-md-home"></span> Home {% endcomment %}
<hr />
<span class="ion-md-log-out"></span> Log out
{% else %}
<span class="ion-md-log-in"></span> Login
<hr />
<span class="ion-md-person-add"></span> Register
{% endif %}
</div>
</nav>
<div class="message-box">
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
{{ message }}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% block category %}
{% endblock category %}
{% block Post_loading %}
{% endblock Post_loading %}
{% block post %}
{% endblock post %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="{% static 'resoures/js/script.js' %}"></script>
<script src="{% static 'resoures/js/script-jquery.js' %}"></script>
<script src="{% static 'vendors/js/jquery.waypoints.min.js' %}"></script>
</body>
</html>
signup_form.html
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
<head>
{% block head %}
<title>CodingFox | Register</title>
<link rel="stylesheet" href="{% static 'resoures/css/login.css' %}" />
{% endblock head %}
</head>
<body>
{% block post %}
<form action="" method="post" class="signup_form">
{% csrf_token %}
<h1>Welcome New User!</h1>
{% comment %} <label for="signup_email">Email :</label>
<input type="email" name="email" id="email">
<label for="signup_username">Username :</label>
<input type="text" name="username" id="username">
<label for="signup_password">Password :</label>
<input type="password" name="password" id="password"> {% endcomment %}
{{ form|crispy }}
{% comment %} <h4>Forgot Password?</h4> {% endcomment %}
<input type="submit" value="Register">
<hr>
<p>Already have a account?</p>
Login
</form>
{% endblock post %}
</body>
Views.py
def registeration_form(request):
if request.method == 'POST':
form=UserRegistrationForm(request.POST)
if form.is_valid():
form.save()
username=form.cleaned_data.get('username')
messages.success(request,f'Account created for {username}!')
return redirect('login_page')
else:
form=UserRegistrationForm()
context = {
'title':'Register',
'form':form
}
return render(request,'signup_form.html',context)
Urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('register/',views.registeration_form, name='register_page'),
]
Can you please give me a solution? This thing just worked a week ago but it's giving errors now. It is also giving errors for creating Post.

ValueError at / save_data/

Cannot assign "'Electronic'": "Product.category" must be a "Category" instance.
File/models.py:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=150, db_index=True)
def __str__(self):
return self.name
class SubCategory(models.Model):
name = models.CharField(max_length=150, db_index=True)
category = models.ForeignKey(Category, related_name='souscatégories', on_delete=models.CASCADE)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100, db_index=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
def __str__(self):
return self.
and business logic code is there....
File/views.py
# from django.urls import reverse_lazy
# from django.views.generic import ListView, CreateView
from django.shortcuts import render
from .models import Product, Category, SubCategory
# Create your views here.
def home(request):
if request.method == "POST":
name = request.POST['name']
subcategory = request.POST['subcategory']
category = request.POST['category']
ins = Product(name=name, subcategory=subcategory, category=category)
ins.save()
data = Product.objects.all()
return render(request, 'mysiteapp/index.html', {'data': data})
and templates is there....
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Hello, world!</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Product List </a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<!-- Table -->
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Product</th>
<th scope="col">Subcategory</th>
<th scope="col">Category</th>
</tr>
</thead>
{% for p in data%}
<tbody>
<tr>
<th scope="row">{{p.id}}</th>
<td>{{p.name}}</td>
<td>{{p.subcategory}}</td>
<td>{{p.category}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<!-- modal -->
<!-- Button trigger modal -->
<h2><a class="btn btn-success" data-toggle="modal" data-target="#exampleModal">
Add Product
</a></h2>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!-- form -->
<form method="POST">{% csrf_token %}
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Product</label>
<div class="col-sm-8">
<input name="name" type="text" id="name" class="form-control mx-sm-2">
</div>
</div>
<div class="form-group row">
<label for="subcategory" class="col-sm-2 col-form-label">SubCategory</label>
<div class="col-sm-8">
<select name="subcategory" class="custom-select mr-sm-2" id="subcategory">
<option>Choose....</option>
{% for p in data %}
<option>{{p.subcategory}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group row">
<label for="category" class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-8">
<select name="category" class="custom-select mr-sm-2" id="category">
<option>Choose....</option>
{% for p in data %}
<option>{{p.category}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
and finally error is :
ValueError at /
Cannot assign "'Electronic'": "Product.category" must be a "Category" instance.
please answer me...
You cannot directly pass category from POST data.
Either it needs to be an instance of Category class
category_id = request.POST['category']
#Get category instance
category = Category.objects.get(pk=category_id)
ins = Product(name=name, subcategory=subcategory, category=category)
or you can use the category pk value.
ins = Product(name=name, subcategory=subcategory, category_id=category_id)

Django DetailView not displaying the content from the database

I am trying to develop a job portal where people can post jobs. I created a Listview and a DetailView for the application. The list view is working but the content isn't appearing on the details page.
views.py:
from django.shortcuts import render
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Application_create
# Create your views here.
class AllApps(ListView):
model = Application_create
template_name = 'fundamentals/allapps.html'
ordering = ['-id']
class ApplicationInDetail(DetailView):
model = Application_create
template_name = 'fundamentals/application_detail.html'
urls.py:
from django.urls import path
from .views import AllApps, ApplicationInDetail
urlpatterns = [
path('allappslist', AllApps.as_view(), name='applist'),
path('app_in_detail/<int:pk>', ApplicationInDetail.as_view(), name='application_detail')
]
models.py:
from django.db import models
from django.urls import reverse_lazy
# Create your models here.
class Application_create(models.Model):
application_title = models.CharField(max_length=500, default='')
application_opening = models.DateTimeField(auto_now=True)
application_closing = models.DateField()
application_description = models.TextField(default='')
company_name = models.CharField(max_length=500, default='')
skills_req = models.CharField(max_length=2000, default='')
job_pay = models.IntegerField(default=10000)
freelancing_pay = models.IntegerField(default=10000)
job_type = models.CharField(max_length=500)
def __str__(self):
return self.application_title + self.company_name
def get_absolute_url(self):
return reverse('application_detail', args = [str(self.id)])
base.html:
<html>
<head>
{% load static %}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link rel="stylesheet" href="{% static 'css/allappslist.css' %}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light navbar_custom">
<a class="navbar-brand" href="#">
<img src="{% static 'images/expertoblogo.png' %}" width="40" height="40" alt="">
</a>
<a class="navbar-brand" href="#" >EXPERTOB</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" style="background-color: white;">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item" style="margin-right: 15px;">
<a class="nav-link" href="#" >Link</a>
</li>
<li class="nav-item" style="margin-right: 15px;">
<a class="nav-link" href="#" >Link</a>
</li>
<li class="nav-item" style="margin-right: 15px;">
<a class="nav-link" href="#" >Link</a>
</li>
</ul>
</nav>
{% block content %}
{% endblock %}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
</body>
</html>
allapps.html:
{% extends 'fundamentals/base.html' %}
{% block content %}
{% for app in object_list %}
<ul>
<li class="list-group-item app_title" style="margin-left: 30px; margin-bottom: 0px; margin-right:30px; margin-top: 30px; background-color: #007FFF;">
<span style="color:white;"> {{app.application_title}} </span>
</li>
<li class="list-group-item list-group-item-light" style="margin-left: 30px; margin-bottom: 0px; margin-right:30px;">
<p>Company name: <span style="font-weight: bold;">{{app.company_name}} </span> </p>
</li>
<li class="list-group-item list-group-item-light" style="margin-left: 30px; margin-bottom: 0px; margin-right:30px;">
<p> {{app.application_description | slice:"0:200"}} ....... </p>
<p> <button type="button" class="btn btn-primary">View Details</button> </p>
</li>
</ul>
{% endfor %}
{% endblock %}
application_detail.html:
{% extends 'fundamentals/base.html' %}
{% block content %}
<h1> {{app.company_name}} </h1>
{% endblock %}
I've specified the model in views too but the content isn't appearing in the application_detail.html file. I'm using a mongo database which is working as the content is appearing in the allapps.html file. Please help me out
I think you must add context_object_name, change your code like below
class ApplicationInDetail(DetailView):
model = Application_create
template_name = 'fundamentals/application_detail.html'
context_object_name = 'app'
In your list view you have {% for app in object_list %}.
object_list is Django's default naming of the list of objects in your view.
In your detail view you use app, but this should be object as that is Django's default naming of the object in the detail view.
The documentation is here https://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-display/

ModuleNotFoundError: No module named 'bootstrap4'. python crash course

i am running into that error. at first i had bootstrap3 installed in my project directory. it was throwing the same error after some googling i saw some troubleshoots advising to install bootstrap4 still am facing the same error. i need help. Below is my code.
installing bootstrap4
pip install django-bootstrap4
settings.py
setting for bootstrap
bootstrap4 = {
'include_jquery':True,
}
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'learning_logs.apps.LearningLogsConfig',
'users',
'bootstrap4',
]
base.html
{% load bootstrap4 %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning Log</title>
{% bootstrap_css %}
{% bootstrap_javascript %}
</head>
<body>
<!--static navbar -->
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar"> </button>
<a class="navbar-brand" href="{% url 'index' %}"> Learning Log</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Topics</li>
</ul>
<ul class="nav navbar-nav navbar-right">
{% if user.is_authenticated %}
<li><a>Hello, {{ user.username }}.</a></li>
<li>log out</li>
{% else %}
<li>register</li>
<li>log in</li>
{% endif %}
</ul>
</div>
<!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="page-header">
{% block header %}{% endblock header %}
</div>
<div>
{% block content %}{% endblock content %}
</div>
</div> <!-- /container -->
</body>
</html>
There are different ways than what you are doing to access bootstrap, instead you could just add the bootstrap links as you would normally add them to html code like this:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
You could also just download the bootstrap files and link it into your static folder.

Jinja2 Child content not showing up

Thanks for the help!
So, I'm trying to create a simple layout with a Bootstrap nav-bar and a block of content on the body, and that works fine. But, when I extend that to a child, no matter what changes I make on the child, nothing shows up!
I'll post the two templates I'm using right now.
layout.html
<!doctype html>
{% extends "bootstrap/base.html" %}
<html>
<head>
<title>{% block title %}{% endblock %} </title>
</head>
<body>
{% block navbar %}
<nav class="navbar navbar-inverse navbar navbar-fixed-stop" role="navigation" style="border-radius:0px;">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand" href="#">BGP Monitor</a></div>
<ul class = "nav navbar-nav">
{% if g.user.is_authenticated %}
<li>Admin Panel</li>
{% endif %}
</ul>
<ul class="nav navbar-nav navbar-right">
{% if g.user.is_authenticated %}
<li><a href ="{{ url_for('logout') }}">Logout</li>
{% else %}
<li><a href ="{{ url_for('login') }}">Login</li>
{% endif %}
</ul>
</div>
</div>
</nav>
{% endblock %}
<div class="container-fluid" id="form">
{% block container %}{% endblock %}
</div>
</body>
</html>
And the child:
{% extends "layout.html" %}
<html>
<head></head>
<body>
<h3>aaa</h3>
{% block container %}
<div class="collapse navbar-collapse" id="container">
{{ super() }}
<form action="{{ url_for('login')}}" class="navbar-form navbar-right" method="POST">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.email(class="form-control", placeholder="Username") }}
</div>
<div class="form-group">
{{ form.password(class="form-control", placeholder="Password") }}
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Sign In</button>
</div>
</form>
</div>
</div>
{% endblock %}
</body>
The nav-bar shows, but the form doesn't show up, at all. It's as if the child does not exist.
Any ideas?
Thank you
P.S:
So, I changed to this:
layout.html
<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-inverse navbar navbar-fixed-stop" role="navigation" style="border-radius:0px;">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand" href="#">BGP Monitor</a></div>
<ul class = "nav navbar-nav">
{% if g.user.is_authenticated %}
<li>Admin Panel</li>
{% endif %}
</ul>
<ul class="nav navbar-nav navbar-right">
{% if g.user.is_authenticated %}
<li><a href ="{{ url_for('logout') }}">Logout</li>
{% else %}
<li><a href ="{{ url_for('login') }}">Login</li>
{% endif %}
</ul>
</div>
</div>
</nav>
<div class="container-fluid" id="container">
{% block container %}{% endblock %}
</div>
</body>
</html>
And this child:
{% extends "layout.html" %}
{% block container %}
<form action="{{ url_for('login')}}" class="navbar-form navbar-right" method="POST">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.email(class="form-control", placeholder="Username") }}
</div>
<div class="form-group">
{{ form.password(class="form-control", placeholder="Password") }}
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Sign In</button>
</div>
</form>
{% endblock %}
This way, there's no duplicate {% extend ... %}.
It now shows the form, but the WHOLE div is clickable, rendering it pretty much useless..
Any ideas?
You aren't supposed to have all the <html><head><body> tags in a child. It should just be:
{% extends "layout.html" %}
{% block container %}
<h3>aaa</h3>
<div class="collapse navbar-collapse" id="container">
{{ super() }}
<form action="{{ url_for('login')}}" class="navbar-form navbar-right" method="POST">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.email(class="form-control", placeholder="Username") }}
</div>
<div class="form-group">
{{ form.password(class="form-control", placeholder="Password") }}
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Sign In</button>
</div>
</form>
</div>
</div>
{% endblock %}
And notice how I moved the <h3>aaa</h3> code to inside the block.
Next, you can only have one {% extends ... %} call per rendering (You can't extend an extension). So, you need to consolidate your child to layout.html, making separate layouts per view.
Alternatively, you could change layout.html to use an include, keeping just one {% extends... %} per view:
layout.html
{% include "bootstrap/base.html" %}
{% block navbar %}
<nav class="navbar navbar-inverse navbar navbar-fixed-stop" role="navigation" style="border-radius:0px;">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand" href="#">BGP Monitor</a></div>
<ul class = "nav navbar-nav">
{% if g.user.is_authenticated %}
<li>Admin Panel</li>
{% endif %}
</ul>
<ul class="nav navbar-nav navbar-right">
{% if g.user.is_authenticated %}
<li><a href ="{{ url_for('logout') }}">Logout</li>
{% else %}
<li><a href ="{{ url_for('login') }}">Login</li>
{% endif %}
</ul>
</div>
</div>
</nav>
{% endblock %}
<div class="container-fluid" id="form">
{% block container %}{% endblock %}
</div>
Again, notice there are no duplicated <html> etc tags in layout.html. Those are already in bootstrap/base.html

Resources