Django CRUD :Update function is not working - python

I made CRUD in django. Update is not working while creating and deleting views are working.Please fix my problem.And tell me where i am lacking.
This is views.py:
from .import models
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render
from .forms import readerRegistrationForm
from .models import Reader, books
from django.views.generic import TemplateView,RedirectView,UpdateView
from django.views import View
# Create your views here.
def done(request):
return render(request,'done.html')
class addshowView(TemplateView):
template_name='add&show.html'
def get_context_data(self,*args,**kwargs):
context= super().get_context_data(**kwargs)
fm=readerRegistrationForm()
stu=Reader.objects.all()
cone=books.objects.all()
context={'str':stu,'form':fm,'con':cone}
return context
def post(self,request):
fm=readerRegistrationForm(request.POST)
if fm.is_valid():
fm.save()
return HttpResponseRedirect('/')
class userdeleteview(RedirectView):
url='/'
def get_redirect_url(self, *args, **kwargs):
p=kwargs['id']
Reader.objects.get(pk=p).delete()
return super().get_redirect_url(*args, **kwargs)
class Updateview(UpdateView):
def get(self,request,id):
pi=Reader.objects.get(pk=id)
fm=readerRegistrationForm(instance=pi)
return render(request,'updateit.html',{'form':fm})
def post(self,request,id):
pi=Reader.objects.get(pk=id)
fm=readerRegistrationForm(request.POST,instance=pi)
if fm.is_valid():
fm.save()
return render(request,'updateit.html',{'form':fm})`
This is forms.py:
from django.forms import fields, widgets
from .models import books,Reader
class readerRegistrationForm(forms.ModelForm):
class Meta:
model=Reader
fields=['name','email','comment']
this is models.py:
from django.db.models.deletion import CASCADE
#Create your models here.
class books(models.Model):
name=models.CharField(max_length=200)
gener=models.CharField(max_length=200)
author=models.CharField(max_length=200)
isbn=models.BigIntegerField()
def __str__(self) :
return self.name
class Reader(models.Model):
name=models.CharField(max_length=200)
email=models.EmailField(max_length=200)
comment=models.TextField()
def __str__(self) :
return self.comment
This is urls.py:
from django.contrib import admin
from django.urls import path
from boom import views
urlpatterns = [
path('', views.addshowView.as_view() , name='show'),
path('updated/',views.done,name='done'),
path('delete/<int:id>/', views.userdeleteview.as_view() , name='doNow'),
path('update/<int:id>/', views.Updateview.as_view() , name='UpNow'),
path('admin/', admin.site.urls),
]
This is updateit.html
{% extends 'index.html' %}
{% block body_block %}
<div class="container">
<h1>Welcome to Reader Update Page!!</h1>
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<button type="button" class="btn btn-success">Update</button>
</form>
</div>
{% endblock %}
this is index.html
<!DOCTYPE html>
{%load static%}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Base</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="alert alert-danger" role="alert">
<div class="blockquote text-center"><h1 class="alert">Welcome!!</h1>
<h1>This is My Virtual Book Stall!</h1>
</div>
</div>
<div class="jumbotron">
{% block body_block %}
{% endblock %}
</div>
</div>
</body>
</html>
This is add&show.html
{% extends 'index.html' %}
{% block body_block %}
<div style="text-align: center;">
<h1 class="alert alert-secondary" role="alert"><em>This is The Library U can Grab!!</em></h1>
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Author</th>
<th>Gener</th>
</tr>
</thead>
<tbody>
{% for st in con %}
<tr>
<th>{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.author}}</td>
<td>{{st.gener}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<form method="POST" class="table table-primary">
{% csrf_token %}
<div class="row justify-content-between">
<div class="col-4">
<h3 class="alert alert-secondary" role="alert">Add member</h3>
{{form.as_p}}
<input class="btn btn-primary" type="submit" value="Register">
</div>
<div class="col-8">
<h3 style="text-align: center;" class="alert alert-secondary" role="alert">Show Data</h3>
{% if str %}
<table class="table ">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col"><strong>Name</strong> </th>
<th scope="col"><strong> Email</strong></th>
<th scope="col"><strong> Comment</strong></th>
<th scope="col"><strong> Action</strong></th>
</tr>
</thead>
<tbody>
{% for st in str %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.comment}}</td>
<td><button type="button" class="btn btn-success">Edit</button>
<button type="button" class="btn btn-danger">Delete</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<h3>NO RECORDS NOW</h3>
{% endif %}
</div>
</div>
</form>
{% endblock %}
This is done.html
{% extends 'index.html' %}
{% block body_block %}
<div class="jumbotron">
<h3>Information updated Successfully!!</h3>
Click Me
</div>
{% endblock %}

You don't need to use two functions separately for update.
Use this:
class Updateview(UpdateView):
def update(request, pk):
pi=Reader.objects.get(pk=id)
fm = readerRegistrationForm(instance=pi)
if request.method == 'POST':
fm = readerRegistrationForm(request.POST, instance=pi)
if fm.is_valid:
fm.save()
return redirect('home')
context = {'form':fm}
return render(request,'updateit.html', context )

Related

'Posts_update' object is not iterable in django

i am just try to get data from db table and show on detail page but i am getting error -'Posts_update' object is not iterable.
I have two tables posts and posts_update. in posts table i am doing CRUD operation and on each update i am adding information in posts_update table now i am trying to get information from posts_update table using mobile as a parameter but i am getting error -'Posts_update' object is not iterable.
models.py
from django.db import models
class Posts(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
content = models.TextField()
mobile = models.CharField(max_length=15,default='')
class Posts_update(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
content = models.TextField()
mobile = models.CharField(max_length=15,default='')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('create/', views.create, name='create'),
path('detail/<int:post_mobile>', views.read, name='detail'),
path('delete/<int:post_id>', views.delete, name='delete'),
path('update/<int:post_id>', views.update, name='update')
]
views.py
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify
from django.http import HttpResponse
from django.contrib import messages
from .models import Posts
from .models import Posts_update
def index(request):
posts = Posts.objects.all()
return render(request, 'index.html', {
'posts': posts
})
def create(request):
if request.POST:
req = request.POST
post = Posts(title=req.get('title'), slug=slugify(req.get('title')), content=req.get('content'), mobile=req.get('mobile'))
post.save()
messages.success(request, 'The record was saved successfully')
return redirect('/')
else:
return render(request, 'create.html')
def update(request, post_id):
if request.POST:
req = request.POST
post = Posts.objects.get(id=post_id)
post.title = req.get('title')
post.slug = slugify(req.get('title'))
post.content = req.get('content')
post.mobile = req.get('mobile')
post.save()
post = Posts_update(title=req.get('title'), slug=slugify(req.get('title')), content=req.get('content'), mobile=req.get('mobile'))
post.save()
messages.success(request, 'The record was saved successfully')
return redirect('/')
else:
post = Posts.objects.get(id=post_id)
return render(request, 'update.html', {
'id': post.id,
'title': post.title,
'slug': post.slug,
'content': post.content,
'mobile': post.mobile
})
def read(request, post_mobile):
post = Posts_update.objects.get(mobile=post_mobile)
# post = Posts_update.objects.all()
return render(request, 'detail.html', {
'Posts_update': Posts_update
})
def delete(request, post_id):
post = Posts.objects.get(id=post_id)
post.delete()
messages.success(request, 'The record was deleted successfully')
return redirect('/')
detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crud Django - {{ title }}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
{% block content %}
<body>
<div class="container">
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h2 class="display-6">Detail post</h2>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">title</th>
<th scope="col">slug</th>
<th scope="col">content</th>
<th scope="col">Mobile</th>
</tr>
</thead>
<tbody>
{% if Posts_update %}
{% for post in Posts_update %}
<tr>
<td>{{ post.id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.slug }}</td>
<td>{{ post.content }}</td>
<td>{{ post.mobile }}</td>
{% endfor %}
{% else %}
<tr>
<td colspan="5">No records found</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
Back
</div>
</div>
</div>
</body>
{% endblock %}
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crud Django</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h2 class="display-6">All Posts</h2>
Create post
{% if messages %}
{% for message in messages %}
<div class="alert alert-success mt-3 alert-dismissible fade show">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
<div class="table-responsive mt-3">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">title</th>
<th scope="col">slug</th>
<th scope="col">content</th>
<th scope="col">Mobile</th>
<th scope="col">action</th>
</tr>
</thead>
<tbody>
{% if posts %}
{% for post in posts %}
<tr>
<td>{{ post.id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.slug }}</td>
<td>{{ post.content }}</td>
<td>{{ post.mobile }}</td>
<th>
Delete
Detail
Update
</th>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="5">No records found</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.5.4/dist/umd/popper.min.js" integrity="sha384-q2kxQ16AaE6UbzuKqyBE9/u/KzioAlnx2maXQHiDX9d4/zp8Ok3f+M7DPm+Ib6IU" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script>
</body>
</html>
In detail.html you are iterating over context object Posts_update
{% for post in Posts_update %}
Which is just Posts_update model, due to views.py.
I guess you meant the post variable there.

Can't access UpdateView in Django

UPDATE(enter image description here I have added backslash to the url and new error comes out )
My idea is to have Teachers and Students and I want my Teachers to have the ability to edit quizzes for the students for some reason when I try to acces the QuizUpdateView via other ListView it gives me 404 Not Found screenshot
So I want to edit my quiz with this view:
class QuizUpdateView(views.UpdateView):
model = Quiz
fields = ('name', 'subject', )
context_object_name = 'quiz'
template_name = 'classroom/quiz_update.html'
def get_context_data(self, **kwargs):
kwargs['questions'] =
self.get_object().questions.annotate(answers_count=Count('answers'))
return super().get_context_data(**kwargs)
def get_queryset(self):
return self.request.user.quizzes.all()
def get_success_url(self):
return reverse_lazy('quizzes')
I have int:pk in my urls.py
urlpatterns = (
path('register', RegisterView.as_view(), name='register'),
path('register/student', StudentRegisterView.as_view(), name='register student'),
path('register/register', TeacherRegisterView.as_view(), name='register teacher'),
path('login', LoginView.as_view(), name='login'),
path('logout', LogoutView.as_view(), name='logout'),
path('quizzes', QuizListView.as_view(), name='quizzes'),
path('quiz/create', QuizCreateView.as_view(), name='create quiz'),
path('quiz/update/<int:pk>', QuizUpdateView.as_view(), name='update quiz'),
)
I have the quiz.pk in templates as well(I tried with quiz.id, same result)
{% extends 'base.html' %}
{% block page_content %}
{% include 'classroom/student_header.html' with active='new' %}
<div class="card">
<table class="table mb-0">
<thead>
<tr>
<th>Quiz</th>
<th>Subject</th>
<th>Length</th>
<th></th>
</tr>
</thead>
<tbody>
{% for quiz in quizzes %}
<tr>
<td class="align-middle">{{ quiz.name }}</td>
<td class="align-middle">{{ quiz.subject.get_html_badge }}</td>
<td class="align-middle"> questions</td>
<td class="text-right">
{% if request.user.type == 'Student' %}
Start quiz
{% elif request.user.type == 'Teacher' %}
<a href="{% url 'update quiz' quiz.pk %}" class="btn btn-
warning">Edit quiz</a>
Delete quiz
{% endif %}
</td>
</tr>
{% empty %}
<tr>
<td class="bg-light text-center font-italic" colspan="4">No exam
matching your interests right
now.
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
Here is the model
class Quiz(models.Model):
owner = models.ForeignKey(UniversityUser, on_delete=models.CASCADE,
related_name='quizzes')
name = models.CharField(max_length=QUIZ_NAME_MAX_LENGTH, unique=True)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE,
related_name='quizzes')
def __str__(self):
return self.name
And here is the template I am using for the UpdateView:
{% extends 'base.html' %}
{% block page_content %}
<h2 class="mb-3">
{{ quiz.name }}
<a href="{% url 'teachers:quiz_results' quiz.pk %}" class="btn btn-primary float-
right">View results</a>
</h2>
<div class="row mb-3">
<div class="col-md-6 col-sm-8 col-12">
<form method="post" action="{% url 'update quiz' quiz.pk %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-success">Save changes</button>
<a href="{% url 'quizzes' %}" class="btn btn-outline-secondary"
role="button">Nevermind</a>
Delete
</form>
</div>
</div>
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-10">
<strong>Questions</strong>
</div>
<div class="col-2">
<strong>Answers</strong>
</div>
</div>
</div>
<div class="list-group list-group-flush list-group-formset">
{% for question in questions %}
<div class="list-group-item">
<div class="row">
<div class="col-10">
{{ question.text }}
</div>
<div class="col-2">
{{ question.answers_count }}
</div>
</div>
</div>
{% empty %}
<div class="list-group-item text-center">
<p class="text-muted font-italic mb-0">You haven't created any
questions yet. Go ahead and add the first question.</p>
</div>
{% endfor %}
</div>
<div class="card-footer">
Add question
</div>
</div>
{% endblock %}
If you have any ideas why this is happening please leave a comment thanks! :)
i'm not sure but is that class you inherit from is right?
try to import :
from django.views.generic.edit import UpdatView
class QuizUpdateView(UpdateView):

Django can't upload file

I'm doing a django app with a form using image file upload. I have a default image in case user doesnt choose an image. But when I save the form, my image isn't saved in my files. Any idea ?
Here's my code :
First my views.py
class AnimalCreateView(generic.CreateView):
model = Animal
form_class = AnimalForm
template_name = 'myApp/animal_create.html'
success_url = reverse_lazy('animal:index')
Then my models.py
class Animal(models.Model):
name= models.CharField()
animal_photo= models.ImageField(upload_to="images/",default="images/noPhoto.svg", null=False, blank=True)
def __str__(self):
return f'{self.name}'
And my animal_create html :
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-lg-8 offset-lg-2">
<h4>My anmials</h4>
<table class="table">
<thead>
<tr>
<th> </th>
<th>Name</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
{% for animal in animal_list%}
<tr>
<td>{{animal.name}}</td>
<p> {{ animal.photo.url }} </p> #check url file
<td class="picture-thumb">
{% if animal.photo.url %}
<img src="{{ animal.photo.url}}"" />
{% else %}
<img src="{% static 'images/noPhoto.svg' %}" />
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock content %}
When I save my file and then check my html or django admin page, all the rows of animal_photo are using the default file...
Where are you using form from context? And also, to upload an images(files) you need to set
{% if form.is_multipart %}
<form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
<form method="post" action="/foo/">
{% endif %}
https://docs.djangoproject.com/en/3.1/ref/forms/api/#testing-for-multipart-forms

filter posts based on a particular field in django template

I am working on a django application. The application holds a form which when filled will redirect to item_list page where the user can view the item they posted and also delete the item. I want this page to list only the items posted by that particular user who is currently logged in. but right now, this page lists items by every user. I tried adding an if case to the template but this results in displaying none of the posts. what am I doing wrong? this is my code so far
items_list template
{% extends 'base.html' %}
{% load staticfiles %}
{% block title %} items {% endblock title %}
{% block header %}
<link rel="stylesheet" href="{% static 'css/item_list.css' %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/item_list.js' %}"></script>
{% endblock header %}
{% block content %}
<div class="container">
<center><h2>Items</h2></center>
<table class='table table-borderless table-hover'>
<thead>
<tr>
<th>Image</th>
<th>Title</th>
<th>Pattern</th>
<th>Color</th>
<th>Vendor</th>
<th>Upload date</th>
<th>Time</th>
<th></th>
<th></th>
</tr>
</thead>
{% for item in items %}
{% if request.user == item.vendor %}
<tr>
<td>
<img src="{{item.img.url}}" alt="{{item.title}}" style="width:80px;">
</td>
<td>{{item.title}}</td>
<td>{{item.pattern}}</td>
<td>{{item.color}}</td>
<td>{{item.vendor}}</td>
<td>{{item.date}}</td>
<td>{{item.time}}</td>
{% endif %}
<td>
Edit item
</td>
<td>
<button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal" style="width:100px">Delete item</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="card-header"><center><h5 class="modal-title">Are you sure you want to delete this item?</h5></center></div>
<div class="modal-body" style="height:200px">
<center>
<br>
<form method="post" action="{% url 'delete_item' item.pk %}" style="margin-top:10%;">
{% csrf_token %}
<button type='submit' class="btn btn-danger" style="width:200px">Delete item</button>
<button type="button" class="btn btn-outline-primary" data-dismiss="modal" style="width:200px">Cancel</button>
</form>
</center>
</div>
<div class="card-footer text-muted">
<center>Once an item is deleted, It cannot be retrieved</center>
</div>
</div>
</div>
</div>
</td>
I am trying to filter the items based on request.user and item.vendor. But this displays none of the items.
views.py
def upload_item(request):
if request.method == 'POST':
form_des = ItemForm(request.POST, request.FILES)
if form_des.is_valid():
form_des.save()
return redirect('item_list')
else:
form_des = ItemForm()
form_des.fields['vendor'].widget.attrs['value'] = request.user
form_des.fields['vendor'].widget.attrs['readonly'] = True
return render(request, 'upload_item.html', {'form_des': form_des})
def item_list(request):
items = Item.objects.all()
return render(request, 'item_list.html', {'items':items})
under upload_item function in views.py, I have made the vendor field readonly and autofilled to the user posting the item so that it cannot be changed.
What am I doing wrong? Please help me
Thank you
You should do the filtering in your view:
def item_list(request):
items = Item.objects.filter(vendor=request.user)
return render(request, 'item_list.html', {'items':items})

How do I fix my Createview in Django

I am trying to make a business card manager using django python but I don't why my business card is not being added. When I press the button "Add business Card", it goes to the BusinessCardListView but it is blank. I also want to know how to make the delete and update button work on the Business Card List. I think I have to add a primary key in the model but I don't know how to pass it correctly.
Views
from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views.generic import View
from .models import BusinessInfo
class BusinessCardListView(generic.ListView):
model = BusinessInfo
template_name = 'manager/BusinessCardList.html'
context_object_name = 'all_business_cards'
def get_queryset(self):
return BusinessInfo.objects.all()
class BusinessCardCreate(CreateView):
model = BusinessInfo
fields = ['card', 'company_name', 'phone_number', 'website', 'representative_name', 'branch_address', 'job_title',
'fax_number', 'cell_phone_number', 'email']
class BusinessCardUpdate(UpdateView):
model = BusinessInfo
fields = ['card', 'company_name', 'phone_number', 'website', 'representative_name', 'branch_address', 'job_title',
'fax_number', 'cell_phone_number', 'email']
class BusinessCardDelete(DeleteView):
model = BusinessInfo
success_url = reverse_lazy('manager:index')
Add Business Card form
{% extends 'manager/base.html' %}
{% block title %}Add a New Business Card{% endblock %}
{% block albums_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="{% url 'manager:index' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'manager/form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add Business Card</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
form_template
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.error }}</span>
</div>
<label class="control-label col-sm-2">{{ field.label_tag }}</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
urls
from django.conf.urls import url
from . import views
app_name = 'manager'
urlpatterns = [
url(r'^$', views.BusinessCardListView.as_view(), name='index'),
url(r'business_card/add/$', views.BusinessCardCreate.as_view(), name='business_card-add'),
url(r'business_card/(?P<pk>[0-9]+)/edit/$', views.BusinessCardUpdate.as_view(), name='edit'),
url(r'business_card/(?P<pk>[0-9]+)/delete/$', views.BusinessCardDelete.as_view(), name='delete'),
]
models
from django.db import models
from django.core.urlresolvers import reverse
# Business Card Info
class BusinessInfo(models.Model):
card = models.FileField(default='Picture')
company_name = models.CharField(max_length=100000, primary_key=True)
website = models.CharField(max_length=100000)
representative_name = models.CharField(max_length=100000)
branch_address = models.CharField(max_length=100000)
job_title = models.CharField(max_length=10000)
email = models.EmailField()
phone_number = models.CharField(max_length=100000)
fax_number = models.CharField(max_length=100000)
cell_phone_number = models.CharField(max_length=100000)
def get_absolute_url(self):
return reverse('manager:index')
def __str__(self):
return self.company_name + ':' + self.representative_name
Business Card List
{% extends 'manager/Base.html' %}
{% block body %}
<style>
table, th, .Info {
border: 1px solid black;
border-collapse: collapse;
text-align: center;
}
</style>
<table style="width:100%">
<tr>
<th>Business Card</th>
<th>Company Name</th>
<th>Representative Name</th>
<th>Job Title</th>
<th>Branch Address</th>
<th>Website</th>
<th>Phone Number</th>
<th>Cell Phone Number</th>
<th>Email</th>
<th>Fax Number</th>
</tr>
{% for businessinfo in all_business_cards %}
<tr>
<td class="Info">{{ businessinfo.card }}</td>
<td class="Info">{{ businessinfo.company_name }}</td>
<td class="Info">{{ businessinfo.representative_name }}</td>
<td class="Info">{{ businessinfo.job_title }}</td>
<td class="Info">{{ businessinfo.branch_address }}</td>
<td class="Info">{{ businessinfo.website }}</td>
<td class="Info">{{ contactinfo.phone_number }}</td>
<td class="Info">{{ contactinfo.cell_phone_number }}</td>
<td class="Info">{{ contactinfo.email }}</td>
<td class="Info">{{ contactinfo.fax_number }}</td>
<td>
<form action="{% url 'music:delete' %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="company_name" value="{{ company_name }}"/>
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
The action attribute in your form tag inside the Business Card Create form template is {% url 'manager:index' %} which points to the BuisinessCardListView thats why it is taking you to the list view on submit.
To achieve what you want it should point the CreateView url, like this:
{% extends 'manager/base.html' %}
{% block title %}Add a New Business Card{% endblock %}
{% block albums_active %}active{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="{% url 'manager:business_card-add' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'manager/form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Add Business Card</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

Categories