I have the following models, view and template:
models.py:
class Batch(models.Model):
material_id = models.ManyToManyField(AssetMetadata)
user = models.ForeignKey(User)
def __str__(self):
return 'Batch_' + str(self.pk) + '_' + self.user.username
class AssetMetadata(models.Model):
material_id = models.CharField(max_length=256, blank=True)
series_title = models.CharField(max_length=256, blank=True)
season_title = models.CharField(max_length=256, blank=True)
season_number = models.IntegerField(default=0)
episode_title = models.CharField(max_length=256, blank=True)
episode_number = models.IntegerField(default=0)
synopsis = models.TextField(max_length=1024, blank=True)
ratings = models.CharField(max_length=256, blank=True)
def __str__(self):
return self.material_id
views.py:
def assets_in_repo(request):
asset_list = AssetMetadata.objects.order_by('id').all()
page = request.GET.get('page', 1)
paginator = Paginator(asset_list, 50)
try:
assets = paginator.page(page)
except PageNotAnInteger:
assets = paginator.page(1)
except EmptyPage:
assets = paginator.page(paginator.num_pages)
if request.method == 'POST':
batch_list = request.POST.getlist('batch')
print(batch_list)
return render(request, 'assets_db/assets.html', {'assets': assets})
snippet from template:
<form method="post">{% csrf_token %}
<input type="submit" value="Create Batch" align="right">
<table class="table table-striped" id="myTable">
<tr>
<th>ID</th>
<th>Material ID</th>
<th>Series Title</th>
<th>Season Tile</th>
<th>Season Number</th>
<th>Episode Title</th>
<th>Episode Number</th>
<th>Create Batch</th>
</tr>
{% for i in assets %}<tr>
<td>{{i.pk}}</td>
<td><a href="/repo/{{ i.id}}">{{i.material_id}}</a></td>
<td>{{i.series_title}}</td>
<td>{{i.season_title}}</td>
<td>{{i.season_number}}</td>
<td>{{i.episode_title}}</td>
<td>{{i.episode_number}}</td>
<td>
<input type="checkbox" name="batch" value="{{i.pk}}">
</td>
</tr>{% endfor %}
</table>
</form>
I am trying to get the data provided from the checkbox and save it in the Batch model.
The user selects assets to create a batch, the form returns the pk for these assetss in AssetMetadata and the selections are stored in a list create via batch_list = request.POST.getlist('batch'). I want to use the data stored in this list to create a new entry in Batch which then links to the asset pk in AssetMetadata.
I have been able to do this successfully in the Django admin page but i would ideally do this in teh view.
I have read https://docs.djangoproject.com/en/1.10/ref/models/relations/ and search stackoverflow but i am stumped as how to do this.
info = Batch.objects.create(season_title ='foo', .....)
info2= AssetMetadata.objects.create(material_id ='some')
info.material_id.add(info2)
try something like this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With