2017-04-17 59 views
0

我試圖從用戶檢索數據。我想要顯示用戶信息的表單也與我用於更新此信息的表單相同。用相同的表單和模板創建,獲取和編輯用戶信息

UPDATE3

一些更新後,我做這項工作,這是我的代碼。如果somenone有更好的方法,這樣做可以分享:)

models.py

from django.db import models 
from django.contrib.auth.models import User 
# Create your models here. 
class informacionFacturacion(models.Model): 
    usuario = models.ForeignKey(User, on_delete=models.CASCADE) 
    apellidos = models.CharField(max_length=100) 
    nombres = models.CharField(max_length=100) 
    [More fields...] 
    def __str__(self): 
     self.apellidos 

forms.py

from .models import informacionFacturacion 
#Create your forms here. 
class informacionFacturacionForm(ModelForm): 
    class Meta: 
     model = informacionFacturacion 
     fields = [ 
      "usuario", 
      "apellidos", 
      "nombres", 
      [More fields...] 
     ] 

views.py

@login_required 
def datosPersonales(request): 
    #Filter query by user ID 
    query = informacionFacturacion.objects.filter(usuario=request.user) 

    form = informacionFacturacionForm() 
    #If query has content, edit record, else, create a new record 
    if query: 
     if request.method == "POST": 
      form = informacionFacturacionForm(request.POST or None, instance=query[0]) 
      if form.is_valid(): 
       edit_content = form.save() 
       edit_content.save() 

    else: 
     if request.method == "POST": 
      form = informacionFacturacionForm(request.POST) 
      if form.is_valid(): 
       create_content = form.save(commit=False) 
       create_content.save() 
       return HttpResponseRedirect(reverse('datosPersonales')) 

    context = { 
     "titulo": "Datos personales | Co.", 
     "body_class": "class= sidebar_main_open sidebar_main_swipe", 
     "form": form, 
     "infoFacturacion": query, 
    } 
    template = "micuenta/datosPersonales.html" 
    return render(request, template, context) 

感謝您的支持。

回答

1

乍一看,informacionFacturacion表似乎沒有被填充。你有沒有檢查到達instance.save()? (換句話說,表單有效)

其次,在模板中,您希望使用informacionFacturacion對象作爲表單元素,並且您正在分別處理它們。這樣做:

if request.POST: 
    form = informacionFacturacionForm(request.POST) 
    if form.is_valid(): 
     instance = form.save(commit=False) 
     instance.save() 
    else: 
     # handle here the form error's, maybe report it in the template 
else: 
    query = informacionFacturacion.objects.filter(usuario=request.user) 
    form = informacionFacturacionForm(instance=query[0]) 

和渲染的infoFacturacionform參數INSEAD:

{{ form.as_p }} 

最後,請確保您的模板格式ID的形式元素名稱相匹配,否則表單不會被填補。

UPDATE

根據您的編輯,現在的錯誤是在這一行:

form = informacionFacturacionForm(request.POST, instance=query_id) 

query_idint,並期待一個模型。更改以下行:

query_id = informacionFacturacion.objects.get(usuario=request.user).id 

query = informacionFacturacion.objects.get(usuario=request.user) 

和故障線路到:

form = informacionFacturacionForm(request.POST, instance=query) 

應該對現在的工作,儘管代碼可以簡化很多。

EDIT 2

這是我想,你希望:

@login_required 
def datosPersonales(request): 
    query = informacionFacturacion.objects.filter(usuario=request.user) 

    if request.method == "POST": # This will handle the template form's POST 
     form = informacionFacturacionForm(request.POST) 
     if form.is_valid(): 
      asd = form.save(commit=False) 
      asd.save() 
      # Here you may want to redirect to somewhere else 
    # Im not sure here, I guess that you want to handle the GET method if 
    # there is no form in the request. Post your template form to see what 
    # is happening. 
    else: 
     form = informacionFacturacionForm(instance=query) 
     # you dont need to save it, it is already in DB 

    context = { 
     "titulo": "Datos personales | Co.", 
     "body_class": "class= sidebar_main_open sidebar_main_swipe", 
     # I think here is your main issue, you are handling a form object 
     # AND a infoFacturacion object. You need to use just the 
     # form object in the template and render it accordingly. 
     "form": form, 
     "infoFacturacion": query, 
    } 
    template = "micuenta/datosPersonales.html" 
    return render(request, template, context) 
+0

我意識到我無法使用save()編輯內容。我會寫一個if語句來檢查表是否有內容。我可以這樣做:if infoFacturacion:#show edit form else:#show create form。對? –

+0

你是什麼意思的「編輯內容」?對象表單和模板中的表單都是可修改的。如果你想看看來自模板的內容,你可以使用'print request.POST'它會打印一個字典,其中包含在視圖的POST方法中發送的表單的元素。 –

+0

我在這裏要做的是在同一視圖中顯示錶格內容,並在其中編輯表格。我現在會嘗試一些代碼,然後我會更新這篇文章。 –

0

嗯,我是在我的系統正同樣的問題,所以我做了這個解決方案,也許它就會爲您!= d

我改變了提交按鈕的值,並使用相同的形式:

<button type="submit" id="submitButton" name="button" value="">Save</button> 

如果是一個新的任務,我改變了按鈕的值使用jQuery:

$('#submitButton').val('new'); 

如果是編輯,我再次更改值:

$('#submitButton').val('edit'); 

在我的views.py,我檢查,如果是編輯或由新的保存該按鈕的值:

def index(request): 
tasks = Task.object.filter() 
context = { 
    'tasks': tasks 
} 
if request.method == 'POST': 
    form = NewTask(request.POST or None) 
    if request.POST['button'] == 'new': 
     if form.is_valid(): 
      context['is_valid'] = True 
      form.save() 
      form = NewTask() 
     else: 
      context['is_valid'] = False 

    if request.POST['button'] == 'edit': 
     instance = Task.object.filter(pk=request.POST['id']).first() 
     form = NewTask(request.POST, instance=instance) 
     if form.is_valid(): 
      context['is_valid'] = True 
      form.save() 
     else: 
      context['is_valid'] = False 
else: 
    form = NewTask() 

context['form'] = form 
return render(request, 'index.html', context) 
相關問題