How to get selected radio button value to pass to UpdateView in Django? - radio-button

I want to get selected value by radio button and pass it to the update view but I couldn't find a way. Both views are class based.
Exception Value:
Reverse for 'update-author' with no arguments not found. 1 pattern(s) tried:
ListView :
class Dashboard(ListView):
model = Author
template_name='catalog/dashboard.html'
def get_context_data(self, **kwargs):
context = super(EditDashboard, self).get_context_data(**kwargs)
context["authors"] =Author.objects.all()
context["publishers"] =Publisher.objects.all()
context["genres"] =Genre.objects.all()
return context
UpdateView:
class UpdateAuthor(UpdateView):
model = Author
fields = '__all__'
template_name='catalog/updateauthor.html'
context_object_name = 'author'
Model:
class Author(models.Model):
first_name = models.CharField(max_length=200, blank=False)
last_name = models.CharField(max_length=200, blank=False)
date_of_birth = models.DateField(null=True, blank =True)
date_of_death = models.DateField(null=True, blank =True)
class Meta:
ordering = ['first_name', 'last_name']
def __str__(self):
return f' {self.first_name} {self.last_name}'
Form in template :
<form action="{% url 'update-author' ????? %}" method="post">
{% csrf_token %}
{% for author in authors %}
<input type="radio" name="choice" id="{{ author.id }}" value="{{ author.id }}">
<label for="author">{{ author.first_name}} {{ author.last_name}}</label><br>
{% endfor %}
<input type="submit" value="Update">
</form>

So if I understand you have a listView with all the authors publishers and genres, and you want to call the updateView with the author selected.
One way is to use javascript:
give an id to the form tag :
map an event on click to the submit button
get the selected radiobox element and value
change the form action value with the value you get
call the submit event
Here is some sample of Jquery you can use to do that:
$(document).ready(function(){
$('#myformid').submit(function(event) {
//prevent the form submition on click
event.preventDefault();
//get the selected value
var selected_author_id =$('input[name="choice"]:checked').val();
console.log(selected_author_id);
//add this value to our form action attribute
$(this).attr('action', 'update-author/'+String(selected_author_id));
//finaly submit the form
$(this).unbind('submit').submit();
});
});
Don't forget to import jquery as well

Related

Send List of IDs from List of Object From View to Controller C#

I have a view with a list of objects as its model
#model List<Users>
Inside that view, I have a form and button to submit the form in ASP.NET Core MVC:
<input class="btn btn-success ml-2" style=" width: 100px;"
type="submit" value="#localizer["Save"]" />
I need another button to cancel form submission and redirect to another method but I need to pass the list of Users with redirection at cancel button
I tried
<a asp-controller="User" asp-action="cancel" asp-route-ids="#Model.Select(x => x.id);">Cancel</a>
but it didn't work, the list is empty
If you use asp-route-somekey to set the query, your target list name was recognized as value of the key "Ids",you could see the result as below:
If you do want to pass list to the query,you could try:
<a asp-controller="User" asp-action="Cancel" asp-all-route-data="#(new Dictionary<string, string> { { "Ids[0]", "1" },{ "Ids[1]", "2" } })">Cancel</a>
The result:
However the length of url is limited, it may cause some errors

Bootstrap select dropdown not rendering viewbag items

For some reason my list is showing up disabled I am trying to use bootstrap-select here
https://developer.snapappointments.com/bootstrap-select/
This is my code that gets the items there is nothing wrong with it as 3 items exist in the view bag
public void GetStandardLookups(int LookupGroupId) {
List<SelectListItem> listItems = new List<SelectListItem>();
var items = _context.StandardLookups.Where(w => w.LookupGroup == LookupGroupId).ToList();
foreach (var item in items) {
SelectListItem listItem = new SelectListItem();
listItem.Text = item.LookupText;
listItem.Value = item.Id.ToString();
listItems.Add(listItem);
}
if(LookupGroupId == Constants.EnforcmentType)
ViewBag.EnforceMentTypesList = listItems;
if (LookupGroupId == Constants.EnforcmentCategory)
ViewBag.EnforcmentCategoryList = listItems;
}
I Create the dropdown as such after storing in the view bag on the controller action of edit. But when I look at the raw html all i have is. This is three rows of data in the database that should be pulling through and I debugged my code and it is getting three items in list Items.
Nothing selected
I am initializing my bootstrap select as follows
$(function () {
$('.selectpicker').selectpicker();
})
I am producing my drop down as follows.
#Html.DropDownListFor(x => x.Enf_Type, (IEnumerable<SelectListItem>)ViewBag.EnforceMentTypesList, String.Empty, new { #class = "selectpicker form-control" })
My Edit action
I did a test using same bootstrap-select you share with testing data, which work as expected.
its shows the words nothing to select and is disabled non clickable
Please check if the html source of dropdown-toggle button with CSS class 'disabled' like below.
<button type="button" class="btn dropdown-toggle disabled btn-light bs-placeholder" data-toggle="dropdown" role="combobox" aria-owns="bs-select-1" aria-haspopup="listbox" aria-expanded="false" data-id="Enf_Type" tabindex="-1" aria-disabled="true" title="Nothing selected"><div class="filter-option"><div class="filter-option-inner"><div class="filter-option-inner-inner">Nothing selected</div></div> </div></button>
And if rendered <select> element with disabled attribute.
<select class="selectpicker form-control" data-val="true" data-val-required="The Enf_Type field is required." disabled="disabled" id="Enf_Type" name="Enf_Type" tabindex="-98"><option value="">
You can try to programmatically enable a selectpicker with following code snippet.
$('.selectpicker').prop('disabled', false);
$('.selectpicker').selectpicker('refresh');

How can I access a model attribute from a queryset with a template tag?

I've added the following model's objects to my view using the get_context_data() method.
models.py:
class Icon(models.Model):
icon_name = models.CharField(max_length=100, default='iconset')
icon = models.ImageField(upload_to='machine_icon/', null=True, blank=True)
def __str__(self):
return str(self.icon_name)
views.py
class MachineSorter(DetailView):
model = MachineCount
template_name = 'brands/machines.html'
def get_context_data(self, **kwargs):
context = super(MachineSorter, self).get_context_data(**kwargs)
context['icon'] = Icon.objects.all()
return context
I can loop through the icons easily and display them like this:
{% for obj in icon %}
<img src="{{ obj.icon.url }}">
{% endfor %}
But I DO NOT want to loop through them, I just want to access an individual icon image where needed, such as:
<img src="{{ icon.name.url }}">
...or something to that effect. When it comes to using additional context in views, the examples I see all use loops. What am I missing here? Any help would be appreciated.
did you tried to retrieve just what you need with a query?
https://docs.djangoproject.com/en/2.2/topics/db/queries/#retrieving-objects

How to render the user profile avatar image into the wagtail template?

I am creating a blog site using the Wagtail CMS. I would like to display the Author avatar image whenever a new post is published. I am trying to render the image from this /admin/account/change_avatar/ location. I can see the image uploaded here is under the wagtailusers_userprofile -> col name: avatar table, but not sure how to render it in the template.
This image isn't a typical Wagtail Image (one that comes from wagtailimages.Image), this looks like a regular models.ImageField.
Here's what's in the UserProfile model for the avatar:
class UserProfile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='wagtail_userprofile'
)
avatar = models.ImageField(
verbose_name=_('profile picture'),
upload_to=upload_avatar_to,
blank=True,
)
Because this is a regular image field, you can get the url by appending .url in your template.
Here's some example template code:
{% if request.user.is_authenticated %}
{% if request.user.wagtail_userprofile.avatar %}
<img src="{{ request.user.wagtail_userprofile.avatar.url }}" alt="{{ request.user.get_full_name }}">
{% else %}
{# No image #}
{% endif %}
{% endif %}
The above code will check to see if the user is authenticated in the template. If you don't need it, ditch it.
THen there's the if statement to checks of the request.user.wagtail_userprofile.avatar exists. The wagtail_userprofile comes from the user field on the UserProfile model. It's using a related_name, so we use that in the template.
I also sprinkled in a {{ request.user.get_full_name }} for the alt tag, because the image alt should probably be the users name in this case, rather than the file name.
If you need the height or width, those are both available through the {{ request.user.wagtail_userprofile.avatar.height }} and {{ request.user.wagtail_userprofile.avatar.width }}.

Way to store data in shopify

I have a requirement, where in I have 4 different drop down on shopify home page. The First drop-down, let's name it city-drop-down, will show list of city. Based on the city selected in city-drop-down, the second drop down, lets name it category-drop-down, will show list of categories available for particular city. Similarly the third drop down should show the value based on the 2nd drop down and 4th drop down should show the value based on 3rd drop down.
Basically, I need to store list of categories available for each city. Similarly I have to store values available for each categories. How can I store this value, so that the moment a value is selected on webpage, I can use a AJAX call to get the available data for next drop down.
Edited *****
Do let me know, if I am doing it totally wrong.
Included the scripts. Please note, initially I uploaded the files under "Files". However I moved it to Assets folder as it was easier to edit the file in Assets folder.
function readcityfile(){
var xmlhttp = new XMLHttpRequest();
var url = "/assets/city_type.txt";
alert("hi");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try{
var myArr = JSON.parse(xmlhttp.responseText);
alert(myArr);
//myFunction(myArr);
}
catch(err) {
alert(err.message);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction(arr) {
var i;
for(i = 0; i < arr.length; i++) {
alert(arr[i].city);
}
}
And the JSON file is -
[{"city": "Jamshedpur","types": "Sweets#Savories#Cake"},{"city": "Ranchi","types": "Sweets#Savories#Cake"}]
One simple way if the data size isn't too large would be to generate your data as a JSON file and simply store it as a file and then edit your theme to include the file's url. A file that is too large might be 100k. Smaller is better but if you don't have a back end to handle the AJAX calls the static file certainly provides a low cost proof of concept.
There are two ways to do this.Either as an asset or a file. Assets are part of your theme so even though you'll be altering your templates to manage this I'd tend to go with a file. (Assets are just files located under the theme but the are dealt with slightly differently)
go to your Shopify Admin control panel
Click Settings
Click Files
Click "Upload Files"
After upload you'll have a file. The next step uses the file's name not its URL.
Go to your theme editor:
Shopify Admin control panel
Online Store
Themes
click Customize Theme
drop-down Theme Options and select HTML/CSS
I'm guessing you are going to select the template product.liquid to edit.
do that and decide where you want to introduce your javascript file. If your script file was named cities_etc.js you'd import it as below:
{{ 'cities_etc.js' | file_url | script_tag}}
This method seems a bit slow if all that you are trying to do is create a tiered menu. Using Ajax requests will mean there are several round trips and it will be visually slow for the user waiting for the ajax request to complete.
You can create a linklist
I know you have already found your method but I would strongly urge you to give this a go. Here is an example of some liquid markup that will created a tiered menu. The parent linklists handle is main-menu then you need to create a linklist for each of the children where the handle matches the title in the main-menu. For example if you have an 'About Us' link in the main menu create a linklist also with the handle 'about-us'. Then just use some simple css or javascript to hide and show the menus on hover.
{% for link in linklists.main-menu.links %}
{% assign child_list_handle = link.title | handleize %}
{% if linklists[child_list_handle].links != blank %}
<li class="dropdown" aria-haspopup="true" data-id="{{ child_list_handle}}">
<a href="{{ link.url }}" class="nav-link {% if link.active %} active{% endif %}">
{{ link.title }}
</a>
<ul class="dropdown_menu hidden" id="{{ child_list_handle }}">
{% for childlink in linklists[child_list_handle].links %}
<li>
{{ childlink.title | escape }}
</li>
{% endfor %}
</ul>
</li>
{% else %}
<li>
{{ link.title }}
</li>
{% endif %}
{% endfor %}