Reputation: 43
I want to save a value in the database when the button is clicked without using a form. I want to save the value in h2 to another model when the button is clicked. What can i do?
TEMPLATE
<div class="widget-main">
<center><h2 name="urun" value="{{ urun.urun_adi }} ">{{ urun.urun_adi }}</h2></center>
</a>
<input type="submit" onclick="location.href='{% url 'sepete_ekle' %}'" value = "sepete ekle" class="btn btn-sm btn-default pull-right">
Sepete Ekle
</input>
<a href="" class="btn btn-sm btn-success">{{urun.fiyat}} TL</a>
</div>
VIEWS
def sepete_ekle(request):
if request.method == 'POST':
urun = request.POST["urun"]
status = 0
urunler = Siparis.objects.create(urun,status)
urunler.save()
messages.success(request, " Sepete Eklendi")
return redirect('/bayi/profil_duzenle')
else:
return HttpResponseRedirect("/")
MODEL
class Siparis(models.Model):
bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"})
urun = models.ForeignKey(Urun, on_delete=models.CASCADE)
adet = models.IntegerField()
tarih = models.DateTimeField()
status = models.BooleanField()
class Meta:
verbose_name = 'Bayi Sipariş'
verbose_name_plural = 'Bayi Siparişleri'
Upvotes: 0
Views: 3301
Reputation: 1156
Replace the html posted by you in problem statement with the below one.
<div class="widget-main">
<center>
<h2>{{ urun.urun_adi }}</h2>
</center>
<form method="POST" action="{% url 'sepete_ekle' %}">
<input type="hidden" value="{{ urun.urun_adi }}" name="urun" />
<input
type="submit"
value="sepete ekle"
class="btn btn-sm btn-default pull-right"
/>
</form>
<a href="" class="btn btn-sm btn-success">{{urun.fiyat}} TL</a>
</div>
to know more about form hidden fields, here is a simple explaination for reference check this out
Upvotes: 1
Reputation: 2084
Once try this, I hope it works. Change view.py to this. Add an arguement to your function sepete_ekle.
def sepete_ekle(request,urun):
if request.method == 'POST':
status = 0
urunler = Siparis.objects.create(urun,status)
urunler.save()
messages.success(request, " Sepete Eklendi")
return redirect('/bayi/profil_duzenle')
else:
return HttpResponseRedirect("/")
And urls.py to this:
path('/path/to/function/<urun>',views.sepete_ekle,name='sepete')
And in your html file:
<div class="widget-main">
<center><h2 name="urun" value="{{ urun.urun_adi }} ">{{ urun.urun_adi }}</h2></center>
</a>
<input type="submit" onclick="location.href='{% url 'sepete_ekle' %}'" value = "sepete ekle" class="btn btn-sm btn-default pull-right">
Sepete Ekle
</input>
<a href="{% url 'sepete' urun.urun_adi %}" class="btn btn-sm btn-success">{{urun.fiyat}} TL</a>
</div>
So, when you click the button the h2 value will be sent in the url and in the view it will be taken from the arguement.
Upvotes: 0