Please see to the screenshot, unable to figure out the reason why the drop down don’t show the last value ‘Person 6’ while, its been populated in the html of that page.
Request help to understand the issue - Thank you!
DropDown not getting updated
DropDown not reflecting data on html
Scenario is, user clicks the ‘+’ button and a modal form opens. Form to add new party will be displayed. Once the user clicks submit button on the modal form, the modal closes and the dropdown is expected to be updated, but, instead its not getting updated though the page html reflects the new addition.
Including the view which resulted this issue.
views.py
#login_required
def AddView(request):
addForm = AddForm(request. POST or None)
if request.method == "POST":
if addForm.is_valid():
addForm.save()
response = HttpResponseRedirect(reverse('entry: entries'))
response ['HX-Trigger'] = 'Partyadded'
return response
else:
addForm = AddForm()
context = {
'addForm': addForm
}
return render(request,"entry/addNew.html",context)
Part of the template the “new_entry.html” does have the form to make new entry.
<div id='form-div' hx-trigger="load, Partyadded from: body">
{% include 'partials/new_entry.html' %}
</div>
Related
I show two solutions, one with GET, the other with Javascript. In both I need to double click the back button to come back to the previous page. I think this is a Django problem.
GET case
In templates I have the following form:
<form id="form-user" action="" method="GET">
<select id="user" data-slug="{{x.user}}" onChange=selectChange(this)>
<option value="">choose</option>
<option value="view">View</option>
</select>
</form>
<script>
function selectChange(select) {
var selectID = select.id;
var value = select.value;
if ($('#'+selectID).data('slug')) {
var my_slug = $('#'+selectID).data('slug');
var my_url = "{% url 'profiles:profile-detail' slug=none %}".replace(/none/, my_slug.toString());
}
if (value == 'view'){
$("#form-"+selectID).attr("action", my_url);
$("#form-"+selectID).submit();
}
}
</script>
In views.py I have:
class ProfileView(DetailView):
model = Profile
def get_object(self, *args, **kwargs):
myslug = self.kwargs.get('slug')
user = User.objects.get(username=myslug)
profile = Profile.objects.get(user=user)
return profile
In urls.py I have:
path('<slug>/', views.ProfileView.as_view(), name='profile-detail'),
This approach takes me to the profile page of {{x.user}}=user1, however when I click the backward button in the browser, it goes from mypath/user1 to mypath/user1?. I don't like this ?. To go back to the previous page I would need to click the backward button twice. I would like to click it only once and remove this ? transition step.
Javascript case
views.py doesn't change as it is not needed. template is quite similar, we just remove the method="GET" in the HTML form tag, while in the javascript we only change the following:
if (value == 'view'){
window.location.href = my_url;
}
Here also, I manage to go to the user page, however to come back to the previous page I need a double click, in this case it goes from mypath/user1 to mypath/user1 and then to the previous page.
I do believe it is a django problem but I'm not sure if we can solve it
EDIT:
As suggested a request POST solution is not required in this case. Also views.py is better written as:
def get_object(self, *args, **kwargs):
slug = self.kwargs.get('slug')
return get_object_or_404(Profile, user__username=slug)
However this doesn't fix the problem.
What about just a link?
View
Through CSS, you can style the link as a button or something else. This will trigger a GET request. A POST request makes not much sense, since you do not change the state: GET requests are supposed to have no side-effects, and POST requests are normally used to create, update, or remove data.
Your view can also be simplified: fetching the User is not necessary:
from django.shortcuts import get_object_or_404
class ProfileView(DetailView):
model = Profile
def get_object(self, *args, **kwargs):
return get_object_or_404(Profile, user__username=myslug)
I have a question on my homepage that the user should answer through radio buttons. The user should press the submit button to send the answer, so basically it is a SELF PAGE submission. The user should not go to another page after submitting the answer but should remain on the same home page. Though I looked up some earlier questions, the code did not work out.
I have created the TEMPLATE DIRECTORY under the root folder and under this directory, there is a 'pages' folder that has the index.html (homepage) inside which I am invoking the form
The form code in the index.html page.
<form action = "?" method = "POST">
I want to know what function should I write in the views. Since the form action does not call a named view I am not able to figure out how I should define the view that updates the data.
def WHAT NAME SHOULD I GIVE HERE(request):
.....other code
I am adding the following code as of 3rd May. When I use this code I get the error. I would like to state that in the form the questions.id is coming from the questions model (or table) but in the function in the views, I want to update the question.id in the questionid field in the answers model
ValueError at /updateans/updateans
Cannot assign "''": "Answers.questionid" must be a "Questions" instance.
The relevant code in the form is
<form action = "{% url 'updateans' %}" method = "POST">
<input type = "hidden" name ="questionid" value = "{{Questions.id}}">
The function in the views file is (as of now I am just trying to update one field but still getting an error - see above)
def updateans(request):
if request.method == 'POST':
questionid = request.POST["questionid"] 'variable questionid defined
print(questionid) --> even the print command shows a blank
myans = Answers(questionid=questionid)
'questionid is a field in the Answers model
myans.save()
Thanks
After Form Submission redirect the user to the same page
def answer_submit(request):
if request.method == 'POST':
name = request.POST["name"]
subject = request.POST["subject"]
email = request.POST["email"]
message = request.POST["message"]
con = Contact(name=name,subject=subject,email=email,message=message)
con.save()
# If u use messages module of django then the next line will work
messages.success(request,"Thank you for contacting us, We will get to you as soon as possible")
return redirect("home.html")
The is some thing like this u just need to redirect the user to same page
I am trying to show the user a summary of a form before the form is submitted and saved to the server.
I have a form on index.html and within that form, I have this input button:
<input type="submit" value="Show summary" name="summary"/>
On the summary.html page, I have another input button within a dummy form. I use this input button to get the form data saved.
<input type="submit" value="Save to DB" name="save_db" />
Here are code snippets of my the methods in my views:
def index(request):
form = JobForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
return summary(request)
return render_to_response('index.html', {'form': form}, context_instance=RequestContext(request))
def summary(request):
if request.method == 'POST':
save_to_db(request) # The problem here is that this is a new request. I lost the previous request with all the data
return render_to_response('thanks.html', context_instance=RequestContext(request))
xml = getxml(request) # form data is serialized
return render_to_response('summary.html', {'xml': xml}, context_instance=RequestContext(request))
From the above, I am able to get a summary of the form data. However, as the inline comment suggests, when I click the "Save to DB" submit button, the previous request with all the form data is lost.
I have looked into Sessions and I could not find a proper of doing the above. I also tried to pass the request as a parameter to the the summary page. However, I think this is not the right way of doing it.
I would appreciate your input!
Thanks.
Have you tried Django Form Preview? Seems that is exactly you are looking for:
Django comes with an optional “form preview” application that helps
automate the following workflow: “Display an HTML form, force a
preview, then do something with the submission.” To force a preview of
a form submission, all you have to do is write a short Python class.
Cheers!
I have a form which includes filefield to upload some files.
Sometimes what happens is at first, I select one file from browse to upload but then i realize i do not want to upload it anymore.How can i make it empty again??
Is it like that once this field is filled it cannot be reverted back to empty??
Thanks in advance
This can be accomplished with javascript.
Quoting Clear upload file input field with jQuery post from electrictoolbox.com:
function reset_html(id) {
$('#'+id).html($('#'+id).html()); }
$(document).ready(function() {
var file_input_index = 0;
$('input[type=file]').each(function() {
file_input_index++;
$(this).wrap('<div id="file_input_container_'+
file_input_index+'"></div>');
$(this).after('<input type="button" value="Clear"
onclick="reset_html(\'file_input_container_'+
file_input_index+'\')"
/>');
});
});
If you try to post an un-validated form, when you re-render the form, the filefield will be empty.
See this issue for more explanation..
Django Form File Field disappears on form error
The following works for me. Add a clear button to your html
<input type="submit" name = "submit-clear" value="clear file">
Then in your view handle this button using..
if 'submit-clear' in request.POST:
return HttpResponseRedirect('')
This should clear any filefields but will also remove any other settings the user has made, if you want to preserve other settings and just remove the filefield, then ensure the form does not validate somehow so that it renders again.
For one of my models, I want to show extra content in the change_form. Basically, my model looks like this:
class News(models.Model):
...
class NewsFromSource(models.Model):
news = models.ForeignKey(News)
...
I want to add a 'search' button that, when clicked, triggers a web service request to an external news source, pulls down the available content, and lists all the news pieces contained. The user can then select one of the pieces to "attach" to the News currently edited in the admin interface (i.e. create a new NewsFromSource based on the content downloaded through the web service).
I am done with the web service. What is the best approach to implementing the search-button, list display for the results (I have a view and template that work, need to get those into the form somehow) and the saving part?
What I ended up doing is the following:
1)
I created a view for fetching search results, which boils down to this:
#/myproject/admin/views.py
#never_cache
def news_search(request):
#...query web service
if 'q' in request.POST:
search_term = request.POST['q']
else:
search_term = ''
news = NewsSearch()
news.search(search_term)
return render_to_response( 'news_search_results.html',
{ 'q': search_term,
'news': news.result_list,
'page': page,
'page_left': news.page_left,
'page_right': news.page_right}
)
2) I mapped the view:
#/myapp/urls.py
...
url(r'^myapp/news/search/$', views.news_search),
3) I extended change_form.html for the news model with the following code:
#/myproject/templates/admin/myapp/news/change_form.html
{% extends "admin/change_form.html" %}
{% block after_field_sets %}
...
{% csrf_token %}
<input type="text" name="q" id="news-search-term">
<div id="news-search-results"></div>
...
function submitSearchForm() {
$.post("/myapp/news/search/",
{ 'q': $('#news-search-term').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() },
function(data){
$('#news-search-results').html(data);
}
);
}
{{ block.super }}
{% endblock %}
4) I created an html template for displaying the results (news_search_results.html, see 1)
So basically I am sending an AJAX request from the admin page to a custom view to retrieve results from the webservice which then are displayed in a div.
Each element in the results list has a button that sends another request that stores the element with the news id as a ForeignKey.
I have no idea whether this is particularly against Django principles. But it seems to work alright.
Suggestions on doing this in a more "Djangonian" way are welcome.
We'll assume you have a related News model. Add that field to raw_id_fields of the modeladmin we're going to hack, then:
Overload the change_form template for this model, extend admin/change_form.html in admin/yourapp/yourmodel/change_form.html
Add javascript in that template to:
Hide the input and magnifier icon from the news raw id field form raw, you can do that in css too
Add something like a span with a button style in that form row that will open a popup when it is clicked
The popup it should open should be your working view/template with a form to select the news
When the user selects a news, the popup should do an ajax post request to get the news id, and close itself
the value is set to the raw id field input that is hidden, this is pretty tough but fear not someone (disclamer: I) published an article with the whole technical details, also found another one but I didn't test it
It's going to be quite some work. Patience and perseverance will be your best qualities for this mission B)