I have a Django formset that I wish to display inline using bootstrap3, but I keep getting the error ManagementForm data is missing or has been tampered with. I've included the {{formset.management_form}} in my html template so I'm not sure why I'm getting this error. Can anyone help me out?
My form looks like this:
class MasterForm(forms.Form):
def __init__(self,*args,**kwargs):
initial_date_start = kwargs.pop('initial_start')
initial_date_end = kwargs.pop('initial_end')
sc_arg_list = kwargs.pop('sc_arg_list')
sc_section_label = kwargs.pop('sc_section_label')
tt_arg_list = kwargs.pop('tt_arg_list')
tt_section_label = kwargs.pop('tt_section_label')
super(MasterForm,self).__init__(*args,**kwargs)
self.fields['WINDOW_START'].initial=initial_date_start
self.fields['WINDOW_END'].initial=initial_date_end
self.fields['sc_ID'].choices=sc_arg_list
self.fields['sc_ID'].label=sc_section_label
self.fields['scID'].choices=sc_arg_list
self.fields['scID'].label=sc_section_label
self.fields['tasktype'].choices=tt_arg_list
self.fields['tasktype'].label=tt_section_label
WINDOW_START = forms.CharField(required=True,label="WINDOW_START")
WINDOW_END = forms.CharField(required=True,label="WINDOW_END")
sc_ID = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple)
scID = forms.ChoiceField(required=True, widget=forms.RadioSelect)
tasktype = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple)
The view that uses it looks like this:
FormSet = formset_factory(MasterForm)
keys = {'initial_start':"1/2/2015",'initial_end':"1/20/2015",'sc_arg_list':sat_list,'sc_section_label':"Please Select A Satelite",'tt_arg_list':task_type,'tt_section_label':"Please Select Task Type"}
if request.method == 'POST':
formset = FormSet(request.POST,keys)
if(formset.is_valid()):
message = "Thank you"
for form in formset:
print form
form.save()
else:
message = "Something went wrong"
else:
formset = FormSet(keys)
return render(request, 'InterfaceApp/gantt_search.html', {'formset': formset})
And the Django template that I am using looks like this:
<form action="/InterfaceApp/gantt_search/" method="post" class="form">
{{ formset.management_form }}
{% csrf_token %}
{% bootstrap_formset formset %}
{% buttons %}
<div class="text-center">
<span class="btn-group">
<button type="submit" class="btn btn-primary center-block" value="Submit" name="All_Planning">
{% bootstrap_icon "fire" %} All Planning
</button>
<button type="submit" class="btn btn-primary center-block" value="Submit" name="Ops_Only">
{% bootstrap_icon "filter" %} Ops Only
</button>
</span>
</div>
{% endbuttons %}
</div>
</form>
I'm not missing the {{formset.management_form}} tag so I'm not sure why Django is telling me that it's not there.
Thanks.
Related
I have been trying to create a to do list app and there has been no problems until when i was adding an edit button, when i press the edit button, it shows the edit page with the text that has to be edited but the submit button that is suposed to change the database is not working, I think I need to add something to the views.py file but I dont know what.
viws.py
def edit(request, id):
created_items = Create.objects.get(id=id)
return render(request, 'my_app/edit.html', {"created_items": created_items})
urls.py
urlpatterns = [
path('edit/<int:id>/', views.edit, name='edit'),
]
models.py
class Create(models.Model):
added_date = models.DateTimeField()
text = models.CharField(max_length=200)
edit.html
{% extends 'index.html' %}
{% block body %}
<div align="center">
<h1>Edit your post!</h1>
<div class="container form-group">
<h1>↓</h1>
<form method="POST">{% csrf_token %}
<textarea class="form-control" name="content" id="id" rows="3" style="text-align: center;">{{ created_items.text }}</textarea>
<button type="submit" class="btn btn-outline-success" style="margin-top: 5px;">Submit</button>
</form>
</div>
</div>
{% endblock %}
You will send POST request when you click submit and need to catch that request in some function like:
if request.method == 'POST':
edited_text = request.POST.get('text') ## 'text' might be changed. I don't know how you handle the request.
related_id = request.POST.get('id') ## You need to take updated id. (somehow?)
Create.objects.filter(id=related_id).update(text=edited_text) ## That will do the job.
Hope it helps,
if there's anyone who knows how can I delete images user, I made a code to do that but I cannot continue I get some stuck. so if anyone could tell me which way can I make it this method?
also, I need to know about the outputs of (userprofile) in (delete_avatar) if this code is true how can I know it? I tried using print and repr but I didn't find this useful. so, anybody can get me help?
views.py
# Update Avatar
#login_required
def add_avatar(request, user_id):
my_logo = request.user.userprofile
form = AddAvatar(instance=my_logo)
get_userid = UserProfile.objects.filter(user_id=user_id)
context = {'form': form, 'get_userid': get_userid}
if request.method == 'POST':
form = AddAvatar(request.POST, request.FILES, instance=my_logo)
if form.is_valid():
form.save()
return redirect('account:view_profile')
return render(request, 'account/change-image.html', context)
# Remove Avatar
#login_required
def delete_avatar(request, user_id):
my_request = request.POST.get('rm-img')
userprofile = UserProfile(my_request)
pdb.set_trace()
if request.method == "POST":
del_img = UserProfile.objects.get(user_id=user_id).logo.delete() # delete object
return redirect('account:view_profile')
return render(request, 'account/change-image.html')
change-image.html
{% extends 'base.html' %}
{% block title %} Add New Image {% endblock %}
{% block body %}
<!-- Add new image for user-profile -->
<div class="change-image">
<div class="add-image">
<div class="container">
<h1>This Image Is Current, <br>Choose Your Image From Your Personal Computer Or Delete</h1>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<label>{{ user.first_name }} {{ user.last_name }}</label>
{{ form.as_p }}
<button type="submit" class="btn btn-success">Change Now</button>
<input type="submit" name="rm-img" class="btn btn-danger" value="Remove Image">
</form>
</div>
</div>
</div>
{% endblock %}
the file html above where I can make a form to update and delete the user image
urls.py
urlpatterns = [
path('new-image/<int:user_id>/', views.add_avatar, name="add_avatar"),
path('del-image/', views.delete_avatar, name="delete_avatar"),
]
forms.py
class AddAvatar(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['logo']
I'm trying to filter ListView based on post method from search bar in my basetemplate. So making it works like:
Insert name --> SearchBar-->GET Method-->SearchView class(in views.py)--> render html with usernames.
I have done this, but it wont work. Could you please tell me what I'm doing wrong?
views.py in my user app
class SearchView(ListView):
model = User
template_name = 'blog/list_of_users.html'
context_object_name = 'all_search_results'
def get_queryset(self):
result = super(SearchView, self).get_queryset()
query = self.request.GET.get('search')
if query:
postresult = User.objects.filter(username__contains=query)
result = postresult
else:
result = None
return result
urls.py in my blog app
path('users_search/?search=<str:username>', user_view.SearchView.as_view(), name='user_search'),
search form in html
<form class="example" method="GET">
<input type="search" placeholder="ユーザー検索..." name="user_name">
<button type="submit">
検索
</button>
rendered html with user names
{% for result in all_search_results %}
{{ result.username }}
{% empty %}
add something to show no results
{% endfor %}
override get_context_data method
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user_name = self.request.GET.get('user_name', '')
context['all_search_results'] = User.objects.filter(username__icontains=user_name )
return context
In your template
<form class="example" method="GET">
<input type="text" placeholder="ユーザー検索..." name="user_name">
<button type="submit">
検索
</button>
</form>
{% for result in all_search_results %}
{{ result.username }}
{% empty %}
add something to show no results
{% endfor %}
Update:
in template, <input ........... name="search">
in views, user_name = self.request.GET.get('search', '')
I have a form that in layman's terms, has a bunch of buttons (that act like checkboxes) with values. Users can select a handful of buttons.
The buttons push their values (via a JQuery function) into a hidden input which I'm using to gather the values.
I would like to make sure that the "values=" attribute of each hidden input isn't null or "" when the user presses the submit form.
Ex: Make sure that the input does NOT equal this:
<input autocomplete="off" id="id_valuePlatform" name="valuePlatform" type="hidden"> or
<input autocomplete="off" id="id_valuePlatform" name="valuePlatform" type="hidden" value="">
Here's the forms.py:
class getGames(forms.Form):
valuePlatform = forms.CharField(required=True, error_messages={'required': 'You need to tell us your platform(s)!'}, widget=forms.HiddenInput(attrs={'autocomplete': 'off'}))
Template:
<form method= "POST" autocomplete="off"> {% csrf_token %}
{{ form.non_field_errors }}
<div class="container">
{% if form.valuePlatform.errors %}
<ol>
{% for error in form.valuePlatform.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %}
</div>
{{ form.valuePlatform }}
</div>
</div>
</form>
Views.py:
from .forms import getGames
def find(request):
form = getGames()
context = {"form": form}
if form.is_valid():
print form.cleaned_data['valuePlatform']
Is this even possible, or would I have to pass the data to Django via a Ajax POST?
Changed views.py to this, after looking at # Alasdair's examples in the documentation:
from .forms import getGames
def find(request):
form = getGames(request.POST or None)
context = {"form": form}
if request.method == 'POST':
if form.is_valid():
print form.cleaned_data['valuePlatform']
i am not able to upload an image from html page but it is possible from admin page
here is my models.py:
def get_upload_file_name(instance,filename):
return "image/%s_%s"%(str(time()).replace('.','_'),filename)
class Company_Profile(models.Model):
user = models.ForeignKey(User)
name = models.CharField(_('Company Name'), max_length= 30)
logo = models.FileField(_('Company Logo'), upload_to=get_upload_file_name)
address = models.TextField(_('Contact Address'), max_length=50)
phone_no = models.IntegerField(_('Contact No'), max_length=12)
my views.py:
def company_prof(request):
if request.method == 'POST':
comp_prof = Company_Prof(request.POST, request.FILES)
if comp_prof.is_valid():
save_prof = comp_prof.save(commit=False)
save_prof.user = request.user
save_prof.save()
messages.success(request, 'Thank you for Registration')
return HttpResponseRedirect('company/'+str(save_prof.id))
else:
comp_prof =Company_Prof()
variables = RequestContext(request, {
'comp_form': Company_Prof()})
return render_to_response("comp_profile.html",
locals(),
context_instance = RequestContext(request))
my settings.py is:
MEDIA_ROOT ='G:\Mini project\Pycharm projects\project4\static/'
MEDIA_URL = ''
html page is:
<form enctype="application/x-www-form-urlencoded" class="global_form" action="" method="post"><div><div><h3>Create Account</h3>
<div id="connect_signup_box" class="connect_box_form clearfix">
<form method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ comp_prof.as_p }}
<input type="submit" class="btn btn-success" value="submit">
{% if save_prof %}
<h3>The details are submitted</h3>
{% endif %}
<input type="reset" class="btn" value="cancel">
{% if value == 'cancel' %}
<h3>Canceled</h3>
{% endif %}
</form>
</div>
</div>
</div>
</form>
when i submit it says no files are chosen. but from admin page there is no problem.
help me..
I think the problem is you have nested forms, which isn't supported by browsers (Can you nest html forms?).
So I am assuming that the browser is just using the first form definition, which has the wrong enctype. Try removing the first form declaration and just keeping this one: <form method="POST" enctype="multipart/form-data">.