我是django的新手,我有以下问题。当我使用createCompany.html登录并创建公司时,公司将在数据库中创建,但其用户'属性保持空白。 user属性应该是登录并创建公司的用户。您认为我的代码有什么问题?
models.py
from django.db import models
from django.contrib.auth.models import User
class Company(models.Model):
name = models.CharField(primary_key = True, max_length = 100)
city = models.CharField(max_length = 30, null = True)
user = models.OneToOneField(User, on_delete=models.SET_NULL, null = True)
yontemler =(('3CNC', '3 eksen CNC'),('5CNC', '5 eksen CNC'),)
imalatyontem = models.CharField(max_length=30, choices=yontemler, null=True, verbose_name = 'İmalat Yöntemleri')
industries =(('Imalat', 'İmalat'),('Kimya', 'Kimya'),('Hammadde', 'Hammadde'),)
industry = models.CharField(max_length=20, choices=industries, null=True, help_text='Sektörünüzü Seçin')
@classmethod
def create(cls, name, city, user, imalatyontem, industry):
company = cls(name=name, city=city, user=user, imalatyontem=imalatyontem, industry=industry)
return company
def get_absolute_url(self):
return models.reverse('company-detail', args=[str(self.id)])
def __str__(self):
return self.name
views.py
from .forms import CompanyCreationForm
def createCompany(request):
if request.method == 'POST':
form = CompanyCreationForm(request.POST)
if form.is_valid():
form.save()
name = form.cleaned_data.get('name')
city = form.cleaned_data.get('city')
user = request.user
imalatyontem = form.cleaned_data.get('imalatyontem')
industry = form.cleaned_data.get('industry')
Company.create(name, city, user, imalatyontem, industry)
return redirect('index')
else:
form = CompanyCreationForm()
return render(request, 'createCompany.html', {'form': form})
forms.py
from django import forms
from .models import Company
class CompanyCreationForm(forms.ModelForm):
class Meta:
model = Company
fields = ['name', 'city', 'imalatyontem', 'industry']
createCompany.html
{% extends "base_generic.html" %}
{% block content %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form action="/createCompany/" method="post">
{% csrf_token %}
{% for field in form %}
<fieldset class="control-group">
<label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label>
<div class="controls">
{{ field }}
<p class="help-text">{{ field.help_text }} </p>
</div>
</fieldset>
{% endfor %}
<input type="submit" value="Submit" />
</form>
{% endblock %}
答案 0 :(得分:2)
你的create
班级方法毫无意义;你应该删除它。它不会保存对象,然后扔掉它。
在添加用户之前,创建实例的工作实际上是由form.save
完成的。所以你应该使用标准模式:
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
return redirect('index')