So I made a form but after i clicked Submit button, it not redirected at all. I don't know if the form is actually submitted or not, because after i clicked submit, the url just added /submit, not even redirect to the right page.
Here's my views:
def submit_company_profile(request):
if request.session['status'] == "employer":
form = CompanyProfileEdit(request.POST or None)
if(request.method == 'POST' and form.is_valid()):
company_creator_profile_id = request.session['profile_id']
country = request.POST.get('country', False)
province = request.POST.get('province', False)
city = request.POST.get('city', False)
company_name = request.POST.get('company_name', False)
company_description = request.POST.get('company_description', False)
company_website = request.POST.get('company_website', False)
company_logo = request.POST.get('company_logo', False)
query = Company.objects.filter(company_creator_profile_id=request.session['profile_id'])
query_size = query.count()
if query_size > 0:
company = query[0]
company.country = country
company.province = province
company.city = city
company.company_name = company_name
company.company_description = company_description
company.company_website = company_website
company.company_logo = company_logo
company.save()
else:
Company.objects.create(
company_creator_profile_id=request.session['profile_id'],
country = country,
province = province,
city = city,
company_name = company_name,
company_description = company_description,
company_website = company_website,
company_logo = company_logo
)
return redirect(reverse('app_employer:company_profile'))
Here's my HTML
<form method="POST" action="{% url 'app-employer:submit-company-profile' %}">
{% csrf_token %}
{% for field in company_form %}
<div class="form-group">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{{field}}
</div>
{% endfor %}
<div class="upload">
<p><strong>Upload your company logo</strong></p>
<div class="row">
<div class="col-sm-4">
<button class="btn btn-block btn-default">Choose File</button>
</div>
<div class="col-sm-4">
<div class="text-file-name">
<p style="color:#999">No file chosen</p>
</div>
</div>
</div>
</div>
<div class="btn-padding-form">
<input id="submit" type="submit" class="btn btn-info btn-md btn-block" value="Submit">
</div>
</form>
The upload logo button can't be use yet. So i'm gonna submit form without uploading the logo.
Related
This question already has answers here:
The view didn't return an HttpResponse object. It returned None instead
(7 answers)
Closed last month.
ValueError at /update_department/14
The view management.views.update_department didn't return an HttpResponse object. It returned None instead.Also when added with return statement data is not updating.
Request information
USER
admin
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'XLqZBPhMKImvlfgWsNLeN1Ei8nz5u1HJ15IvAQV4JNwVMeG31rhDOD1q9PJuwXmz'
department_code
'15'
department_name_e
'Finance'
department_name_l
'Finance'
parent_code
''
submit
''
These are the details.I don't know why is there error here while all the posted data is right.also the form is not updating.
Models:
class Departments(models.Model):
department_code = models.CharField(db_column='Department_Code', primary_key= True, max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_e = models.CharField(db_column='Department_Name_E', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_l = models.CharField(db_column='Department_Name_L', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
parent_code = models.CharField(db_column='Parent_Code', max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
is_active = models.BooleanField(db_column='Is_Active') # Field name made lowercase.
created_by = models.IntegerField(db_column='Created_By') # Field name made lowercase.
created_date = models.DateTimeField(db_column='Created_date') # Field name made lowercase.
modified_by = models.IntegerField(db_column='Modified_By') # Field name made lowercase.
modified_date = models.DateTimeField(db_column='Modified_date') # Field name made lowercase.
class Meta:
db_table = 'Departments'
unique_together = (('department_code'),)
def __str__(self):
return str("self.department_name_e") or ''
View:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
department_code = form.cleaned_data['department_code']
department_name_e = form.cleaned_data['department_name_e']
department_name_l = form.cleaned_data['department_name_l']
parent_code = form.cleaned_data['parent_code']
obj = form.save(commit = False)
obj.is_active = True
obj.created_by = request.user.id
obj.created_date = datetime.today()
obj.modified_by = request.user.id
obj.modified_date = datetime.today()
obj.save()
return HttpResponseRedirect('department_list')
forms:
class DepartmentsForm(forms.ModelForm):
class Meta:
model = Departments
fields = ['department_code','department_name_e','department_name_l','parent_code']
HTML:
{% extends 'base.html' %}
{% block title %}Update Company{% endblock title %}
{% block body %}
<div style="margin-left:22%" class=" top-marg">
<h2 ><strong>Company:</strong></h2><br><br>
<form class="" action="{%url 'update_company' comp_up.company_code %}" method="post">
{% csrf_token %}
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_code}}" class="form-control" id="company_code" name="company_code" placeholder="Company Code" required>
<label style="margin-left:15px" for="company_code">Company Code</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_e}}" class="form-control" id = "company_name_e" name="company_name_e" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name English</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_l}}" class="form-control" id = "company_name_l" name="company_name_l" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name Local</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.tel}}" class="form-control" id = "tel" name="tel" placeholder="Telephone Number" required>
<label style="margin-left:15px" for="tel">Telephone Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.fax}}" class="form-control" id = "fax" name="fax" placeholder="Enter Fax"required>
<label style="margin-left:15px" for="fax"> Fax Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<textarea name="address" class="form-control" rows="4" cols="100" placeholder="Address" required>{{comp_up.address}}</textarea>
<label style="margin-left:15px" for="address">Address</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<select class="form-control" name="country_id" required>
<option value="{{comp_up.country_id.id}}" >{{comp_up.country_id.country_name_e}}</option>
{% for con in country %}
<option value="{{con.id}}" >{{con.country_name_e}}</option>
{% endfor %}
</select>
</div>
<br>
<label style = "margin-left:21%; " for="logo">Logo</label>
<div class="form-floating" >
<input value="{{comp_up.}}" style = "margin-left:21%;" accept="image/*" type="file" name="logo" onchange="loadFile(event)" required> <br>
<img style = "margin-left:21%;" id="output" >
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
</div>
<br><br>
<center>
<button type="submit" class="btn btn-success" name="submit">Update</button>
<button type="button" class="btn btn-primary" onclick="window.location.href = '{%url 'company_list'%}'" name="cancel">Cancel</button>
</center>
</form>
</div>
{% endblock body %}
You have provided HttpReponse only for POST and valid form. You should give the standard response (with empty form) for fresh entries or posting with errors. Like this:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
...
return HttpResponseRedirect('department_list')
form = DepartmentsForm()
return render(request, 'template.html', context={'form': form})
I am attempting to create a blogging application and in it I have 2 forms, one for editing pre-existing posts, and the other for creating them. However, I am unable to get updated images, when the edit form is submitted. All textual data goes through...
Models.py:
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts')
short_description = models.TextField()
updated_on = models.DateTimeField(auto_now=True)
content = RichTextUploadingField()
created_on = models.DateTimeField(auto_now=True)
status = models.IntegerField(choices=Status, default=0)
cover_image = models.ImageField(upload_to = 'coverimages', null =True, blank = True)
captioned_image = models.ImageField(upload_to = 'captionedimages', null=True, blank = True)
caption = models.CharField(max_length=300)
featured = models.IntegerField(choices=Featured, default=1)
category = models.ForeignKey(PostCategory, on_delete=models.CASCADE, null=True, blank=True)
embedded_code = models.TextField(blank=True, null=True, default='null')
tags = models.ManyToManyField(Tag, blank=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
forms.py:
class EditForm(forms.Form):
title = forms.CharField(max_length=100, label='Post Title')
short_description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100}))
content = forms.CharField(widget=CKEditorUploadingWidget())
status = forms.NullBooleanField(label='Ready to Publish?')
image = forms.ImageField(label='Select a cover image:', required=False)
captioned_image = forms.ImageField(label='Select a captionable image:', required=False)
caption = forms.CharField(max_length=200)
try:
category = forms.ModelChoiceField(queryset=PostCategory.objects.all())
except:
category = forms.ChoiceField(choices= ('default'))
embed = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":100}))
tags = forms.CharField(widget=forms.Textarea(attrs = {"rows":1, "cols":150}))
editpost.html:
{% load widget_tweaks %}
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %} {{ form.media }}
<legend>Edit Post: {{ post }}</legend>
<div class="form-group">
<label class="col-form-label mt-4" for="inputDefault">Title</label>
{% render_field form.title class="form-control" %}
</div>
<div class="form-group">
<label class="form-label mt-4" for="exampleTextarea"
>Short Description</label
>
{% render_field form.short_description class="form-control" %}
</div>
<div class="form-group">
<label class="col-form-label mt-4" for="inputDefault">Content</label>
{{ form.content }}
</div>
<div class="form-group">
<label class="form-label mt-4" for="exampleSelect1"
>Ready To Publish?</label
>
{% render_field form.status class="form-select" id="exampleSelect1"%}
</div>
<div class="form-group">
<label class="form-label mt-4" for="formFile">Cover Image</label>
{% render_field form.image class="form-control" id="formFile"%}
{% if post %}
<br>
<p>Current Image:</p>
<img src="{{ post.cover_image.url }}" alt="" style="height: 400px;">
{% endif %}
</div>
<fieldset>
<div class="form-group">
<label class="form-label mt-4" for="formFile"
>Captioned Image</label
>
{% render_field form.captioned_image class="form-control" %}
{% if post %}
<br>
<p>Current Image:</p>
<img src="{{ post.captioned_image.url }}" alt="" style="height: 400px;">
{% endif %}
</div>
<div class="form-group">
<label class="col-form-label mt-4" for="inputDefault"
>Caption</label
>
{% render_field form.caption class="form-control" %}
</div>
</fieldset>
<div class="form-group">
<label class="col-form-label mt-4" for="inputDefault">Category</label>
{% render_field form.category class="form-select"%}
</div>
<div class="form-group">
<label class="col-form-label mt-4" for="inputDefault">Embed</label>
{% render_field form.embed class="form-control"%}
</div>
<div class="form-group">
<label class="col-form-label mt-4" for="inputDefault">Tags</label>
{% render_field form.tags class="form-control"%}
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
After the form is submitted, the image is not saved in the media/coverimages folder, and the development server returns:
Not Found: /media/images.jpg
[23/Jan/2022 09:16:24] "GET /media/images.jpg HTTP/1.1" 404 3786
One thing I have noticed is that if I use the admin site, the image uploads properly, which leads me to believe that perhaps issue is with the form, or how the form is being handled
EDIT:
views.py:
# Converts tag string from a form to a nice iterable list
def tagsplitter(input):
input = str(input)
tags = input.split(', ')
return tags
# Fetches all the tags of a QueryObject and returns tags in a nice list
def tagstringer(object):
tags = object.tags.all()
taglist = []
for tag in tags:
taglist.append(tag.tag)
str1 = ", "
return str1.join(taglist)
#staff_member_required(login_url='login')
def edit_post(request, slug):
context = {}
post = Post.objects.get(slug=slug)
context.update({'post': post})
if request.method == "POST":
form = EditForm(request.POST, request.FILES)
if form.is_valid():
image_path = post.cover_image.path
if os.path.exists(image_path):
os.remove(image_path)
title = request.POST.get('title')
short_description = request.POST.get('short_description')
content = request.POST.get('content')
statusraw = request.POST.get('status')
if str(statusraw) == 'true':
status = 1
else:
status = 0
cover_image = request.FILES.get('image')
captioned_image = request.FILES.get('captioned_image')
caption = request.POST.get('caption')
category = request.POST.get('category')
tags = tagsplitter(request.POST.get('tags'))
embed = request.POST.get('embed')
print(f"cover image: {cover_image}")
if cover_image is not None:
if captioned_image is not None:
# Add both images
newpost = Post.objects.filter(pk=post.pk).update(title=title, cover_image = cover_image, captioned_image=captioned_image, short_description=short_description, content=content, status=status, caption=caption, category=category, embedded_code=embed)
else:
print('Adding cover image only')
# Add only cover image
newpost = Post.objects.filter(pk=post.pk).update(title=title, cover_image = cover_image, short_description=short_description, content=content, status=status, caption=caption, category=category, embedded_code=embed)
else:
if captioned_image is not None:
# Add only captioned image
newpost = Post.objects.filter(pk=post.pk).update(title=title, captioned_image=captioned_image, short_description=short_description, content=content, status=status, caption=caption, category=category, embedded_code=embed)
else:
# Add neither
newpost = Post.objects.filter(pk=post.pk).update(title=title, short_description=short_description, content=content, status=status, caption=caption, category=category, embedded_code=embed)
newpost = Post.objects.get(title = title)
newpost.tags.clear()
for tag in tags:
tag = Tag.objects.update_or_create(tag = tag)
newpost.tags.add(tag[0])
return redirect('blogger:post', slug = slug)
else:
tagstr = tagstringer(post)
init_dict = {
'title': post.title,
'content': post.content,
'short_description': post.short_description,
'status': post.status,
'cover_image': post.cover_image,
'caption': post.caption,
'embed': post.embedded_code,
'category':post.category,
'tags': tagstr
}
form = EditForm(initial = init_dict)
context.update({'form': form})
return render(request, template_name="blogger/edit_post.html", context=context)
I am a newbie, and I am working on a website. On this website I have created admin panel to manage different products and attributes .
I have a page named size.html and and I am supposed to change it name and make it productAtributes.html and on this single page I want to do all add, update, delete operations for different Product attributes.
My code is as:
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class Color(models.Model):
color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
prod_color = models.CharField("Product Color", max_length=50, null=False)
def __str__(self):
return "{color_id}-->{prod_color}".format(color_id=self.color_id,
prod_color=self.prod_color)
class PaperChoice(models.Model):
paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)
def __str__(self):
return "{}-->{}".format(self.paper_id,
self.paper_choices_name)
views.py
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect
from user.models import *
def size(request):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
else:
size_show = Size.objects.all()
# start paginator logic
paginator = Paginator(size_show, 3)
page = request.GET.get('page')
try:
size_show = paginator.page(page)
except PageNotAnInteger:
size_show = paginator.page(1)
except EmptyPage:
size_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/size.html', {'size_show': size_show})
def size_edit(request, id):
size_edit = Size.objects.filter(size_id=id)
return render(request, 'admin1/size.html', {'size_edit': size_edit})
def size_edit_update(request, id):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(size_id=id, prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
def size_delete(request, id):
size_deletee = Size.objects.filter(size_id=id)
size_deletee.delete()
return redirect('/admin1/productSize')
As I created add, update, delete functionality for Size I am going to do it same with color and Papaer choice.
size.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size{% endblock %}
{% block main %}
<h1>
<center>Size</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Product Size</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-product-size'%}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
<br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<br>
{% if size_show %}
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Product Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Product Id</th>
<th>Product Size</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in size_show %}
<tr>
<td>{{x.size_id}}</td>
<td>{{x.prod_size}}</td>
<td><a href="/admin1/size_edit/{{x.size_id}} "
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="/admin1/size_delete/{{x.size_id}}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if size_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in size_show.paginator.page_range %}
{% if size_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if size_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_next_page_number}}"> Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if size_edit %}
{% for x in size_edit %}
<form action="/admin1/size_data_update/{{x.size_id}}" method="POST">
{% csrf_token %}
<label>Size Name:</label>
<input type="text" name="prod_size" value="{{x.prod_size}}" class="form-control w-50"><br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
</form>
{% endfor %}
{% endif %}
</div>
</div>
</div>
{% endblock %}
For performing oertions of views.py I have created size.html .Nut there around 10 to 12 product attributes ,and for that attributes I don't want to create seprate html pages.
I want to do all the operations for all the attributes in single html page. Is it possible?
Means according to the atrribut type request the page data should change dynamically, I do not have to create seprate template pages for each attribute.
You need to make the form in your views, not the Templates, I'm not sure if this is best practise but it's the only way I see you can do this, (using Class-Based Views would simplify this process a lot) but if you want to stick to functions, this is what you do.
Let's take an input line:
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
Let's use Django's tags and turn it into this:
<label>{{form.display_name}}:</label>
<input type="text" name="{{form.name}}" class="form-control w-50">
The class will probably be the same but you could extend the same functionality to the class or type fields.
In the backend, you want to make a list of all the elements you want to show, with nested dictionaries:
forms = [ # Each form
[ # Each field within the form, this way, you can have a different amount each time
{'display_name': 'Product Size', # label Display name
'name': 'prod_size'}, # name tag value
{'display_name': "it's value", # This is a different field
'name': 'just an example'}
],
]
Then you can do a for loop in the templates:
{% for form in forms %}
{$ for field in form %}
<label>{{field.display_name}}:</label>
<input type="text" name="{{field.name}}" class="form-control w-50">
I'm not exactly sure what you're trying to do in your code, so I didn't make this example too specific, but hopefully, it will give you inspiration to get you on the right track, if you need more help, just ask
I'm trying to make a django developed website which is called MuyPicky. It is a website which allows you to find restaurants and other things based on your pickiness. I am currently making a page for forms which adds Restaurants to the database. As I am doing this I get this error:
IntegrityError at /restaurants/create.
NOT NULL constraint failed: restaurants_restaurantlocation.name
Is this why I get the error
Here is the forms.py:
class RestaurantCreateForm(forms.Form):
title = forms.CharField()
location = forms.CharField(required = False)
category = forms.CharField(required = False)
The form.html:
{% extends "base.html" %}
{% block title %}Add Restaurant || {{block.super}} {% endblock %}
{% block content %}
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-offset-4 col-md-4 col-md-offset-4">
<h1>Add Restaurant</h1>
<form method="POST">{% csrf_token %}
<input title="Title" class="form-control" type="text" name="Title" placeholder="Title">
<br>
<input title="Location" class="form-control" type="text" name="Location" placeholder="Location"><br>
<input title="Category" class="form-control" type="text" name="Category" placeholder="Category"><br>
<!--<input title="Save" class="form-control btn btn-info " type="submit" value="Save" >--><br>
<button class="btn btn-success form-control btn-md center-block" type="submit">Save</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
The view from views.py:
def restaurant_createview(request):
#if request.method == "GET":
# print("get data")
if request.method == "POST":
title = request.POST.get("title") #(request.POST["title"])
location = request.POST.get("location")
category = request.POST.get("category")
obj = RestaurantLocation.objects.create(
name = title,
location = location,
category = category
)
return HttpResponseRedirect("/restaurants/")
template_name = "restaurants/form.html"
context = {}
return render(request, template_name, context)
Lastly the urls.py:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^/$', TemplateView.as_view(template_name="home.html")),
url(r'^restaurants/$', RestaurantListView.as_view()),
url(r'^restaurants/create/$', restaurant_createview),
url(r'^restaurants/(?P<slug>[\w-]+)/$', RestaurantDetailView.as_view()),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html")),
url(r'^about/$',TemplateView.as_view(template_name="about.html"))]
Your fields have name Title, Location, Category but your Django code is looking for title, location and category. These need to be the same.
I do not why but the line recording.component=component in my views.py does not save the component which is given as an argument and I do not understand the reason. The only think that I have in mind is that I am using smart_select. Here is what I have:
My views.py file:
def create_recording(request, slug, inspection_id, component_id):
inspection = get_object_or_404(Inspection, pk=inspection_id)
plant = get_object_or_404(Plant, slug=slug)
component=get_object_or_404(Component, pk=component_id)
if request.method == "POST":
form = RecordingForm(request.POST)
if form.is_valid():
recording = form.save(commit=False)
recording.user = request.user
recording.plant = plant
recording.inspection=inspection
recording.component=component
recording.save()
return redirect('data:inspection_detail', slug=plant.slug, inspection_id=inspection.id)
else:
form = RecordingForm()
context = {'form': form, 'plant':plant,'inspection':inspection,}
template = 'data/create_recording.html'
return render(request, template, context)
my models.py:
class Recording(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
plant = models.ForeignKey(Plant, on_delete=models.CASCADE)
inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE)
component = models.ForeignKey(Component)
group = ChainedForeignKey(Group, chained_field="component", chained_model_field="component", show_all=False, auto_choose=True, sort=True)
failure = ChainedForeignKey(Failure, chained_field="group", chained_model_field="group", show_all=False, auto_choose=True, sort=True)
def __str__(self):
return str(self.failure)
my forms.py:
class RecordingForm(forms.ModelForm):
class Meta:
model = Recording
fields = ['group', 'failure',]
my html:
<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id component_id=1 %}">
<button type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus"></span> Chair
</button>
</a>
<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id component_id=2 %}">
<button type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus"></span> Table
</button>
</a>
and the html for for my form:
<div class = "col-sm-7">
<div class="panel panel-primary">
<div class="panel-heading">
<h4>Add new recording</h4>
</div>
<div class="panel-body">
<form method='POST'>
{% csrf_token %}
{{ form|crispy }}
<button type = 'submit' class="btn btn-success">Save</button>
</form>
</div>
</div>
</div>
and my url:
url(r'^plants/(?P<slug>[-\w]+)/inspection(?P<inspection_id>[0-9]+)/create_recording/(?P<component_id>[0-9]+)$', views.create_recording, name='create_recording'),
please let me know if I need to add some more information.