Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom HTML for ManyToMany Field in ModelForm
    text
    copied!<p>I am currently working on a form that displays information about a specific product on my website. Each price is represented by a <em>Price</em> object, and each <em>Item</em> has several <em>Price</em> objects associated with it. I have created a ModelForm to display the data in my <em>Item</em>, which works. However, when I try to display the ManyToMany field in my ModelForm, I get a small box that lists all of my <em>Price</em> objects. I need to display custom HTML for the <em>Price</em> objects so that I can have them interact with some JavaScript I have. Below is the code I have thus far:</p> <pre><code>class Item(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) description = models.CharField(max_length=1000) category = models.ForeignKey(Category) prices = models.ManyToManyField(Price, blank=True) images = models.ManyToManyField(Image) runs = models.ManyToManyField(ActivityRun, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.name class ItemForm(ModelForm): class Meta: model = Item description = forms.CharField(widget=TinyMCE()) @login_required def edit_item(request, item_id): item = get_object_or_404(Item, pk=item_id) if request.method == 'POST': form = ItemForm(request.POST, request.FILES, instance=item) if form.is_valid(): return HttpResponseRedirect("/items/") else: form = ItemForm(instance=item) return render(request, 'edit_item.html', {'form': form}) </code></pre> <p>And the part of my template I am trying to display:</p> <pre><code>{% for price in form.prices %} &lt;span class="price_box" style="width: 200px;"&gt; &lt;a href="#" class="remove_price"&gt;x&lt;/a&gt;{{ price.name }} ${{ price.price }} &lt;input type="hidden" name="price_name" value="{{ price.name }}"&gt; &lt;input type="hidden" name="price_cost" value="{{ price.price }}"&gt; &lt;/span&gt; {% endfor %} </code></pre> <p>I am not entirely sure how to go about accomplishing this . . .</p> <p>More specifically, how do I change the HTML for the manytomany display in my form?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload