Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python - Django data save model without form in template

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...