当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Updating fields of model using forms and views on Django 1.7

问题描述:

In models.py my Product model is

class Product(models.Model):

productName = models.CharField(max_length=20, default='1',blank=False,null=False, primary_key = True)

userPhone = models.CharField(max_length=20, default='1')

userid = models.ForeignKey(Account, default='1',null=True)

productDesc = models.TextField(blank=False,null=False, default='1')

productCategory = models.ForeignKey(Category, null=False, default='1')

productPrice = models.DecimalField(default='0',blank=False,null=False, max_digits=6, decimal_places=2)

picture = models.ImageField(upload_to='product_images', blank=True, null=True, default='1')

def __unicode__(self):

return self.productName

The form that I have to add new Products is,

class ProductForm(forms.ModelForm):

productName = forms.CharField(label='Product Name')

productCategory = forms.ModelChoiceField(label='Category', queryset=Category.objects.all())

productDesc = forms.CharField(label='Product Description', widget=forms.Textarea)

productPrice = forms.DecimalField(label='Expected Price')

userPhone = forms.CharField(label='Phone Number')

picture = forms.ImageField(label='Upload Picture')

class Meta:

model = Product

fields = ('productName', 'productCategory', 'productDesc', 'productPrice', 'userPhone', 'picture',)

def clean_productName(self):

productName = self.cleaned_data['productName']

try:

Product.objects.get(productName=productName)

except Product.DoesNotExist:

return productName

raise forms.ValidationError("A product under that name already exits. Rename your product.")

def clean_productCategory(self):

productCategory = self.cleaned_data['productCategory']

def clean_productDesc(self):

productDesc = self.cleaned_data['productDesc']

def clean_productPrice(self):

productPrice = self.cleaned_data['productPrice']

def clean_userPhone(self):

userPhone = self.cleaned_data['userPhone']

def clean_picture(self):

picture = self.cleaned_data['picture']

And to take form input, I have in my views.py file

@login_required(login_url='/accounts/login/')

def newProduct(request):

if(request.method =='POST'):

product_form = ProductForm(request.POST, request.FILES)

if product_form.is_valid():

product = product_form.save(commit=True)

product.save()

else:

print product_form.errors

else:

product_form = ProductForm()

return render(request, 'market/postad.html', {'product_form':product_form} )

I want to update the userid field of Product model to the user_id of the logged in user. How do I go about doing that?

request.user.id

might give me the id of the logged in user. But how do I associate that with the product that is being entered into the database? (I am using MySQL database)

My AUTH_USER_MODEL isn't configured to Account. Is there any way to do it without configuring it?

My Account model is

class Account(models.Model):

user = models.OneToOneField(User)

I imported User from django.contrib.auth.models

网友答案:

In views.py (if your AUTH_USER_MODEL configured to Account)

@login_required(login_url='/accounts/login/', template_name='market/postad.html')   
def newProduct(request):
    product_form = ProductForm(request.POST or None, request.FILES or None)
    if(request.method =='POST'):
        if product_form.is_valid():
            product = product_form.save(commit=False)
            product.userid = Account.objects.get_or_create(user=request.user)
            product.save()
        else:
            print product_form.errors
    return render(request, template_name, {'product_form':product_form} )
分享给朋友:
您可能感兴趣的文章:
随机阅读: