2017-03-05 40 views
1

我希望有人可以給我一些幫助,告訴我如何用Django做以下事情(如果我沒有解釋一切正確,對Django還是個新東西,並且不知道很多事情,請諒解):Django讓用戶通過表單更新網站上的TextField值?

我有一個電影表,那些電影有一個「描述」數據字段,當他們點擊它時,一個表格打開並顯示電影的當前描述。如果他們雙擊這個描述,他們可以改變它,然後保存該值。我做了一個小的GIF以可視化的想法:

enter image description here

至少那這背後的基本理念,到目前爲止我已經成功地使大多數的東西跑,可惜不是Django的部分其中用戶的「新」數據發送到數據庫並替換描述的舊數據。

所以有人可以向我解釋我該如何做這項工作?我知道我可能需要爲我的views.py編寫一個函數,然後創建一個新的url模式,但我無法弄清楚究竟如何。所以任何幫助,歡迎!下面是我的代碼(我希望我已經包括每一個你們需要的文件):

views.py

from django.shortcuts import get_object_or_404, render 
from django.http import HttpResponseRedirect 
from django.urls import reverse 
from django.views import generic 
from django.views.generic.list import ListView 
from .models import * 

class AllMovies(generic.ListView): 
    model = Movie 
    template_name = "consilium/index.html" 
    context_object_name = "latest_movie_list" 

class MovieDetails(generic.DetailView): 
    model = Movie 
    template_name = "consilium/detail.html" 

urls.py

from django.conf.urls import url 
from . import views 
from .models import * 
from django.views.generic.list import ListView 

app_name = "consilium" 
urlpatterns = [ 
    url(r'^$', views.AllMovies.as_view(), name="index"), 
    url(r'^(?P<slug>[\w_0-9]+)/$', views.MovieDetails.as_view(), name='detail'), 
] 

models.py

from django.db import models 
from decimal import Decimal 
from django import forms 
from django.contrib import admin 

class Movie(models.Model): 
    // removed the other models for better overview 
    description = models.TextField('Movie Description') 

    def __str__(self): 
     return self.title 

的index.html

{% extends "consilium/base.html" %} 

{% block body %} 
    <table class="table"> 
     <thead> 
      <tr> 
       <th></th> 
       <th colspan="2">My Movielist</th> 
       <th> 
      </tr> 
      <tr> 
       <th></th> 
       <th>TITLE</th> 
       <th>GENRE</th> 
       <th>RELEASE DATE</th> 
       <th>DIRECTOR</th> 
       <th>DESCRIPTION</th> 
       <th>RUNTIME</th> 
       <th>STATUS</th> 
       <th>IMDB</th> 
      </tr> 
     </thead> 
     <tbody> 
      {% if latest_movie_list %} 
       {% for movie in latest_movie_list %} 
       <tr> 
        <td></td> 
        <td> 
         <a href="{% url 'consilium:detail' movie.slug %}" data-toggle="popover" data-placement="left" data-content='<img class="title-image" src="{{movie.image.url}}"/>'>{{ movie.title }}</a> 
        </td> 
        <td>{{ movie.get_genre_display}}</td> 
        <td>{{ movie.date}}</td> 
        <td>{{ movie.director}}</td> 
        <td id="icn-change" data-toggle="collapse" data-target=".demo{{ forloop.counter }}"> 
        Description <i class="fa fa-caret-right"></i> 
        </td> 
        <td>{{ movie.runtime}} min</td> 
        <td>{{ movie.get_status_display}}</td> 
        <td>{{ movie.imdb}}</td> 
       </tr> 
       <tr> 
        <td></td> 
        <td class="hiddenRow" colspan="8"> 
         <div class="container collapse demo{{ forloop.counter }}"> 
          <div class="row justify-content-center"> 
           <div class="col"> 
            <form method="post" id="usrform">{% csrf_token %} 
             <textarea id="text" class ="form-control" readonly="true" onkeydown="expandtext(this)" ondblclick="this.readOnly='';">{{movie.description}}</textarea> 
            </form> 
           </div> 
          </div> 
          <div class="row justify-content-center"> 
           <div class="col align-self-start">Double Click to Edit</div> 
           <div class="col align-self-end"> 
            <input type="submit" id="set" class="pull-right"/> 
           </div> 
          </div> 
         </div> 
        </td> 
       </tr> 
       {% endfor %} 
       {% else %} 
        <tr> 
         <td>No Movies are available.</td> 
        </tr> 
      {% endif %} 
     </tbody> 
    </table> 
{% endblock %} 

的script.js

// removed all other code for overview 

// replace description text with user input 
    $('#set').click(function() { 
     var test = $('#text').val(); 
     localStorage.setItem("test", test); 
    }); 

    $('#text').text(localStorage.getItem("test")); 

我希望我沒有錯過任何東西,感謝大家誰可以幫我!

+1

未來您正在試圖*更新*現有的Movie實例。在文檔中查看[UpdateView](https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-editing/#updateview)。 –

+0

謝謝,會給它一個讀:) –

回答

0

感謝pythondev slack社區的大力幫助!

views.py:讓我的電影模式

class MovieUpdateForm(forms.ModelForm): 
    class Meta: 
     model = Movie 
     fields = ['description'] 

reverse_lazy的描述字段是很重要的,所以,當我點擊我的按鈕,它不會重定向我康士廉(我的應用程序的名字)/ 2 /更新並保留在我有我的表的索引網站上

class MovieUpdateView(UpdateView): 
    model = Movie 
    form_class = MovieUpdateForm 
    success_url = reverse_lazy('consilium:index') 

網址。潘岳:

url(r'^(?P<pk>[0-9]+)/update/$', views.MovieUpdateView.as_view(), name='movie_update'), 

在這裏,這是我塞URL模式我在我的urls.py之前把這個重要的,否則它不工作:

url(r'^(?P<slug>[\w_0-9]+)/$', views.MovieDetails.as_view(), name='detail'), 

我在我的HTML表單:使用PK = movie.pk所以會搶了正確的電影,給我的textarea的名字「說明」,所以我的方法知道其中數據是從

<form action="{% url 'consilium:movie_update' pk=movie.pk %}" method="post" id="usrform">{% csrf_token %} 
     <textarea id="text" class ="form-control" name="description" readonly="true" onkeydown="expandtext(this)" ondblclick="this.readOnly='';">{{movie.description}}</textarea> 
     <input type="submit" id="set" class="pull-right"/> 
</form> 
1

我在一個類似的項目上工作,這就是我所做的。

from django.forms.models import model_to_dict 

@login_required 
def edit_profile(request): 
    profile, created = ClientProfile.objects.get_or_create(user_id=request.user.id) 
    if request.method == 'POST': 
     form = ProfileSubmissionForm(request.POST, instance=profile) 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect(reverse('jobs:list')) 
    else: 
     profile_dict = model_to_dict(profile) 
     form = ProfileSubmissionForm(profile_dict) 
     return render(request, 'jobs/profile.html', {'form': form}) 

實質上,model_to_dict呈現存儲在表格數據庫中的值。 instance=profile確保我正在更新表單而不是創建新對象。

+0

嘿,首先謝謝你!你能解釋一下我的代碼更詳細嗎?我對整個Python/Django主題還不熟悉,但是我還沒有完全瞭解:)我試着用你的代碼來模擬我的模型,但是它並沒有工作,即使控制檯也沒有給出任何迴應錯誤消息。也不會我必須添加一些東西到我的urls.py並更改我的JavaScript文件? –

+0

'def edit_description(request): description,created = Movie.objects.get_or_create(movie_id = request.movi​​e.id) if request.method =='POST': form = usrform(request.POST,instance = description ) 如果form.is_valid(): form.save() 返回HttpResponseRedirect(反向( 'CONSILIUM:索引')) 否則: profile_dict = model_to_dict(介紹) 形式= usrform(profile_dict) 返回渲染(請求,'consilium/index.html',{'form':form})' 試圖理解你給我一點代碼,是否正確使用? –