Django 自定义表单单选按钮

0 投票
2 回答
897 浏览
提问于 2025-04-18 11:28

我在我的模板里有两个单选按钮,一个是喜欢,另一个是不喜欢,用户只能选择其中一个。我在模板里写了以下代码,虽然能正常工作,但看起来真的很丑,我想把它美化一下。

  <input type="radio" name="Like" value="Like">Like<br>
  <input type="radio" name="Like" value="Dislike">Dislike

我在视图中使用了这些按钮的名称和数值。

 if request.POST.get('Like') == 'Like':
                con = UserContent(time=time, comment = comment, liked = True, disliked = False, doctor_id = doctor.id, user_id = request.user.id)
                doctor.likes += 1
                doctor.netlikes = doctor.likes - doctor.dislikes
                doctor.save()
                con.save()

            elif request.POST.get('Like') == 'Dislike':
                con = UserContent(time=time, comment = comment, liked = False, disliked = True,  doctor_id = doctor.id, user_id = request.user.id)
                doctor.dislikes +=1
                doctor.netlikes = doctor.likes - doctor.dislikes
                doctor.save()
                con.save()

我希望模板里的按钮能变成图片按钮,样子像这样。

    <div class="like">
         <input type = "radio" name = "Like" value = "like" <img style="max-width: 100px;"src="/static/meddy1/images/like_option.png">
        </div>

        <div class="dislike">
           <input type = "radio" name = "Like" value = "Dislike" <img style="max-width: 100px;"src="/static/meddy1/images/dislike_option.png">
        </div>

我尝试过这样做,但都不行。我不确定单选按钮是不是最好的选择。我只想让其中一个被选中,因为它们是表单的一部分。有没有什么好的办法可以实现呢?

2 个回答

0

如果我要做你想做的事情,我会用两个按钮,然后在点击按钮的时候发送一个$POST请求到服务器...

所以你有两个按钮:

<style>
.vote{
    background-color:#CCCCCC;
}
.vote:hover{
    background-color:#666666;
    color:white;
}
</style>

<button class="vote" data-type="like">Like</button>
<button class="vote" data-type="dislike">Dislike</button>

一旦点击其中任何一个,这个函数就会把数据发送到服务器。记得你需要发送一个csrf令牌到服务器,否则会出现403错误,除非你在django视图中使用@csrf_exempt,但我不推荐这样做。

$(".vote").click(function(){
    var vote = $(this).data('type');
    var token = "{{ csrf_token }}";
    var url = "your/url/"

    jQuery.post(url, { vote: vote , csrfmiddlewaretoken: token  } , function(data) {
      // ## deal with the response...
    });
}); 

在服务器上:

把csrf令牌包含在渲染按钮模板的视图中。我通常会把所有东西放在一个params字典里:

params = {}
params.update(csrf(request))
params['whatever'] = "another variable that you need to send to the template"
params['other']= "you get the point, right?"

## render the view with the params
## they become accessible on the template like this : {{ whatever}}

return render_to_response('your_template_name',params)

在处理POST请求的视图中使用类似这样的代码:

try:
    vote = request.POST['vote']
    ## do whatever you need with the vote value
except:
    ## deal with the exception here

把所有东西整合在一起:

网址

url(r'^votes/$',  'app_name.views.votes', name='votes'),

视图

from django.core.context_processors import csrf
from django.shortcuts import render_to_response, redirect
from django.http import HttpResponse

def votes(request):
    params = {}
    params.update(csrf(request))

    if request.method == 'POST':
        ## Processing
        try:
            vote = request.POST['vote']
            ## do whatever you need
            return HttpResponse('Your vote was '+vote)
        except:
            return HttpResponse('There was an error')

    else:
        ##Displaying the initial view 
        return render_to_response('votes_template',params)

模板

<script type="text/javascript" src="/static/jquery.js"></script>

<style>
.vote{
    background-color:#CCCCCC;
}
.vote:hover{
    background-color:#666666;
    color:white;
}
</style>

<button class="vote" data-type="like">Like</button>
<button class="vote" data-type="dislike">Dislike</button>

<script>
$(document).ready(function(){
    $(".vote").click(function(){
        var vote = $(this).data('type');
        var token = "{{ csrf_token }}";
        var url = "/votes/"

        jQuery.post(url, { vote: vote , csrfmiddlewaretoken: token  } , function(data) {
            alert(data)
        });
    }); 
}); 
</script>

老实说,我也做不到更好。我注意到你已经为这个问题挣扎了几天,所以这是我能给出的最佳答案。

0

那里有个拼写错误,导致图片看不见。你可以试试这样:

    <div class="dislike">
       <input type = "radio" name = "Like" value = "Dislike" ><img style="max-width: 100px;" src="/static/meddy1/images/like_option.png">
    </div>

    <div class="like">
       <input type = "radio" name = "Like" value = "Like" ><img style="max-width: 100px;" src="/static/meddy1/images/like_option.png">
    </div>

撰写回答