Error in models running Django 1.9.5 - django

Whenever I try to run, I'm getting the following error described below. Already I researched a solution, but I can not make it work.
Exception Type: ValueError
Exception Value:
ModelForm has no model class specified.
Exception Location: /usr/local/lib/python2.7/dist-packages/django/forms/models.py in init, line 275
Python Executable: /usr/bin/python
Python Version: 2.7.6
Erro Traceback
File "/home/ubuntu/workspace/envelope/views.py" in cad_professor
67. form = ProfessorForm()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in init
275. raise ValueError('ModelForm has no model class specified.')
views.py
#login_required(login_url='/login/')
def cad_professor(request):
context = {}
if request.method == 'POST':
form = ProfessorForm(request.POST)
if form.is_valid():
form.save()
context['success'] = True
else:
form = ProfessorForm()
context['form'] = form
template_name = 'envelope/cad_professor.html'
return render(request,template_name , context)
forms.py
from django import forms
from .models import Professor
class ProfessorForm(forms.ModelForm):
class meta:
model = Professor

Your meta spelling is wrong. Change to:
class ProfessorForm(forms.ModelForm):
class Meta:
model = Professor

Related

App works with ModelChoiceField but does not work with ModelMultipleChoiceField

I am trying to retrieve user input data in a django page. But I am unable to choose to multichoice field. I have tried multiple alternatives to no relief.
self.fields['site'].queryset=forms.ModelMultipleChoiceField(queryset=sites.objects.all())
self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id))
self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)])
forms.py
class SearchForm(forms.Form):
class Meta:
model= images
fields=['site']
def __init__(self,*args,**kwargs):
project_id = kwargs.pop("project_id") # client is the parameter passed from views.py
super(SearchForm, self).__init__(*args,**kwargs)
self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id))
views.py
def site_list(request, project_id):
form = SearchForm(project_id=project_id)
site_list = sites.objects.filter(project__pk=project_id).annotate(num_images=Count('images'))
template = loader.get_template('uvdata/sites.html')
if request.method == "POST":
image_list=[]
form=SearchForm(request.POST,project_id=project_id)
#form=SearchForm(request.POST)
#site_name=request.POST.get('site')
if form.is_valid():
site_name=form.cleaned_data.get('site')
print(site_name)
I expect to get a multiselect field but I end up getting this error:
Exception Value:
'site'
Exception Location: /home/clyde/Downloads/new/automatic_annotator_tool/django_app/search/forms.py in init, line 18
(line 18:self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)]))
You are not defining your form correctly. The documentation shows you how to do this.
In your case it would be something like this:
class SearchForm(forms.Form):
site = forms.ModelMultipleChoiceField(queryset=Sites.object.none())
def __init__(self,*args,**kwargs):
project_id = kwargs.pop("project_id")
super(SearchForm, self).__init__(*args,**kwargs)
self.fields['site'].queryset = Sites.objects.filter(project_id=project_id))
You also appear to be confusing regular Form and ModelForm, as Meta.model is only used in ModelForm whereas you are using a regular Form. I suggest you read up on the difference in the documentation before you proceed.

MultipleObjectsReturned- get() returned more than one mPurchase -- it returned 2

I am beginner to django. While trying to save mPurchase form I am getting MultipleObjectReturned error. I am trying to get data from form using POST request. Every time I submit the form I am getting an error.
views.py
def milkPurchase(request):
title='Buy Milk'
milk = mPurchase.objects.all()
if request.method=='POST':
form=mPurchaseForm(request.POST)
if form.is_valid():
m = get_object_or_404(mPurchase)
m.mPurchase_date=timezone.now()
m.save()
return redirect('milk-purchase')
else:
form=mPurchaseForm()
context = {
'title': title,
'form': form,
'milk':milk
}
return render(request,'dairyapp/milk-purchase.html',context)
forms.py
class mPurchaseForm(forms.ModelForm):
"""
This form is for milk purchase
"""
seller=forms.CharField(
label='Seller Name',
max_length=50,
)
mPurchase_product=forms.ChoiceField(
choices=MILK_CHOICES,
label='Milk Type',
initial='',
widget=forms.Select(),
required=True
)
mPurchase_qty=forms.FloatField(
label='Qty'
)
mPurchase_rate=forms.FloatField(
label='Rate'
)
class Meta:
model=mPurchase
fields=('seller','mPurchase_product','mPurchase_qty','mPurchase_rate',)
here is my
models.py
class mPurchase(models.Model):
mPurchase_id=models.AutoField(primary_key=True)
seller=models.CharField(max_length=50)
mPurchase_date=models.DateTimeField(default=timezone.now)
mPurchase_product=models.CharField(max_length=10,choices=MILK_CHOICES)
mPurchase_qty=models.FloatField()
mPurchase_rate=models.FloatField()
def __str__(self):
return self.seller
Can you please help me get through this? I have tried using
mPurchase.objects.filter()
Also, tried to catch exception using ObjectDoesNotExist and MultipleObjectReturned
from django.core.exceptions import ObjectDoesNotExist,
MultipleObjectsReturned
You need to change in here:
if request.method=='POST':
form=mPurchaseForm(request.POST)
if form.is_valid():
m = form.save(commit=False) # <--- Here
m.mPurchase_date=timezone.now()
m.save()

django Markdown problems

Django:1.11.5
Python:3.5.2
Markdown 2.6.9 https://pypi.python.org/pypi/Markdown/
views.py
from django.shortcuts import render
from .models import Post
import markdown
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
Post.content = markdown.markdown(Post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
# Create your views here.
models.py
from django.db import models
import django.utils.timezone as timezone
class Category(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(blank = True, null = True)
pub_date = models.DateTimeField(default=timezone.now)
update_time = models.DateTimeField(auto_now=True)
category = models.ForeignKey(Category)
# Create your models here.
Error message
AttributeError at /
'DeferredAttribute' object has no attribute 'strip'
Request Method: GET
Request URL: http://www.balinzuoqi.com/
Django Version: 1.11.5
Exception Type: AttributeError
Exception Value:
'DeferredAttribute' object has no attribute 'strip'
Exception Location: /usr/local/lib/python3.5/dist-packages/markdown/__init__.py in convert, line 355
Python Executable: /usr/bin/python3
Python Version: 3.5.2
Python Path:
['/data/mysite',
'/usr/local/bin',
'/usr/lib/python35.zip',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-i386-linux-gnu',
'/usr/lib/python3.5/lib-dynload',
'/usr/local/lib/python3.5/dist-packages',
'/usr/lib/python3/dist-packages']
Do not know where there is a problem.
Remove Post.content = markdown.markdown (Post.content), show normal!
English is not my native language; please excuse typing errors.
You are reading content from and writing content to the Post class, not an instance of the class. You need to iterate through the list and update each instance:
def home(request):
Post_list = Post.objects.all().order_by('-pub_date')
for post in Post_list:
post.content = markdown.markdown(post.content)
return render(request, 'home.html',
context={'Post_list':Post_list})
Whether that is a recommended way of converting Markdown to HTML to pass to a template is another matter. Its been a few years since I've used Django, but that wasn't how it used to be done. However, that is a different question.
Regardless, you were not actually passing any Markdown text to the Markdown parser as you were not using an instance of the class. With the for loop I added above, the Markdown content for each 'Post' is now being passed to the Markdown parser.

attribute error method object has no attribute

Im new to Django Framework and i'm taking an online course on LinkedIn Learning. I am using a newer version of python/django so I run into some syntax problems.
my python version is 3.5.4rc1.
my django version is 1.11.4
I created a model in models.py for an inventory:
class Item(models.Model):
titel = models.CharField(max_length=200)
omschrijving = models.TextField()
aantal = models.IntegerField()
This is the code in my views.py file:
from django.shortcuts import render
from django.http import Http404
from inventory.models import Item
def index(request):
items = Item.objects.exclude(aantal=0)
return render (request, 'inventory/index.html', {
'items': items,
})
return HttpResponse('<p>In index view</p>')
def item_detail(request, id):
try:
item = Item.objects.get.id=(id) #THIS ONE CAUSES PROBLEM???
except Item.DoesNotExist:
raise Http404('Dit item bestaat niet')
return render(request, 'inventory/item_detail.html', {
'item': item,
})
In the browser the localhost:8000 shows homepage as expected.
localhost:8000/item/1/ gives error:
AttributeError at /item/1/
'method' object has no attribute 'id'
Request Method: GET
Request URL: http://localhost:8000/item/1/
Django Version: 1.11.4
Exception Type: AttributeError
Exception Value:
'method' object has no attribute 'id'
Exception Location:
C:\Users\info_000\Desktop\django\mysite\inventory\views.py in item_detail, line 15
Please Help!
item = Item.objects.get(id=id)
^^^
# id = field_name of primary key in your model as string ('id' on default)
# id = your local variable 'id' from function signature

Error while dealing with Django UserProfile form.

This is my view for User registration:
def user_reg(request):
UserReg = modelformset_factory(UserProfile)
if request.method == 'POST':
formset = UserReg(request.POST)
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/thanks/')
else:
formset = UserReg()
return render_to_response("regform.html",{"formset":formset,})
This is my models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
name = models.CharField(max_length = 100)
reg_no = models.TextField(unique=True)
password = models.CharField(max_length=128)
The error I get is:
Exception Type: DatabaseError at /register/
Exception Value: column auth_userprofile.name does not exist
LINE 1: ..._userprofile"."id", "auth_userprofile"."user_id", "auth_user...
I've two questions here:
1. Obviously, i want to know why I'm getting the error and how to debug.
2. Is this the right way to go about it or should a define it in forms.py and then import it? The model formset I meant. The django documentation showed that this way it can be done.
The error is a database error, you need to add the column "name" to the table "auth_userprofile". I'd highly recommend looking into "South" for all your database schema migration needs.