I can't update my post using modelformset factory - python

i am using two models named Posts and PostPicture and posts model have multiple text fields whereas PostPicture model have one image field and one posts foreignkey field and i am using formset_factory on image field in views to let the user upload multiple images with the post, the problem is that whenever i try to update the post it updates the text fields of Posts model but it doesn't update the images i upload with it...there's something wrong with my update view and i can't figure out
Here's my views.py for update_post
def update_post(request, post_id):
ImageFormSet = modelformset_factory(PostPicture,
form=AddPictures, extra=5, min_num=1,
can_delete=True)
post_form = get_object_or_404(Posts, pk=post_id)
pics_form = PostPicture.objects.filter(post=post_id)
if request.method == "POST":
form = AddFile(request.POST, instance=post_form)
formset = ImageFormSet(request.POST or None, queryset=pics_form)
if form.is_valid() and formset.is_valid():
posting = form.save(commit=False)
posting.user = request.user
posting.save()
for form in formset.cleaned_data:
image = form['image']
photo = PostPicture(post=posting, image=image)
photo.save()
messages.success(request, 'Post updated Successfully!')
return render(request, 'vehicles_app/addfile.html', {
'form': form,
'pics_form': pics_form,
'formset': formset,
'post_form': post_form,
'post_id': post_id,
})
else:
messages.success(request, 'Post not updated Successfully!')
print(form.errors, formset.errors)
else:
form = AddFile(instance=post_form)
formset =
ImageFormSet(queryset=PostPicture.objects.filter(post=post_id))
return render(request, 'vehicles_app/update_post.html', {'form':
form, 'formset': formset, 'pics_form': pics_form,
'post_form':post_form,'post_id': post_id})
here's my update_post.html
<form id="post_form" method="post" action="{% url
'vehicles_app:update_post' post_id %}"
enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="form-group">
<div style="float: left; width: 50%">
<label for="title">Ad Title</label>
</div>
<div class="title" style="float: right; width: 45%">
<input type="text" name="title" placeholder="Type Here"
value='{{ form.initial.title }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="city">City</label>
</div>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="mileage">Mileage</label>
</div>
<div class=mileage style="float: right; width: 45%">
<input type="text" name="mileage" placeholder="ie:50000"
value='{{ form.initial.mileage }}' required>
</div>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="details">Type details here</label>
</div>
<div class="details" style="float: right; width: 45%">
<textarea name="details" rows="9" cols="45" value='{{
form.initial.details }}' required></textarea>
</div>
</div>
<br>
{{ formset.management_form }}
{% if formset %}
{% for form in formset %}
{% if form %}
<table class="display" cellspacing="1" width="100%">
<tr>
<td>{{ form }}</td>
</tr>
</table>
{% endif %}
{% endfor %}
{% endif %}
<input type="submit" name="submit" value="Update"
class="btn btn-info" id="post_btn">
<input type=button class="btn btn-default" value="Cancel"
onClick="javascript:history.go(-1);">
</form>

Related

Why I can't save values in database? Django

I want to save my form in database, but save() doesn't work. When I do this, error wasn't showing. At the start, I think problem was in database, but it isn't
views.py
def comments(request):
comments = Comment.objects.all()
form = CommentForm()
context = {"comments": comments, "form": form}
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.avtor = request.user
comment.save()
return HttpResponseRedirect(reverse('comment'))
else:
context["form"] = form
return render(request, "home/comments.html", context)
else:
return render(request, "home/comments.html", context)
And models. So, I think problem yet in views.py. I bad know how function save() is working.
models.py
class Comment(models.Model):
Text = models.TextField(verbose_name='Text')
date = models.DateTimeField(default=timezone.now, verbose_name='date')
avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE)
def __str__(self):
return 'Comment {} at {}'.format(self.avtor, self.date)
class Meta:
ordering = ["-id"]
forms.py
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ("Text",)
At the last, I want to save avtor, text and Date. Help me please.
<div class="container" style="min-height: 520px;">
<form class="text-light formGroupComm" action="/" method="post">
{% csrf_token %}
{{ form }}
<br>
<button style="width: 6%!important;" class="btn btn-warning mb-5 mt-3 mx-auto" type="submit">submit</button>
</form>
<div class="comments text-dark">
{% for comentPost in comments %}
<div class="commentItem bg-warning my-3" style="border-radius: 40px; padding: 20px;">
<div style="border-bottom: 3px solid black;" class="comTitle mx-3 my-3">{{ comentPost.avtor }}</div>
<div style="" class="comText mx-5">{{ comentPost.Text }}</div>
<div style="" class="comDate mx-3 my-5">{{ comentPost.date|date:"F d, Время: h:i" }}</div>
</div>
{% endfor %}
</div>
</div>
The action attribute specifies where to send the form-data when a form is submitted (https://www.w3schools.com/tags/att_form_action.asp).
So when you put the "/" in there, the form will send the data to the home page (represented by / in html). This means that your data doesn't get to the POST section of your def comments(request) method. When the method is not called, the logical outcome is thus that there isn't a new comment added.
This is the correct code:
<div class="container" style="min-height: 520px;">
<form class="text-light formGroupComm" method="post">
{% csrf_token %}
{{ form }}
<br>
<button style="width: 6%!important;" class="btn btn-warning mb-5 mt-3 mx-auto" type="submit">submit</button>
</form>
<div class="comments text-dark">
{% for comentPost in comments %}
<div class="commentItem bg-warning my-3" style="border-radius: 40px; padding: 20px;">
<div style="border-bottom: 3px solid black;" class="comTitle mx-3 my-3">{{ comentPost.avtor }}</div>
<div style="" class="comText mx-5">{{ comentPost.Text }}</div>
<div style="" class="comDate mx-3 my-5">{{ comentPost.date|date:"F d, Время: h:i" }}</div>
</div>
{% endfor %}
</div>
</div>

Django-Vue error "Failed to mount app: mount target selector returned null."

Thanks for looking into my problem, I am a beginner with Django and Vue your assistance with this wil be extremely helpful. I am working on a Job portal and created the job search functionality in Django as backend for the same I have an app called job into my Django project. The browser Js console gives this error Failed to mount app: mount target selector returned null. For this app I have an add job view, through which an employer adds the jobs. For this I'm using Vue for validation and showing any errors if any non-null fields are not entered by the employer account. So this is not how it was supposed to look,Unexpected results snap shot so as you can see it wasn't supposed to give me [[error]] and company_size instead The company size is missing as per the Vue AddJobApp, given below. Also if were to add # within mount-function-createapp within Vue-AddJobApp, the page entirely disappears (blank page). what am I doing wrong here?
adding # in AddJob.mount() function is making the page go blank a
Add job template
{% extends 'core/base.html' %}
{% block content %}
<div id="add-job-app">
<h1 class="title"> Add Job</h1>
<form action="." method="POST" v-on:submit="validateForm">
{% csrf_token %}
{% if form.errors %}
{% for error in form.errors %}
<div class="notification is-danger">
{{ error }}
</div>
{% endfor %}
{% endif %}
<div class="notification is-danger" v-if ="error.length" >
<p v-for="error in errors" >
[[ error ]]
</p>
</div>
<div class="field">
<label for="">Title</label>
<div class="control">
<input class="input" type="text" name="title" id="id_title" v-model= "title">
</div>
</div>
<div class="field">
<label for="">Short description</label>
<div class="control">
<textarea name="short_description" id="id_short_description" class="textarea" v-model= "short_description" ></textarea>
</div>
</div>
<div class="field">
<label for="">Long description</label>
<div class="control">
<textarea name="long_description" id="id_long_description" class="textarea" v-model= "long_description" ></textarea>
</div>
</div>
<div class="field">
<label for="">Company name</label>
<div class="control">
<input class="input" type="text" name="company_name" id="id_company_name" v-model= "company_name" >
</div>
</div>
<div class="field">
<label for="">Company address</label>
<div class="control">
<input class="input" type="text" name="company_address" id="id_company_address" v-model= "company_address">
</div>
</div>
<div class="field">
<label for="">Company zipcode</label>
<div class="control">
<input class="input" type="text" name="company_zipcode" id="id_company_zipcode" v-model= "company_zipcode">
</div>
</div>
<div class="field">
<label for="">Company place</label>
<div class="control">
<input class="input" type="text" name="company_place" id="id_company_place" v-model= "company_place">
</div>
</div>
<div class="field">
<label for="">Company Country</label>
<div class="control">
<input class="input" type="text" name="company_country" id="id_company_country" v-model= "company_country">
</div>
</div>
<div class="field">
<label for="">Company Size</label>
<div class="control">
<div class="select">
<select name="company_size" v-model = "company_size">
<option value="">Choose Size</option>
<option value="size_1_9">1-9</option>
<option value="size_10_49">10-49</option>
<option value="size_50_99">50-99</option>
<option value="size_100">100+</option>
</select>
</div>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-success">Submit</button>
</div>
</div>
</form>
</div>
{% endblock %}
{% block scripts %}
<script >
const AddJobApp = {
data() {
return {
title:'',
company_name:'',
short_description:'',
company_size:'',
errors:[]
}
},
delimiters:['[[',']]'],
methods :{
validateForm(e){
this.errors = []
if( this.title ===''){
this.errors.push('The title field is missing')
}
if( this.short_description ===''){
this.errors.push('The short description field is missing')
}
if( this.company_name ===''){
this.errors.push('The company name field is missing')
}
if( this.company_size ===''){
this.errors.push('The company size is missing')
}
if(this.errors.length){
e.preventDefault()
return false
}else{
return true
}
}
}
}
Vue.createApp(AddJobApp).mount('add-job-app');
</script>
{% endblock %}
my views.py file inside of job app
from apps.job.forms import AddJobForm, ApplicationForm
from django.shortcuts import redirect, render
from .models import Job
from django.contrib.auth.decorators import login_required
from apps.notification.utilities import create_notification
def job_detail(request,job_id):
job = Job.objects.get(pk=job_id)
return render(request, 'job/job_detail.html',{'job':job})
def search(request):
return render(request,'job/search.html')
#login_required
def apply_for_job(request,job_id):
job = Job.objects.get(pk=job_id)
if request.method=='POST':
form = ApplicationForm(request.POST)
if form.is_valid():
application = form.save(commit=False)
application.job = job
application.created_by = request.user
application.save()
create_notification(request, job.created_by ,'application',extra_id=application.id)
return redirect('dashboard')
else:
form = ApplicationForm()
return render(request,'job/apply_for_job.html',{'form':form,'job':job})
#login_required
def add_job(request):
if request.method=='POST':
form = AddJobForm(request.POST)
if form.is_valid():
job = form.save(commit=False)
job.created_by = request.user
job.save()
return redirect('dashboard')
else:
form = AddJobForm()
return render(request,'job/add_job.html',{'form':form})

Passing Parameters From a Class Based View in Django

I have a class based Update view "ManifestUpdate", which is a modal pop up, and is launched from within another function based view "Manifest". I need to be able to take the field = 'reference' from my ManifestUpdate view and make it available to the "Manifest" view as 'Reference_Nos'. As you can see ManifestUpdate should direct the user to Manifest, but it does not, just nothing happens (it works if I change this to direct to any other view). I believe this is because I am not passing that parameter. Can anyone tell me how to capture that 'reference' parameter within ManifestUpdate and pass it to Manifest from the class based view?
views.py
class ManifestUpdate(BSModalUpdateView):
model = Manifests
template_name = 'manifest_update.html'
form_class = UpdateManifestForm
success_message = 'Success: Manifest was updated.'
success_url = reverse_lazy('manifest')
def manifest(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
reference_id = form.cleaned_data.get('reference')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
else:
reference_id = request.POST.get('Reference_Nos')
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id),
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class UpdateManifestForm(BSModalForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
update_manifest.html
#showing the modal window body
<form method="post" action="">
{% csrf_token %}
<div class="modal-header">
<h3 class="modal-title">Update Manifest</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="{% if form.non_field_errors %}invalid{% endif %} mb-2">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.product_name" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
</div>
</div>
<div class="modal-footer">
<button type="button" class="submit-btn btn btn-primary">Update</button>
</div>
</form>
manifest_readonly.html
#showing the html rendered by the manifest view
{% extends 'base.html' %}
{% load humanize %}
{% block body %}
{% load staticfiles %}
<div class="container">
<div class="col-xs-12">
{% if messages %}
{% for message in messages %}
<div class="alert alert-success" role="alert">
<center>{{ message }}</center>
</div>
{% endfor %}
{% endif %}
</div>
</div>
<div class="container">
<form id="create_mani_form" method="POST">
<br>
<br>
<br>
{% csrf_token %}
<div class="column">
<label for="form.reference" class="formlabels">Reference ID: </label><br>
<!-- <input type="text" value="{{ reference_id }}">-->
{{ form.reference }}
<br>
<br>
<label for="form.count" class="formlabels">CNF: </label>
<br>
{{ form.CNF }}
<br>
</div>
<div class="description">
<div class="column">
<label for="form.description" class="formlabels">Description: </label>
<br>
{{ form.product_name}}
<br><br>
<label for="form.count" class="formlabels">FOB: </label>
<br>
{{ form.FOB }}
<br>
</div>
</div>
<div class="column">
<label for="form.cases" class="formlabels">Cases: </label>
<br>
{{ form.cases }}
<br>
</div>
<div class="column">
<label for="form.count" class="formlabels">Count: </label>
<br>
{{ form.count }}
<br>
<label for="form.reference" class="formlabels">Case Total: </label><br>
<input type="text" value="{{ total_cases|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total CNF: </label><br>
<input type="text" value="{{ totalCNF|intcomma }}" readonly>
<br>
<label for="form.reference" class="formlabels">Total FOB: </label><br>
<input type="text" value="{{ totalFOB|intcomma }}" readonly>
</div>
<br>
<br>
<button type="submit" name="add_mani" style="border-color: #7395AE;">Add Line</button>
</form>
<br>
<h4>Manifest</h4>
<div class="table-responsive">
<!--<table id="manifest_table" class="table table-striped table-bordered table-sm " cellspacing="0"-->
<table class="table table-striped table-bordered manifest_table" cellspacing="0" style="width="100%">
<thead>
<tr>
<th style="width:2%;"</th>
<th style="width:10%;">Cases</th>
<th style="width:60%;">Description</th>
<th style="width:10%;">Count</th>
<th style="width:10%">FOB</th>
<th style="width:10%">CNF</th>
</tr>
</thead>
<tbody>
{% for manifests in data %}
<tr>
<td>
<!-- Update book buttons -->
<button type="button" class="update-manifest btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'manifest_update' manifests.pk %}">
<span class="fa fa-pencil"></span>
</button>
</td>
<td>{{ manifests.cases }}</td>
<td>{{ manifests.product_name}}</td>
<td>{{ manifests.count}}</td>
<td>{{ manifests.FOB}}</td>
<td>{{ manifests.CNF}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="text-center">
Subit Manifest
</div>
<div class="modal fade" tabindex="-1" role="dialog" id="modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="jquery.min.js"></script>
<script src="jquery.fulltable.js"></script>
<script src="script.js"></script>
<script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script>
<script>
$(function () {
$(".update-manifest").each(function () {
$(this).modalForm({formURL: $(this).data('id')});
});
});
</script>
{% endblock %}
jquery.bootstrap.modal.forms.js
(function ($) {
// Place the form at formURL to modalContent element of modal with id=modalID
var newForm = function (modalID, modalContent, modalForm, formURL, successURL, errorClass) {
$(modalContent).load(formURL, function () {
$(modalID).modal('toggle');
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
});
};
// Add AJAX validation to the modalForm
var ajaxSubmit = function (modalID, modalContent, modalForm, successURL, errorClass) {
$(modalForm).submit(function (event) {
// Prevent submit and POST form to url using AJAX
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
// Serialize form data
data: $(this).serialize(),
success: function (response) {
// Update form with errors after unsuccessful POST request
// Django form.is_valid() = False
if ($(response).find(errorClass).length > 0) {
$(modalID).find(modalContent).html(response);
ajaxSubmit(modalID, modalContent, modalForm, successURL, errorClass);
}
// Hide modal after successful POST request when & redirect to successURL
else {
$(modalID).modal("hide");
window.location.href = successURL;
}
}
});
});
};
$.fn.modalForm = function (options) {
// Default settings
var defaults = {
modalID: "#modal",
modalContent: ".modal-content",
modalForm: ".modal-content form",
formURL: null,
successURL: "/",
errorClass: ".invalid"
};
// Extend default settings with provided options
var settings = $.extend(defaults, options);
return this.each(function () {
$(this).click(function (event) {
newForm(settings.modalID,
settings.modalContent,
settings.modalForm,
settings.formURL,
settings.successURL,
settings.errorClass);
event.preventDefault();
});
});
};
}(jQuery));

Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicles_app/(?P<post_id>[0-9]+)/update_post/$']

I have searched a lot, but couldn't find a solution. There are a lot of related questions being asked before and I think there's no mistake but there's still an error.
Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicles_app/(?P<post_id>[0-9]+)/update_post/$']
Here is my index.html
{% for obj in context %}
<div class="container" style="padding-left:240px; padding-right:0px; width: 78%; margin-bottom:30px;">
<div class="well" style=" background-color: rgb(220, 220, 220);">
<div class="media">
<div class="media-body">
<div class="list-group">
<div class="d-flex w-100 justify-content-between">
<h1 class="media-heading" style="margin-top:20px; margin-bottom:20px; color: black;">{{ obj.title }}</h1>
{% for img in obj.postpicture_set.filter %}
<div class="w3-content" style="max-width:800px">
{% if img.image %}
<img style="margin-bottom:30px; float: right" class="mySlides" src="{{ img.image.url }}" width="200" height="180">
{% endif %}
</div>
{% endfor %}
<p> {{ obj.details }} </p>
<ul class="list-inline list-unstyled">
<li><span><i class="glyphicon glyphicon-calendar"></i> {{ obj.date }} </span></li>
<li>|</li>
<span><i></i> {{ obj.brand }} </span>
<li>|</li>
<span><i></i> {{ obj.city }} </span><br>
<form action="{% url 'vehicles_app:data' obj.id %}" method="post">{% csrf_token %} <input type="hidden" name="post_id" value="{{ obj.id }}">
<input type="hidden" name="usr_id" value="{{ obj.user_id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" class="btn btn-primary" value="Details"</td></form>
{% if request.user == obj.user or request.user.is_superuser %}
<form action="{% url 'vehicles_app:file-delete' obj.id %}" method="post" style="display: inline;">{% csrf_token %} <input type="hidden" name="post_id" value="{{ obj.id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" value="Delete" class="btn btn-danger btn-sm"</td></form>
<form action="{% url 'vehicles_app:update' obj.id %}" method="post" style="display: inline;">{% csrf_token %}<input type="hidden" name="post_id" value="{{ obj.id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" value="Update" class="btn btn-default btn-sm"</td></form>
{% else %}
{% endif %}
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Here is views.py
def update_post(request, post_id):
ImageFormSet = modelformset_factory(
PostPicture,
form=AddPictures,
extra=10,
min_num=1
)
post_form = get_object_or_404(Posts, pk=post_id)
if request.method == "POST":
form = AddFile(request.POST, instance=post_form)
formset = ImageFormSet(
queryset=PostPicture.objects.filter(
post=post_id
)
)
if form.is_valid() and formset.is_valid():
form.save()
for form in formset:
if form:
image = form['image']
photo = PostPicture(post=form, image=image)
photo.save()
messages.success(
request, 'Post submitted Successfully!'
)
return render(
request,
'vehicles_app/update_post.html',
{
'form': form,
'formset': formset,
'post_form':post_form
}
)
else:
print(form.errors, formset.errors)
else:
form = AddFile()
formset = ImageFormSet(
queryset=PostPicture.objects.none()
)
return render(
request,
'vehicles_app/update_post.html',
{
'form': form,
'formset': formset,
'post_form':post_form
}
)
Here is the url for my update, only update is not working, but other things like data and delete are working fine.
urlpatterns = [
url(r'^signUp/$', views.signUp, name='signUp'),
url(r'^user_login/$', views.user_login, name='user_login'),
url(r'^addfile/$', views.addfile, name='addfile'),
url(r'^(?P<pk>[0-9]+)/delete/$', views.FileDelete.as_view(), name='file-delete'),
url(r'^(?P<post_id>[0-9]+)/data/$', views.data, name='data'),
url(r'^(?P<post_id>[0-9]+)/update_post/$', views.update_post, name='update'),
url(r'^myposts/$', views.myposts, name='myposts'),
url(r'^received/$', views.received, name='received'),
url(r'^received_files/$', views.received_files, name='received_files'),
]
here is my update_post.html
{% extends "vehicles_app/index.html" %}
{% block body_block %}
{% load staticfiles %}
<html>
<body>
<div class="container" id="addfile_form" style="margin- left:200px; width: 78%;">
<!-- <div class="col-xs-12 col-sm-4 col-md-6 col-sm-offset-2 col- md-offset-2"> -->
<div class="panel panel-default">
<div>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<h2 style="margin-left:100px;"> {{ message }} </h2>
{% endfor %}
</ul>
{% endif %}
</div>
<div class="panel-heading">
<b><h2 id="post_head" class="panel-title">Update Post here!</h2>
</b>
</div>
<div class="panel-body">
<form id="post_form" method="post" action="{% url
'vehicles_app:update_post' post_id %}"
enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="form-group">
<div style="float: left; width: 50%">
<label for="title">Ad Title</label>
</div>
<div class="title" style="float: right; width: 45%">
<input type="text" name="title" placeholder="Type Here"
value='{{ form.title.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="city">City</label>
</div>
<div class="city" style="float: right; width: 45%">
<select name="city" value='{{ form.city.value }}'>
<option selected="selected"
value="islamabad">Islamabad</option>
<option value="karachi">Karachi</option>
<option value="lahore">Lahore</option>
<option value="peshawar">Peshawar</option>
<option value="quetta">Quetta</option>
<option value="multan">Multan</option>
<option value="faisalabad">Faisalabad</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="price">Price</label>
</div>
<div class="price" style="float: right; width: 45%">
<input type="text" name="price" placeholder="Type Here"
value='{{ form.price.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="brand">Brand</label>
</div>
<div class="brand" style="float: right; width: 45%">
<select name="brand" value='{{ form.brand.value }}'>
<option selected="selected"
value="honda">Honda</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="suzuki">Suzuki</option>
<option value="toyota">Toyota</option>
<option value="lexus">Lexus</option>
<option value="hyundai">Hyundai</option>
<option value="jeep">Jeep</option>
<option value="mazda">Mazda</option>
<option value="mitsubishi">Mitsubishi</option>
<option value="daewoo">Daewoo</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="modelyear">Model-Year</label>
</div>
<div class="modelyear" style="float: right; width: 45%">
<input type="text" name="modelyear"
placeholder="ie:1970-2018" value='{{ form.modelyear.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="condition">Condition</label>
</div>
<div class="condition" style="float: right; width: 45%">
<select name="condition" value='{{ form.condition.value
}}'>
<option selected="selected" value="new">NEW</option>
<option value="used">USED</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="mileage">Mileage</label>
</div>
<div class=mileage style="float: right; width: 45%">
<input type="text" name="mileage" placeholder="ie:50000"
value='{{ form.mileage.value }}' required>
</div>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="details">Type details here</label>
</div>
<div class="details" style="float: right; width: 45%">
<textarea name="details" rows="9" cols="45" value='{{
form.details.value }}' required></textarea>
</div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
{{ formset.management_form }}
{% if formset %}
{% for form in formset %}
{% if form %}
<table class="display" cellspacing="1" width="100%">
<tr>
<td>{{ form }}</td>
</tr>
</table>
{% endif %}
{% endfor %}
{% endif %}
<input type="submit" name="submit" value="Update" class="btn
btn-info" id="post_btn">
</form>
</div>
</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</body>
</html>
{% endblock %}
The error is coming from this url tag in your update_post.html template.
<form id="post_form" method="post" action="{% url 'vehicles_app:update_post' post_id %}"
You get the error with arguments '('',)' in the error message because you haven't included post_id in the template context. You can add it with:
return render(request, 'vehicles_app/update_post.html', {
'form': form,
'formset': formset,
'post_form': post_form,
'post_id': post_id,
})
Remember to do this for GET and POST requests.

i wanna update my formset factory images post, i am able to update posts text fields but formset factory images are noot updating [duplicate]

i am using two models named Posts and PostPicture and posts model have multiple text fields whereas PostPicture model have one image field and one posts foreignkey field and i am using formset_factory on image field in views to let the user upload multiple images with the post, the problem is that whenever i try to update the post it updates the text fields of Posts model but it doesn't update the images i upload with it...there's something wrong with my update view and i can't figure out
Here's my views.py for update_post
def update_post(request, post_id):
ImageFormSet = modelformset_factory(PostPicture,
form=AddPictures, extra=5, min_num=1,
can_delete=True)
post_form = get_object_or_404(Posts, pk=post_id)
pics_form = PostPicture.objects.filter(post=post_id)
if request.method == "POST":
form = AddFile(request.POST, instance=post_form)
formset = ImageFormSet(request.POST or None, queryset=pics_form)
if form.is_valid() and formset.is_valid():
posting = form.save(commit=False)
posting.user = request.user
posting.save()
for form in formset.cleaned_data:
image = form['image']
photo = PostPicture(post=posting, image=image)
photo.save()
messages.success(request, 'Post updated Successfully!')
return render(request, 'vehicles_app/addfile.html', {
'form': form,
'pics_form': pics_form,
'formset': formset,
'post_form': post_form,
'post_id': post_id,
})
else:
messages.success(request, 'Post not updated Successfully!')
print(form.errors, formset.errors)
else:
form = AddFile(instance=post_form)
formset =
ImageFormSet(queryset=PostPicture.objects.filter(post=post_id))
return render(request, 'vehicles_app/update_post.html', {'form':
form, 'formset': formset, 'pics_form': pics_form,
'post_form':post_form,'post_id': post_id})
here's my update_post.html
<form id="post_form" method="post" action="{% url
'vehicles_app:update_post' post_id %}"
enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="form-group">
<div style="float: left; width: 50%">
<label for="title">Ad Title</label>
</div>
<div class="title" style="float: right; width: 45%">
<input type="text" name="title" placeholder="Type Here"
value='{{ form.initial.title }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="city">City</label>
</div>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="mileage">Mileage</label>
</div>
<div class=mileage style="float: right; width: 45%">
<input type="text" name="mileage" placeholder="ie:50000"
value='{{ form.initial.mileage }}' required>
</div>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="details">Type details here</label>
</div>
<div class="details" style="float: right; width: 45%">
<textarea name="details" rows="9" cols="45" value='{{
form.initial.details }}' required></textarea>
</div>
</div>
<br>
{{ formset.management_form }}
{% if formset %}
{% for form in formset %}
{% if form %}
<table class="display" cellspacing="1" width="100%">
<tr>
<td>{{ form }}</td>
</tr>
</table>
{% endif %}
{% endfor %}
{% endif %}
<input type="submit" name="submit" value="Update"
class="btn btn-info" id="post_btn">
<input type=button class="btn btn-default" value="Cancel"
onClick="javascript:history.go(-1);">
</form>

Categories

Resources