Related
I have three models jobposition, wage, kitfee and they are related by a OneToMany relation.
class JobPosition(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.ForeignKey(Title, on_delete=models.CASCADE)
...
class Wage(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
amount = models.FloatField(blank=True,null=True)
type = models.CharField(choices=WAGETYPE, max_length=30)
position = models.ForeignKey(JobPosition, related_name='wages', on_delete=models.CASCADE, blank=True, null=True)
class KitFee(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
kit_name = models.CharField(max_length=20, blank=True, null=True)
amount = models.FloatField(blank=True, null=True)
type = models.CharField(choices=WAGETYPE, max_length=30)
position = models.ForeignKey(JobPosition, related_name='kit_fees', on_delete=models.CASCADE, blank=True, null=True)
I am building a user interface where a user can create a position with associated wage and kit_fee (let's say just one wage and one kit fee for now).
The problem I am facing is that I am not sure how to make a post request in the right way.
I created these two forms and served them to a django template using a templateview.
class JobPositionForm(forms.ModelForm):
class Meta:
model = JobPosition
fields = ['title','city','dept_head','files','department_budget']
...
class WageForm(forms.ModelForm):
class Meta:
model = Wage
exclude = ['id']
my view
class NewPosition(MyLoginRequiredMixin,TemplateView):
template_name = 'action/crew/position.html'
def get_context_data(self, **kwargs):
self.project = get_object_or_404(JobProject, id=kwargs['project_id'])
context = super().get_context_data(**kwargs)
context['position_form'] = JobPositionForm(project=self.project, user=self.request.user)
context['wage_form'] = WageForm()
context['kit_fee_form'] = KitFeeForm()
return context
def post(self,request, **kwargs):
print(request.POST)
self.project = get_object_or_404(JobProject, id=kwargs['project_id'])
position_form = JobPositionForm(request.POST, project=self.project, user=self.request.user)
wage_form = WageForm(request.POST)
kit_fee_form = KitFeeForm(request.POST)
print(kit_fee_form.data['amount'])
print(wage_form.data['amount'])
The page is rendered smoothly, however I am now realizing that I don't know how to submit those two forms together inside a single post request and also how to initialize the forms in the view when processing the post request.
I thought about using formset but I don't know how to use it with different forms.
I guess I can always do this manually using Javascript to parse each value and place it into the same POST... but I was hoping there was a work around it using some nice django functionality. Especially cause the manual approach doesn't scale well.
<form id="position_form">
<div id="title_div" style="margin-top: 20px;">
<label for="id_title" style="margin-bottom: 5px;" class="lead">Title</label><br/>
{{position_form.title}}
<div id="city_div" style="margin-top: 20px;" onfocus="$('#title_creation_div').hide();">
<label for="id_city" style="margin-bottom: 5px;" class="lead">City</label><br/>
{{position_form.city}}
</div>
<br>
<div class="inner" style="display: inline-block;margin-right: 5px;margin-left: 5px; text-align: center">
<label for="OtherComp">Department Budget</label><br/>
{{position_form.department_budget}}
</div>
<div class="inner" style="display: inline-block;margin-right: 5px;margin-left: 5px; text-align: center">
<label for="TeamInfo">Department Head</label><br/>
{{ position_form.dept_head }}
</div>
</form>
<form id="wage_form">
<div id="outer" style="width:100%; margin-top: 20px ">
<div class="inner" style="display: inline-block;margin-right: 5px;margin-left: 5px">
<label for="{{ wage_form.amount.id_for_label }}">Rate</label><br/>
{{wage_form.amount}}
</div>
<div class="inner" style="display: inline-block;margin-right: 5px;margin-left: 5px; text-align: center">
<label for="{{ wage_form.type.id_for_label }}">Rate Type</label><br/>
{{wage_form.type}}
</div>
</div>
</form>
Any idea?
Edit
I am using this javascript to send all forms into the same post request and it seems to be working ok. However, I am noticing that many fields have the same id so I can't initiate the forms properly. Also, the process doesn't seem to be scalable if I start adding additional wages/kitfee to the screen.
$("form").submit(function (e) {
e.preventDefault();
let data_array = $("form").map(function(){
return $(this).serializeArray();
});
data_array.push({csrfmiddlewaretoken: "{{ csrf_token }}"})
console.log(data_array)
$.ajax({
type: "POST",
url: "{% if source == 'edit' %}{% url 'action:edit_position' project.id position.id %}{% else %}{% url 'action:new_position' project.id %}{% endif %}",
data:data_array,
success:function(html){
}
});
});
Since you are using a model form, you can directly pass in the request into the form instance to process both the forms simultaneously... See a simple signup scenario below where two model forms ( User_form and User_profile_Form) are being processed,
Views.py
def signup(request):
registered = False
if request.method == "POST":
user_form = User_form(data=request.POST)
user_profileform = user_profile_form(data=request.POST)
if(user_form.is_valid() and user_profileform.is_valid()):
user = user_form.save()
user.set_password(user.password)
user.save()
profile = user_profileform.save(commit=False)
profile.user = user
if 'profile_picture' in request.FILES:
profile.profile_picture = request.FILES['profile_picture']
profile.save()
registered = True
else:
print(user_form.errors, user_profileform.errors)
UPDATE 1 Adding template part
<!DOCTYPE html>
{% extends "base.html" %}
{% load static %}
{% load bootstrap_tags %}
{% block title %}
Signup
{% endblock %}
{% block body %}
<div class="container">
{% if registered %}
<h1>Thankyou for REGISTERING with us</h1>
<br>
click here to continue
{% else %}
<h4 style="text-align: center;" > Already have an account ? </h4>
<h3>PLEASE fill the registration form below</h3>
<form enctype="multipart/form-data" method="POST">
<div class="container sign-form">
{% csrf_token %}
<h4>
<u>Account Information : </u>
{{ user_form |as_bootstrap }}
<br>
<hr>
<br>
<u><h4>Personal Information :</h4></u>
{{ user_profileform |as_bootstrap }}
</h4>
<input type="submit" class = "btn btn-primary" name="submit" value="Sign Up" style="margin: 0% 15%; width: 70%">
</div>
</form>
{% endif %}
{% endblock %}
I have a view complaints page where a user can view the complaints he/she have submitted. When the user clicks on one of the cards, I need a new page to open where the user can view the details of that complaint and edit it as well.
It should go from here:
to here: Where they can view details and make changes as well:
This is my models.py:
class Complaint(models.Model):
user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True)
id = models.AutoField(blank=False, primary_key=True)
reportnumber = models.CharField(max_length=500 ,null = True, blank= False)
eventdate = models.DateField(null=True, blank=False)
event_type = models.CharField(max_length=300, null=True, blank=True)
device_problem = models.CharField(max_length=300, null=True, blank=True)
manufacturer = models.CharField(max_length=300, null=True, blank=True)
product_code = models.CharField(max_length=300, null=True, blank=True)
brand_name = models.CharField(max_length = 300, null=True, blank=True)
exemption = models.CharField(max_length=300, null=True, blank=True)
patient_problem = models.CharField(max_length=500, null=True, blank=True)
event_text = models.TextField(null=True, blank= True)
document = models.FileField(upload_to='static/documents', blank=True, null=True)
def __str__(self):
return self.reportnumber
views.py:
def EditComplaints(request):
complaint = request.user.complaint
form = ComplaintForm(instance=complaint)
if request.method == 'POST':
form = ComplaintForm(request.POST, request.FILES, instance=complaint)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'newcomplaint.html', context)
template (the view history page):
<div class="col right-pro-con">
<div class="img-cir">
<form method='POST' action="" enctype="multipart/form-data">
{% csrf_token %} {% if request.user.profile.profile_pic.url %}
<img src={{request.user.profile.profile_pic.url}} alt="" width="100px" height="100px" class="pro-img"> {% else %}
<img src="{% static 'profileimages/msi.jpg' %}" alt="" width="100px" height="100px" class="pro-img"> {% endif %}
<p class="my-name">{{request.user.profile.first}}
<p>
<p class="my-email-id">{{request.user.profile.email}}</p>
</form>
</div>
CONTACT US
</div>
template(edit complaint page):
<div class="col-lg middle middle-complaint-con">
<i class="fas fa-folder-open fa-4x comp-folder-icon"></i>
<h1 class="all-comp">New Complaint</h1>
<form class="" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p class="sub-typ-wr">Submit Type</p>
<button type="button" class="btn btn-secondary document-btn">Document</button>
<div class="rep-num">
<label class="written-label" for="">Report Number</label>
<div class="written-txt-field">{{form.reportnumber}}</div>
</div>
<div class="eve-dte">
<label class="written-label" for="">Event Date</label>
<div class="written-txt-field">{{form.eventdate}}</div>
</div>
<div class="eve-typ">
<label class="written-label" for="">Event Type</label>
<div class="written-txt-field">{{form.event_type}}</div>
</div>
<div class="dev-pro">
<label class="written-label" for="">Device Problem</label>
<div class="written-txt-field">{{form.device_problem}}</div>
</div>
<label class="written-label eve-txt" for="">Event Text</label>
<div class="Manufacturer">
<label class="written-label" for="">Manufacturer</label>
<div class="written-txt-field">{{form.manufacturer}}</div>
</div>
<div class="pro-code">
<label class="written-label" for="">Product Code</label>
<div class="written-txt-field">{{form.product_code}}</div>
</div>
<div class="brand-name">
<label class="written-label" for="">Brand Name</label>
<div class="written-txt-field">{{form.brand_name}}</div>
</div>
<div class="exem">
<label class="written-label" for="">Exemption</label>
<div class="written-txt-field">{{form.exemption}}</div>
</div>
<div class="pat-pro">
<label class="written-label" for="">Patient Problem</label>
<div class="written-txt-field">{{form.patient_problem}}</div>
</div>
<div class="comp-textarea">{{form.event_text}}</div>
<button type="button" class="btn btn-secondary attach-btn-1"><div class="fas fa-file-upload">{{form.document}}</div></button>
<button type="submit" name="submit" class="btn btn-secondary save-btn-1"><i class="fas fa-save"></i> Save</button>
</form>
</div>
url:
urlpatterns = [
path('admin/', admin.site.urls),
path('Home/', landing_page.views1.landing, name= 'Home'),
path('Registration/', accounts.views.RegisterPage),
path('Login/', accounts.views.LoginPage, name='Login'),
path('Login/Profile/', accounts.views.profile, name='Profile'),
path('Logout/', accounts.views.LogoutUser, name='Logout'),
path('Login/Add-Complaint/', accounts.views.NewComplaint, name = 'New'),
path('Login/Add-Complaint/Document-Style/', accounts.views.DocComplaint, name='doc'),
path('My-History/', accounts.views.History, name='MyHistory'),
path('Complaint/', accounts.views.EditComplaints, name='Complaint')
]
How do I do this? What should I add in the code for the code to open that particular complaints details and for that complaints page to edit?
okay, so you already have a view. What you need is some sort of unique identifier to help you figure out the actual object that the user wants to edit.
So, in your urls.py you will have to add a pattern similar to:
urlpatterns = [
...
path('complain/<int:pk>/edit/', views.EditComplaint.as_view(), name='edit-complain'),
...
]
Inside your views.py, handle it in a manner something similar to:
from django.views.generics import UpdateView
from django.contrib.auth.mixins import UserPassesTestMixin
from django.http import Http404
from django.utils.translation import gettext_lazy as _
from .models import Complaint
class EditComplaint(UserPassesTestMixin, UpdateView):
model = Complaint
fields = ('info', ) # define whatever field that you want to render
def form_valid(self, form):
# do your form validation here
def test_func(self):
"""ensuring the reporter themselves is updating the complain"""
complain = self.get_object()
if self.request.user == complain.user:
return True
raise Http404(_('This complain does not exist'))
def success_url(self):
# this is only required if your model doesn't have a `get_absolute_url` method
# return the actual url of the instance
All you need now is to add a link inside your template for the EditComplaint view(assuming you already have the list of donations inside your list template as donations).
Something along the lines should do the job
{% for complaint in complaints %}
Edit Complaint
{% endfor %}
I am having some trouble getting a file to post via a form using generic class-based view CreateView. Below is what i have so far. I am not quite sure how to handle the file and if request.FILES is getting the file being posted or if there is something else i need to be doing to capture the file information in the form. I have tried following the docs, however no luck in getting something working. File uploads as a blank field.
views.py
# Create
class FileUploadCreateView(BSModalCreateView):
template_name = 'fileupload/create-file.html'
form_class = FileUploadModelForm
success_message = 'Success: File was uploaded.'
success_url = reverse_lazy('files_list')
# Add required field my_user prior to posting form
def form_valid(self, form):
form = FileUploadModelForm(self.request.POST, self.request.FILES)
self.object = form.save(commit=False)
self.object.my_user = self.request.user
self.object.file_status = 'ready'
return super().form_valid(form)
forms.py
class FileUploadModelForm(BSModalModelForm):
class Meta:
model = FileUpload
fields = ['file_name', 'file_description', 'file_date_from', 'file_date_to','file_upload']
widgets = {
'file_name': forms.TextInput(attrs={'class':'form-control mb-3', 'id':'ruleset_name'}),
'file_description': forms.Textarea(attrs={'rows':5}),
'file_date_from': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
),
'file_date_to': DatePickerInput(
options={
"format": "MM/DD/YYYY",
"showClose": True,
"showClear": True,
"showTodayButton": True,
}
),
'file_upload': forms.FileInput(attrs={'class':'form-control-file mb-3', 'id':'file_upload', 'type':'file', }),
}
html
{% load widget_tweaks %}
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title" style="color:#7a7a7a;">
<i class="fas fa-plus-square fa-med pr-2 align-middle"></i>
<span class="align-middle">ADD File</span>
</h5>
<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>
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}" style="font-size: small; color:#7a7a7a;">{{ field.label }}</label>
{% render_field field class="form-control" %}
<div class="{% if field.errors %} invalid{% endif %}">
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="submit-btn btn btn-primary pr-4 pl-4">Save</button>
</div>
</form>
model.py
class FileUpload(models.Model):
"""
Class for the creation of file uploads
"""
id = models.AutoField(primary_key=True)
my_user = models.ForeignKey('users.MyUser', on_delete=models.CASCADE, related_name='file_uploads', default=None)
file_name = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Name')
file_description = models.CharField(max_length=255, blank=False, default=None, verbose_name='File Description')
file_date_from = models.DateField(default=None, null=True, blank=False, verbose_name='File Date From')
file_date_to = models.DateField(default=None, null=True, blank=False, verbose_name='File Date To')
STATUS_CHOICES = (
('ready','Ready'),
('processed', 'Processed'),
('archived','Archived'),
)
file_status = models.CharField(max_length=9, choices=STATUS_CHOICES, default=None, blank=False, verbose_name='File Status')
file_create_date = models.DateTimeField(verbose_name='File Create Date', auto_now_add=True)
file_upload = models.FileField(upload_to='uploads/%Y/%m/%d/', default=None, verbose_name='File Upload', blank=True)
class Meta:
ordering = ['-file_create_date']
constraints = [
models.UniqueConstraint(fields=['my_user','file_name'], name='Unique MyUser File')
]
def __str__(self):
return self.file_name
Pretty sure you forgot to add the enctype="multipart/form-data" data attribute to the form tag in your template.
To be sure, you would have to provide us with the Model, the Form and the template code.
after working on the view for some time, I was able to get the file to post via the following, using cleaned_data.
# Add required fields prior to posting form
def form_valid(self, form):
self.instance = form.save(commit=False)
self.instance.my_user = self.request.user
self.instance.file_status = 'ready'
self.instance.file_upload = form.cleaned_data['file_upload']
return super().form_valid(form)
I am learning django. I am working on a blog. When user reply to a comment it is showing time of its parent comment. It should show actual time of reply. I attached a picture with this post.Please have a look , you will better understand my question. How can I fix? I tried but all in vain. may be it is a silly mistake from me or i am not getting it. Thanks in advance
view.py
def blogPost(request, slug):
post = Post.objects.filter(slug=slug).first()
comments = BlogComment.objects.filter(post=post, parent=None)
replies = BlogComment.objects.filter(post=post).exclude(parent=None)
replyDict = {}
for reply in replies:
if reply.parent.sno not in replyDict.keys():
replyDict[reply.parent.sno] = [reply]
else:
replyDict[reply.parent.sno].append(reply)
context = {'post':post, 'comments':comments, 'user': request.user, 'replyDict': replyDict}
return render(request, 'blog/blogPost.html',context)
def postComments(request):
if request.method == 'POST':
comment = request.POST.get('comment')
user = request.user
postSno = request.POST.get('postSno')
post = Post.objects.get(sno=postSno)
parentSno = request.POST.get('parentSno')
if parentSno == "":
comments = BlogComment(comment=comment, user=user, post=post)
comments.save()
messages.success(request, 'Your Comment has been posted Successfully')
else:
parent = BlogComment.objects.get(sno=parentSno)
comments = BlogComment(comment=comment, user=user, post=post, parent=parent)
comments.save()
messages.success(request, 'Your reply has been posted Successfully')
return redirect(f"/blog/{post.slug}")
models.py
class Post(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
content = models.TextField(max_length=10000)
author = models.CharField(max_length=20)
region = models.CharField(max_length=20)
slug = models.CharField(max_length=50, default="")
timestamp = models.DateTimeField(blank=True)
thumbnail = models.ImageField(upload_to="images", default="")
def __str__(self):
return self.title + 'by' + self.author
class BlogComment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) #it is pointing the value of blogcomment so we use 'self'
timestamp = models.DateTimeField(default=now)
replytimestamp = models.DateTimeField(default=now)
def __str__(self):
return self.comment[0:10] + "..." + "by " + self.user.username
blogPost.html
{% for comment in comments %}
<div class="row border border-dark mx-0 my-3">
<div class="col-md-1"><img src="/media/images/usr.png" height="55px" width="55px"></div>
<div class="col-md-11"><b> {{comment.user.username}} </b>
<span class="badge badge-secondary">{{comment.timestamp | naturaltime}}</span>
<!--this will show time in 2 hours ago or x hour ago like-->
<div>
<p class="font-italic">{{comment.comment}}</p>
</div>
<div class="reply mx-0">
<p>
{% if user.is_authenticated %}
<button class="btn btn-primary btn-sm" type="button" data-toggle="collapse"
data-target="#replyBox{{comment.sno}}" aria-expanded="false" aria-controls="collapseExample">
reply
</button>
</p>
<div class="collapse" id="replyBox{{comment.sno}}">
<div class="card card-body mb-2">
<form action="/blog/postComments" method="POST">{% csrf_token %}
<div class="form-group">
<label for="comment">Post a Reply</label>
<input type="text" class="form-control" id="comment" name="comment"
placeholder="Write a reply Here">
<input type="hidden" name="parentSno" value="{{comment.sno}}">
</div>
<input type="hidden" name="postSno" value="{{post.sno}}">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
{% endif %}
<div class="replies my-2">
{% for reply in replyDict|get_val:comment.sno %}
<!-- this will return replies associated with comment.sno in the replyDict[] -->
<div class="row my-2">
<div class="col-md-1"><img src="/media/images/usr.png" height="35px" width="35px"></div>
<div class="col-md-11">
<b> {{comment.user.username}} </b><span
class="badge badge-secondary">{{comment.timestamp | naturaltime}}</span>
<div>{{reply.comment}}</div>
</div>
<br>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
commentand reply pictures
I am beginner in django . I would like to make an application that allows a user to record examinations and related images.
So i try to uploading multiple images in Django for a single post according this topic http://qasimalbaqali.com/uploading-multiple-images-in-django-for-a-single-post/.
But nothing happens when I press the button
I explain my models. A document is a generic class. An exam is a document, a document contains files.
class Document(models.Model):
class Meta:
db_table = 'Document'
slug = models.SlugField(max_length=100)
user = models.ForeignKey(User)
level = models.ForeignKey(ClassLevel, null=False, default=1)
school = models.ForeignKey(School, null=False, default=1)
nb_views = models.IntegerField(default=0)
name = models.CharField(max_length=100)
matter = models.ForeignKey(ClassTopic, null=False, default=1)
status = models.IntegerField(choices=DOCUMENT_STATUS, default=1)
creation_date = models.DateTimeField(auto_now_add=True)
deletion_date = models.DateTimeField(auto_now_add=False, default=None, null=True)
def __unicode__(self):
return self.name + " (" + str(self.status) + ") " + self.school.name
class DocumentFile(models.Model):
class Meta:
db_table = 'DocumentFile'
file = models.FileField(upload_to="photo/", null=True)
document = models.ForeignKey(Document)
def __unicode__(self):
return self.file
class Exam(Document):
class Meta:
db_table = 'Exam'
year_exam = models.IntegerField(choices=EXAM_YEAR_CHOICES, default=1)
mock_exam = models.IntegerField(choices=EXAM_TYPE, default=1)
def __unicode__(self):
return self.name + " " + self.matter
I create two forms. For exam and for file.
class UploadFileForm(ModelForm):
#description = forms.CharField(max_length=30)
file = forms.FileInput()
helper = FormHelper()
helper.form_id = 'file-input'
helper.form_show_labels = False
helper.layout = Layout(PrependedText('file', "", placeholder=""))
#helper.layout.insert(1, HTML("<input type='file' class='file' multiple data-show-upload='false' data-show-caption='true'>"))
class Meta:
model = DocumentFile
fields = ('file',)
#exclude = ("file_type", "file_path", "document")
class CreateExamForm(forms.ModelForm):
helper = FormHelper()
helper.form_id = 'CreateExam'
helper.form_show_labels = False
helper.layout = Layout(
PrependedText("matter", "", ""),
PrependedText("level", "<small class='text-warning'>Selectionner la classe. </small>", ""),
PrependedText("school", "<pre><small>Selectionner l\'établissement. </small></pre>", css_class="selectpicker"),
PrependedText("year_exam", ""),
PrependedText("mock_exam", ""))
class Meta:
model = Exam
exclude = ("slug", "user", "nb_views", "name", "status", "creation_date", "deletion_date")
My view
def createexam(request):
# Creation du formulaire + upload des images
doc_form = CreateExamForm(auto_id=True)
# Création du formset avec n itération : extra=2
file_form_set = modelformset_factory(DocumentFile, form=UploadFileForm, extra=1)
# Récupération du formulaire géré par le mécanisme formset
#formset = sortedfilesform()
if request.method == "POST":
doc_form = CreateExamForm(request.POST)
files_form = file_form_set(request.POST, request.FILES, queryset=DocumentFile.objects.none())
if doc_form.is_valid() and files_form.is_valid():
doc_save = doc_form.save(commit=False)
doc_save.user = request.user
for fileform in files_form.cleaned_data:
image = fileform['file']
one_image = DocumentFile(document=doc_save, file_value=image)
one_image.save(commit=False)
transaction.commit()
msg = FORM_PROPERTIES.FORM_EXAM_STORED.replace("user", request.user.nickname)
messages.add_message(request, messages.SUCCESS, msg)
form = LoginForm()
context = {'form': form}
return render_to_response(template_name='login.html', context=context, context_instance=RequestContext(request))
else:
messages.add_message(request, messages.SUCCESS, FORM_PROPERTIES.FORM_EXAM_ERROR)
context = {'doc_form': doc_form, 'file_form_set': file_form_set, }
return render(request, 'createexam.html', context)
else:
context = {'doc_form': doc_form, 'file_form_set': file_form_set, }
return render(request, 'createexam.html', context)
my url.py
urlpatterns = [
# Examples:
url(r'^$', home, name='home'),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', home),
url(r'^home', home),
url(r'^login', login),
url(r'^logout', logout),
url(r'^register$', register),
url(r'^createexam$', createexam),
url(r'^account/reset_password', reset_password, name="reset_password"),
]
My template is simple
<div id="login-overlay" class="modal-dialog">
<div class="row">
<div class="panel panel-info" >
<div class="panel-heading">
<div class="panel-title">Créer un examen</div>
</div>
<div class="panel-body" >
<div class="col-sm-12">
<form id="post_form" method="POST" action='.'
enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in doc_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in doc_form %}
{{ field }} <br />
{% endfor %}
{{ file_form_set.management_form }}
{% for form in file_form_set %}
{% crispy form %}
{% endfor %}
<input type="submit" value="Add recipe" class="submit" />
</form>
</div>
</div>
</div>
</div>
Everything seems good form me. But my submit does no think.
I 'm on it for two days.
I read and tried many things. Does anybody can help me please (Sorry for my english)
There are a couple of things wrong here.
Firstly you are not showing the form errors in the template, so the user has no way of knowing why their submission is invalid. Make sure you either do {{ field.errors }} after every field, or do {{ form.errors }} for the whole form at once; and remember to do this both form the main form and the image formset.
Secondly, you're saving the forms with commit=False, so they are not persisted to the database. It's fine to do that if you want to add extra data not included in the form, but you then need to remember to actually persist the object by calling eg doc_save.save().
I solved my problem when i put my main form body in <table> ... </table>
<form id="CreateExamForm" method="POST" enctypr="multipart/form-data">
{% csrf_token %}
<table>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Classe - Matière - Date</h3>
<span class="pull-right"><i class="glyphicon glyphicon-chevron-up"></i></span>
</div>
<div class="panel-body">
{% crispy doc_form %}
{{ file_form_set.management_form }}
{% for f_form in file_form_set %}
<div class="form-inline">
{% crispy f_form %}
</div>
{% endfor %}
</div>
</div>
</table>
<input type="submit" value="Add recipe" class="submit" />
</form>