Trouble getting Django ModelForm inside modal to work - django

OK - I'm positive that the issue is that I have some fundamental understanding of how forms work in Django, so 30,000 ft conceptual explanations are welcome, in addition to code fixes!
I'm trying to run my site from (mostly) a single view (and single template), with modal popups to view info (working) and to edit or add it (not working). I can see the form, fill it out, and click submit, at which point the modal closes, but no new Courses show up in the admin view.
I'll confine this to a single model - my simplest - for the time being:
models.py:
class Course(models.Model):
Name = models.CharField(max_length=30,unique=True)
Active = models.BooleanField(default=True)
def __unicode__(self):
return u'%s' % (self.Name)
views.py
def IndexView(request,Course_id,Section_id):
template_name = 'gbook/index.html'
print Course_id,Section_id
this_course = Course.objects.get(pk=Course_id)
active_courses = Course.objects.all().filter(Active=True).exclude(pk=Course_id)
section_list = Section.objects.all().filter(course=this_course)
if len(section_list) >1:
multi_section = True
else:
multi_section = False
active_section = Section.objects.get(pk=Section_id)
roster = Student.objects.all().filter(sections__in=[active_section])
announcement_list = Announcement.objects.all().filter(sections__in=[active_section])
courseaddform = CourseAddForm()
context = {'active_courses':active_courses, 'this_course': this_course,
'active_section':active_section, 'section_list':section_list,
'roster':roster, 'multi_section':multi_section,
'announcement_list':announcement_list, 'courseaddform':courseaddform}
return render(request,'gbook/index.html', context)
forms.py
class CourseAddForm(forms.ModelForm):
class Meta:
model = Course
fields = ['Name', 'Active']
templates/index.html
...
<li class="dropdown">
<span class="glyphicon glyphicon-cog" aria-hidden="true"></span><span class="caret"></span>
<ul class="dropdown-menu">
<li><a data-toggle="modal" data-target="#SectionRosterModal">Roster</a></li>
<li><a data-toggle="modal" data-target="#AnnouncementModal">Announcements</a></li>
<li><a data-toggle="modal" data-target="#CourseAddModal">CourseAdd</a></li>
</ul>
</li>
...
<!-- COURSE ADD MODAL -->
<div class="modal fade" id="CourseAddModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:5px 10px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4>Add Course</h4>
</div>
<div class="modal-body" style="padding:10px 10px;">
<form data-parsley-validate method="post" id="courseaddform" action="" enctype="multipart/form-data"
data-parsley-trigger="focusout">
{% csrf_token %}
{{ courseaddform.as_p }}
<p id="login-error"></p>
<input type="submit" class="btn btn-info submit" name="AddCourse" value="Add Course" />
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
...
I think that there's supposed to be a POST command in there somewhere, but I really don't have a good handle on the process here. Thanks for the help!

It looks like you are not doing anything with the form data when you post back, you need to process the form if the request method is a POST
def IndexView(request, ...):
if request.method == "GET":
... do what you are doing now and return
elif request.method == "POST":
cf = CourseAddForm(request.POST)
if cf.is_valid():
...do stuff with cf.cleaned_data <---- this is a dict
return ....
You are doing the same thing for GET and POST requests right now and neither deals with the submitted form
see here for more details
https://docs.djangoproject.com/en/1.10/topics/forms/#the-view
EDIT #1:
The POST should be a standard HTTP POST request back to the same URL. Just set the method tag as you are now and action="." (or a URL lookup in the template).
You need to return a valid HTTPResponse object but the normal case when dealing with a form is to return a HTTPResponseRedirect(...some url...) if the form is valid. In the case of a single page app, if you reload the same page you need to do everything you did in the request.method == "GET" so maybe return a HTTPResponseRedirect back to the same URL. In this case, I would look at the django messages framework and add a message to the context saying the form was submitted successfully and display the message in the reloaded page (you should always check if there is a message to display anyway when using the messages framework so this will not break the case where you are loading the page for the first time)
https://docs.djangoproject.com/en/1.9/ref/contrib/messages/

Related

The right way to dynamically add Django formset instances and POST usign HTMX?

I'm making a form with a nested dynamic formset using htmx i (want to evade usign JS, but if there's no choice...) to instance more formset fields in order to make a dynamic nested form, however when i POST, only the data from 1 instance of the Chlid formset (the last one) is POSTed, the rest of the form POSTs correctly and the Child model gets the relation to the Parent model
I read the django documentation on how to POST formset instances and tried to apply it to my code, also i got right how to POST both Parent and Child at the same time. For the formsets i'm making a htmx get request hx-get to a partial template that contains the child formset and that works great, the only problem is that this always returns a form-0 formset to the client side, so for the POST the data repeats x times per field and only takes the data placed in the last instance, however i tried to change the extra=int value on my formset to get more forms upright, this gave the expected result, one Child instance per form in extra=int, so my problem is up with htmx and the way i'm calling the new Child formset instances.
here's my code. (i plan to nest more child formsets inside this form so i call this sformset for conveniece)
****views.py****
def createPlan(request):#Requst for the Parent form
form = PlanForm(request.POST or None)
sformset = StructureFormset(request.POST or None) #Nesting the Child formset
context = {
'form':form,
'sformset':sformset,
}
if request.method == 'POST':
print(request.POST)
if form.is_valid() and sformset.is_valid():
plan = form.save(commit=False)
print(plan)
plan.save()
sform = sformset.save(commit=False)
for structure in sform:
structure.plan = plan
structure.save()
return render(request, 'app/plan_forms.html', context)
def addStructure(request):
sformset = StructureFormset(queryset=Structure.objects.none())#add a empty formset instance
context = {"sformset":sformset}
return render(request, 'app/formsets/structure_form.html', context)
****forms.py****
StructureFormset = modelformset_factory(Structure,
fields = (
'material_type',
'weight',
'thickness',
'provider'
))
****relevant part for plan_forms.html template****
<form method="POST">
{% csrf_token %}
<div class="col-12 px-2">
<div class="row px-3 py-1">
<div class="col-3 px-1">{{ form.format }}</div>
<div class="col-3 px-1">{{ form.pc }}</div>
<div class="col-3 px-1">{{ form.revission }}</div>
<div class="col-3 px-1">{{ form.rev_date }}</div>
</div>
<div class="row px-3 py-1">
<div class="col-3 px-1">{{ form.client }}</div>
<div class="col-3 px-1">{{ form.product }}</div>
<div class="col-3 px-1">{{ form.gp_code }}</div>
<div class="col-3 px-1">{{ form.code }}</div>
</div>
</div>
<div>
<table>
<tbody style="user-select: none;" id="structureforms" hx-sync="closest form:queue">
<!--Structure formset goes here-->
</tbody>
<tfoot>
<a href="" hx-get="{% url 'structure-form' %}" hx-swap="beforeend" hx-target="#structureforms">
Add structure <!--Button to call structure formset-->
</a>
</tfoot>
</table>
</div>
<div class="col-12 px-2">
<div class="row px-4 py-1">{{ form.observation }}</div>
<div class="row px-4 py-1">{{ form.continuation }}</div>
<div class="row px-4 py-1">{{ form.dispatch_conditions }}</div>
<div class="row px-3 py-1">
<div class="col-6 px-1">{{ form.elaborator }}</div>
<div class="col-6 px-1">{{ form.reviewer }}</div>
</div>
</div>
<button type="submit">Submit</button>
</form>
****formsets/structure_form.html****
<tr>
<td class="col-12 px-1">
{{ sformset }}
</td>
</tr>
**** relevant urls.py****
urlpatterns = [
path('create_plan/', views.createPlan, name='create_plan'),
path('htmx/structure-form/', views.addStructure, name='structure-form')]
Additionally, the form that i built in admin.py using fields and inlines is just exactly what i want as the raw product (except for the amount of initial formsets and styles)
To summarize the problem: At present, your code successfully brings in the new formset, but each new formset comes with a name attribute of form-0-title (ditto for id and other attributes). In addition, after adding the new formset with hx-get the hidden fields originally created by the ManagementForm will no longer reflect the number of formsets on the page.
What's needed
After a new formset is added to the site, here's what I think needs to happen so Django can process the form submission.
Update the value attribute in the input element with id="id_form-TOTAL_FORMS" so the number matches the actual number of formsets on the page after hx-get brings in the new formset.
Update the name and id of the new formset from form-0-title to use whatever number reflects the current total number of formsets.
Update the labels' for attributes in the same way.
You can do this with Javascript on the client side. Alternatively, you can do effectively the same thing with Django on the server side and then htmx can be the only javascript needed to do the rest. For that, I have used empty_form to create the html content of a formset which can be altered as needed. That work is shown in the build_new_formset() helper, below.
Example
Here's what I have working:
forms.py
from django import forms
from django.forms import formset_factory
class BookForm(forms.Form):
title = forms.CharField()
author = forms.CharField()
BookFormSet = formset_factory(BookForm)
views.py
from django.utils.safestring import mark_safe
from app2.forms import BookFormSet
def formset_view(request):
template = 'formset.html'
if request.POST:
formset = BookFormSet(request.POST)
if formset.is_valid():
print(f">>>> form is valid. Request.post is {request.POST}")
return HttpResponseRedirect(reverse('app2:formset_view'))
else:
formset = BookFormSet()
return render(request, template, {'formset': formset})
def add_formset(request, current_total_formsets):
new_formset = build_new_formset(BookFormSet(), current_total_formsets)
context = {
'new_formset': new_formset,
'new_total_formsets': current_total_formsets + 1,
}
return render(request, 'formset_partial.html', context)
# Helper to build the needed formset
def build_new_formset(formset, new_total_formsets):
html = ""
for form in formset.empty_form:
html += form.label_tag().replace('__prefix__', str(new_total_formsets))
html += str(form).replace('__prefix__', str(new_total_formsets))
return mark_safe(html)
Note re: build_new_formset() helper: formset.empty_form will omit the index numbers that should go on the id, name and label attributes, and will instead use "__prefix__". You want to replace that "__prefix__" part with the appropriate number. For example, if it's the second formset on the page its id should be id_form-1-title (changed from id_form-__prefix__-title).
formset.html
<form action="{% url 'app2:formset_view' %}" method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
<p>{{ form }}</p>
{% endfor %}
<button type="button"
hx-trigger="click"
hx-get="{% url 'app2:add_formset' formset.total_form_count %}"
hx-swap="outerHTML">
Add formset
</button>
<input type="submit" value="Submit">
</form>
formset_partial.html
<input hx-swap-oob="true"
type="hidden"
name="form-TOTAL_FORMS"
value="{{ new_total_formsets }}"
id="id_form-TOTAL_FORMS">
<p>{{ new_formset }}</p>
<button type="button"
hx-trigger="click"
hx-get="{% url 'app2:add_formset' new_total_formsets %}"
hx-swap="outerHTML">
Add formset
</button>
Note re: the hidden input: With every newly added formset, the value of the input element that has id="id_form-TOTAL_FORMS" will no longer reflect the actual number of formsets on the page. You can send a new hidden input with your formset and include hx-swap-oob="true" on it. Htmx will then replace the old one with the new one.
Docs reference: https://docs.djangoproject.com/en/4.1/topics/forms/formsets/

How to add comments with ajax in django website?

How can I add comments in my Django website without refreshing the page?
Here are my codes:
VIEW.PY
#login_required
def comments(request, post_id):
"""Comment on post."""
post = get_object_or_404(Post, id=post_id)
user = request.user
comments = Comment.objects.filter(post=post).order_by('-date')#comment
if request.method == 'POST':#Comments Form
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.user = user
comment.save()
messages.success(request, 'Comment has been added successfully.')
return HttpResponseRedirect(reverse('core:comments',args=[post_id]))
else:
form = CommentForm()
template = loader.get_template('post/comments.html')
context = {'post':post,'form':form,'comments':comments,}
return HttpResponse(template.render(context, request))
COMMENTS.HTMl
Form section:
<div class='commentsection' >
<strong>
<form action="{% url 'core:comments' post.id %}" method='post' id=comment-form >
{% csrf_token %}
{% bootstrap_form form %}
</form>
<br/>
<br/>
</strong>
</div>
Comments section:
{% for comment in comments %}
<div class="card mb-3" style="width: 30rem;">
<div class="row no-gutters">
<small> <a style="color: black;" href="{% url 'core:user_profile' comment.user %}"><img src="{{comment.user.profile.profile_pic.url}}" width=50 height=50 class="profile-image img-circle " style="object-fit: cover; float: auto; "><strong style="font-size: 18px;" > #{{comment.user}} </strong></a> </small> <small><span class="glyphicon glyphicon-time"></span> {{ comment.get_date }}</small>
</div>
<div class="card-body" style="width:100%; padding-left:20%; margin-top:-8%; word-break: break-all; color:black; " >
<h5 class="card-text">
{{ comment.comment }}</h5>
<small > Replies [{{comment.total_replies}}] </small
</div>
</div>
</div>
<br/><br/>
{% empty %}
<center>
No commnets
</center>
{% endfor %}
My problems:
Add comments without refreshing the page.
Auto-add newly added comments in the comment section without refreshing the page.
Thanks in advance!
You've correctly surmised that this an AJAX problem, though you could nowadays use a websocket as well. Traditional django solution would be with an AJAX callback.Short of writing it for you, I can offer a pro-forma solution (outline):
Add a view to your site which returns in JSON (or XML or any other serialisable format) a list of new comments from a given datetime (which you pass to the view as a GET param, or POST param if you prefer).
Add Javascript to you page which periodically polls the server with new comment requests. if it gets any returned then it has to dynamically add those comments to the DOM for you.
Your second request, auto-adding new comments, is contingent on whether you want to use a websocket or not. If you use a websocket then yes, the server can inform your page through that socket when new comments arrive. But if you want to stick with AJAX, then it is contingent on the polling interval (which is one big reason websockets were developed and are useful).
There are endless tutorials and how-tos online about writing the Javascript to fetch data and dynamically update the DOM, as there on how to use websockets.

add multiple forms to page on button click

I am working on developing a permitting app using django. This is my first django project so bear with me here...
we have a default utility permit that contains some basic info like property owner and address. Then from that you can attach a sewer, or water or row or any combination of related tables to the permit. Basically I am looking for a way to return a page with the default utility permit then have a series of links or buttons to add more forms to that page.
I made some model forms for each of the models and can display them individually on the page
forms.py
class UtilityPermitForm(forms.ModelForm):
class Meta:
model = UtilityPermit
fields = ['...']
class SewerPermitForm(forms.ModelForm):
class Meta:
model = SewerPermit
fields = ['...']
class WaterPermitForm(forms.ModelForm):
class Meta:
model = WaterPermit
fields = ['...']
I successfully added them to a list and could iterate through and get them to add
views.py
class BuildForms(View):
permits = []
utility_form = UtilityPermitForm
sewer_form = SewerPermitForm
water_form = WaterPermitForm
permits.append(utility_form)
permits.append(sewer_form)
permits.append(water_form)
template_name = 'engineering/UtilityPermitForm2.html'
def get(self, request, *args, **kwargs):
out_permits = []
for form in self.permits:
out_permits.append(form())
return render(request, self.template_name, {'form': out_permits})
def post(self, request, *args, **kwargs):
if request.GET.get('testButton'):
return HttpResponse("I guess")
form = self.utility_form(request.POST)
return render(request, self.template_name, {'form': form})
def add_permit(self, request, permit):
# need to get a thing to add a permit to the list
pass
.html
{% block content %}
<div>
<form class="site_form" action={% url 'engineering:utility_permit' %} method="post">
{% csrf_token %}
{% for item in form %}
{{ item }}
<hr>
{% endfor %}
<input type="submit" value="Submit">
</form>
</div>
{% endblock content %}
so again, my problem is I want to start with a one permit and then have links or buttons to add each form as needed. I'm a bit at a loss here and any help would be greatly appreciated.
EDIT:
so I have this base permit that comes up when a user navigates to it like so, and I want to have a user click the add sewer permit button or link or whatever
and then the corresponding permit will come up
you can create multiple same form in one page dynamically using formset
see Documentation
and maybe this tutorial is exactly what you are looking for.
EDITED
if I understand your question correctly, how about this:
first, it would be better to separate your form with dictionaries instead of list in your views.py
context = {
'utility_form': self.utility_form,
'sewer_form': self.sewer_form,
'water_form': self.water_form
}
return render(request, self.template_name, context)
then in your .html file,
if you want to add one form each time you click the button, my trick is:
show your base permit form first (said utility_form), button to add other form, and hide your other form first.
<div class="form-container">
<form class="site_form" action={% url 'engineering:utility_permit' %} method="post">
{% csrf_token %}
{{ utility_form }}
<div id="additional-forms"></div> <!-- notice this div -->
<hr>
<input type="submit" value="Submit">
</form>
</div>
<button class="add-sewer-form">Sewer Permit</button>
<div id="sewer-form-template" style="display: none;">
<div class="sewer-form-container">
{{ sewer_form }}
</div>
</div>
and then using jquery to add onclick listener, clone that hidden form, then insert it after base form (actually inside div with id additional-forms).
$('.add-sewer-form').click(function(){
let sewer_form = $('#sewer-form-template .sewer-form-container:first').clone(true);
$(sewer_form).appendTo($('#additional-forms'))
});
I haven't test it yet, but when you click the add button, it should be give result like this:
<div class="form-container">
<form class="site_form" action={% url 'engineering:utility_permit' %} method="post">
{% csrf_token %}
{{ utility_form }}
<div id="additional-forms">
<div class="sewer-form-container">
{{ sewer_form }}
</div>
</div>
<hr>
<input type="submit" value="Submit">
</form>
</div>
<button class="add-sewer-form">Sewer Permit</button>
<div id="sewer-form-template" style="display: none;">
<div class="sewer-form-container">
{{ sewer_form }}
</div>
</div>
Hope it can answer your question :)
First add the button
<button><button>
Then add onclick attribute to it which will help react on click
<button onclick='do'><button>
Then create script that contain the function to display the other form
<script>
function do() {
document.getElementById('form').innerHTML ='add your form here'
}
</script>
all together
<button onclick='do'><button>
<script>
function do() {
document.getElementById('form').innerHTML ='add your form here'
}
</script>

Django - Taking of object model by select tag and passing this object to another view

I'm struggling with the following problem. In my project I have the following model:
models.py
class InputSignal(models.Model):
name = models.CharField(max_length=512)
author = models.ForeignKey(User, on_delete=models.CASCADE)
adnotations = models.TextField(blank=True, null=True)
input_file = models.FileField(upload_to='signals/', null=False, validators=[validate_file_extension])
add_date = models.DateTimeField(default=datetime.now())
last_edit_date = models.DateTimeField(default=datetime.now())
last_json_results = models.FileField(upload_to='resuts/')
objects = models.Manager()
def delete(self):
self.input_file.delete()
super().delete()
def __str__(self):
return self.name
def add_date_pretty(self):
return self.add_date.strftime('%b %e %Y')
Two url addresses:
urls.py
path('display/list', displayviews.display_list, name='display-list'),
path('display/details/<int:signal_id>', displayviews.display_details, name='display-details'),
And two view functions:
views.py
def display_list(request):
signals = InputSignal.objects.filter(author=request.user)
return render(request, 'display_list.html', {'signals': signals})
def display_details(request, signal_id):
signal = get_object_or_404(InputSignal, pk=signal_id)
The template of the first function of the view at this moment looks like this:
display_list.html
<div class="row mt-2">
<div class="col-lg-1"></div>
<div class="col-lg-10">
<select class="form-control mt-2 text-center">
{% for signal in signals %}
<option>
<h2>{{ signal.name }}</h2>
</option>
{% endfor %}
</select>
</div>
<div class="col-lg-1"></div>
</div>
<div class="row mt-3 mb-2">
<div class="col-lg-4"></div>
<div class="col-lg-4">
Perform Analysis
</div>
<div class="col-lg-4"></div>
</div>
I would like based on the structure of this template to design a solution that after selecting the signal name from the select tag and clicking the 'perform analysis' button, go to the next view - display_details (request, signal_id). Where I will save the previously selected model object to the variable. Choosing the right object I would like to use the object ID. I would like to ask for help, what I was able to design presented above.
A couple of things here.
To submit data from a web page you need a form element (unless you're using Ajax, which doesn't seem necessary here). Your select box needs a name attribute, and each option needs a value to submit. Also, you can't submit a form with an a link; you need a submit button. So:
<form action="{% url 'display-details' %}">
<select name="signal_id" class="form-control mt-2 text-center">
{% for signal in signals %}
<option value="{{ signal.id }}">
<h2>{{ signal.name }}</h2>
</option>
{% endfor %}
<button class="btn btn-outline-success btn-block">Perform Analysis</button>
</form>
Now this data is being submitted in the querystring to your display_details view, eg "/display/details/?signal_id=5". So you need to remove the parameter from the URL pattern, and get the data inside the view from the GET params:
path('display/details/', displayviews.display_details, name='display-details'),
...
def display_details(request):
signal_id = request.GET['signal_id']
signal = get_object_or_404(InputSignal, pk=signal_id)

Django: How save partial filled form state

I don't know exactly how to ask this question.
The thing is that I have a main view to create new entries in a model. This model has some 1-many relations, so I added a + button to add new entries of this fields (secondary model) in case they did not exist. When I submit this new data I redirect to the previous page (main view), and if you already filled some fields in the main view, that information is lost.
Can someone suggest me what the best way to deal with this would be?
Thanks in advance!
UPDATE:
'main model view'
class OrganismCreate(LoginRequiredMixin,CreateView):
"""Template: //catalog/templates/catalog/organism_form.html"""
model = Organism
fields = '__all__'
'main model template' (part)
<form action="" method="post">
{% csrf_token %}
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">Add a new entry: </div>
<div class="panel-body">
<hr>
<div class="row">
<div class="form-group col-sm-4 col-md-3">
<div class="form-group col-sm-4 col-md-3">
<label for="id_inst_own">Owner:</label>
{% render_field form.inst_own class="form-control" %}
<i class="fa fa-plus-circle "></i> Add new
</div>
<div class="panel panel-default">
<div class="panel-body">
...........................................
<button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-filter"></span> submit </button>
</div>
</div>
</div>
Then the related model view:
def test_f(request):
if request.method == "GET":
Form = InstitutionForm()
render(request, 'catalog/institution_form.html')
if request.method == "POST":
Form = InstitutionForm(request.POST)
if Form.is_valid():
Form.save()
next = request.POST.get('next', '/')
return redirect(next)
pre=request.META.get('HTTP_REFERER')
return render(request, 'catalog/institution_form.html',{"form" : Form, "pre": pre})
And the related model template
{% block content %}
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="hidden" name="next" value="{{ pre }}">
<input type="submit" class="btn btn-success" value="Submit" />
</form>
{% endblock %}
There are a number of ways to solve this problem. Here's some suggestions. Not an exclusive list:
Save the incomplete model data in the database as as a 'draft' version of the final data. This could be a totally different model or else using the same model (assuming the related fields are nullable) and giving it a 'draft' flag or similar.
Use an inline formset to create the related objects in the same view. Django Extra Views has some useful tools for this (https://github.com/AndrewIngram/django-extra-views).
Using JavaScript, save the unfinished form data to local storage and then recover it when the original form is loaded again.
I have implemented a draft system to do this along the lines of 1. in #ChidG's answer.
In models I have something like
class AbstractThing(models.Model):
field = models.CharField()
class Meta:
abstract = True
class CompleteThing(AbstractThing):
class Meta:
managed = True
db_table = 'complete_thing'
class IncompleteThing(AbstractThing):
fields_to_not_blank = [AbstractThing._meta.get_field(x) for x in []] #if you don't want to change some fields
for f in AbstractThing._meta.fields:
if f not in fields_to_not_blank:
f.blank = True
f.null = True
class Meta:
managed = True
db_table = 'incomplete_thing'
Then you can use model forms and handle the cases in your views.