简体   繁体   中英

Custom HTML for ManyToMany Field in ModelForm

I am currently working on a form that displays information about a specific product on my website. Each price is represented by a Price object, and each Item has several Price objects associated with it. I have created a ModelForm to display the data in my Item , which works. However, when I try to display the ManyToMany field in my ModelForm, I get a small box that lists all of my Price objects. I need to display custom HTML for the Price objects so that I can have them interact with some JavaScript I have. Below is the code I have thus far:

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})

And the part of my template I am trying to display:

{% for price in form.prices %}
    <span class="price_box" style="width: 200px;">
        <a href="#" class="remove_price">x</a>{{ price.name }} ${{ price.price }}
    <input type="hidden" name="price_name" value="{{ price.name }}">
    <input type="hidden" name="price_cost" value="{{ price.price }}">
    </span>
{% endfor %}

I am not entirely sure how to go about accomplishing this . . .

More specifically, how do I change the HTML for the manytomany display in my form?

One approach is to use an inline_modelformset to edit your prices. This will probably require you to change your Item model to not have a M2M to Price, but rather have Item as an FK to Price.

This way, you can use a custom form for Price, and have one or more instances of a PriceForm that will be automatically related to an Item. The formset will have the delete functionality as well, which you could handle via Ajax if you wish. You could also dynamically add/remove forms.

Hope that helps you out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM