【问题标题】:Updating django "notes" section with ajax使用 ajax 更新 django “notes”部分
【发布时间】:2021-12-21 14:02:09
【问题描述】:

我查看了文档并观看了视频,并提出了另一个关于堆栈溢出的问题,但就是不明白如何在我的 django 项目中使用 ajax。本质上,我有一个从 for 循环返回的区域管理器列表(这里是 models.py、views.py 和 detail.html 显示):

models.py

class TM(models.Model): #Change this to territory manager and delete database and recreate
    Name = models.CharField(max_length = 200,null=True)
    Cell = models.CharField(max_length= 200, null=True)
    EmailAddress = models.EmailField(null=True)
    Notes = models.CharField(max_length=500, null=True)
    Distributor = models.CharField(max_length=200,null=True)
    State = models.CharField(max_length=200,null=True)
    Brand = models.CharField(max_length=200,null=True)

    def __str__(self):
        try:
            if self.Distributor is not NullBooleanField:
                return self.Name + ' - ' + self.Distributor + ' - '  + self.State
        except TypeError: 
            return self.Name

views.py

def detail(request):
    
    try:
        if request.method == 'POST':
            state = request.POST['state']
            brand = request.POST['brand']
            territory_manager = TM.objects.filter(State__icontains=state).filter(Brand__icontains=brand)
            return render(request,'homepage/detail.html', {'state': state, 'territory_manager':territory_manager})
        else:
            state = request.POST['state']
            brand = request.POST['brand']
            return render(request,'homepage/detail.html', f"No Results for {state} or {brand}")
    except TM.DoesNotExist:
        raise Http404("Info Does Not Exist")

table in detail.html

<table class= "content-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Distributor</th>
                            <th>State</th>
                            <th>Brand</th>
                            <th>Cell</th>
                            <th>Email</th>
                            <th>Notes</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                        {% for tm in territory_manager %}
                            <td style="white-space:nowrap;">{{ tm.Name }}</td>
                            <td style="white-space:nowrap;">{{ tm.Distributor }}</td>
                            <td style="white-space:nowrap;">{{ tm.State }}</td>
                            <td style="white-space:nowrap;">{{ tm.Brand }}</td>
                            <td style="white-space:nowrap;">{{ tm.Cell }}</td>
                            <td style="white-space:nowrap;">{{ tm.Email }}</td>
                            <td id='notes' contenteditable="True">{{ tm.Notes }}</td>
                            <td><button id="note_submit" type="button">Update</button></td>  
                        </tr>
                        {% endfor %}
                        </tr>
            
                        </tbody>
                </table>

它会加载一个页面,其中包含区域经理的姓名、电子邮件、电话和备注部分。我已使注释部分可编辑并希望使用 ajax,因此当有人编辑注释部分并点击更新按钮时,更新的注释将保存到数据库并显示给用户。我尝试将几个不同的 SO 答案拼凑在一起,但无济于事。这是我所拥有的:

script placed at the bottom of my detail.html

<script>
            $(document).ready(function () {   
                $(document).on("click",'.notes_submit', function() {
                    $.ajax({
                        url: "/ajax/",
                        type: "POST",
                        data: {action: 'note_update', note: document.getElementById("notes").value},
                        success: function(data){
                            $("#notes").html("<strong>"+data.note+"</strong>");                
                            }
                    });
                });
            });
            
            </script> 

functions in views.py

def post(self,request, *args, **kwargs):
    if self.request.is_ajax():
        return self.ajax(request)

def ajax(self, request):
    response_dict= {
        'success': True,
    }
    action = request.POST.get('action','')

    if action == 'note_submit':
        note_id = request.POST.get('id','')

    if hasattr(self, action):
        response_dict = getattr(self, action)(request)
        note = TM.objects.get(Note='note_id')
        response_dict = {
            'note_name':note.name
        }

    return render(simplejson.dumps(response_dict),
                        mimetype='application/json')

任何方向表示赞赏。谢谢!

【问题讨论】:

    标签: django ajax


    【解决方案1】:

    您在 ajax 调用中省略了 url 选项。在这种情况下,请求被发送到当前页面。在您的情况下,这将是详细视图,它不处理 ajax 请求。

    并将数据选项中的 EventListener 替换为注释的内容。

    $.ajax({
        url: // PUT THE URL TO YOUR AJAX HANDLING VIEW HERE //,
        type: "POST",
        data: {action: 'note_update', note: document.getElementById("notes").textContent;},
        success: function(data){
          $("#notes").html("<strong>"+data.note+"</strong>");                
          }
        });
    

    【讨论】:

    • 非常感谢您的回复!那么我在 ajax 调用中输入的 url 是否必须指向另一个 .html 模板?因为我试图让 detail.html 页面只更新而无需导航。我还更新了上述帖子的script placed at the bottom of my detail.html 部分并尝试再次运行它,但没有任何反应。有没有其他我贴错标签的东西你可以看到?谢谢! @yagus
    • 不,网址应该指向处理您的 ajax 请求的视图。在您的情况下,它是“ajax”视图,它不会呈现新模板。这是一个后端操作,与任何 html 无关。我建议您熟悉 Django MVT 设计的基础知识。否则,将难以实现更高级的概念,例如 ajax。 @贾斯汀本菲特
    • 好的,谢谢!我会做更多的研究
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多