i have read a few of the examples regarding integrirty errors caused by appending _id to the end of an attribute but most of them regard user_id which is not the error i have - mine is dealing with a setting the initial value of a foreign key to another model (recipe has fk to cookbook)
so here is my trace
IntegrityError at /cookbook/createrecipe/
(1048, "Column 'original_cookbook_id' cannot be null")
Request Method: POST
Request URL: http://127.0.0.1:8000/cookbook/createrecipe/
Django Version: 1.3.1
Exception Type: IntegrityError
Exception Value:
(1048, "Column 'original_cookbook_id' cannot be null")
Exception Location: /Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/connections.py in defaulterrorhandler, line 36
Python Executable: /usr/bin/python
Python Version: 2.6.1
def createrecipe(request):
form = RecipeForm(request.POST)
if request.method == 'POST':
if form.is_valid():
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
recipe = form.save()//error
...
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form': form,
})
data = {
'form': t.render(c),
as you can probably see i have a foreign_key named original_cookbook that i want to set initial to the cookbook of the user.
any idea what might be causing this i can send more code if needed
thanks
snackerfish
.....
form = RecipeForm(request.POST)
if request.method == 'POST':
if form.is_valid():
recipe = form.save(commit=False)
recipe.original_cookbook = request.user.cookbooks.all()[0]
recipe.save()
Related
i am trying to save both FK data as well as tags into same model. FK is the user. user has to submit the question and tags like stack overflow. but i am not able to save both of them. it looks some issue at my views. Can you please help.
ValueError at /qanda/askquestion/
Question objects need to have a primary key value before you can access their tags.
Request Method: POST
Request URL: http://127.0.0.1:8000/qanda/askquestion/
Django Version: 2.2.4
Exception Type: ValueError
Exception Value:
Question objects need to have a primary key value before you can access their tags.
Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/taggit/managers.py in get, line 424
Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7
Python Version: 3.7.4
Python Path:
['/Users/SRIRAMAPADMAPRABHA/Desktop/IampythonDEV/iampython',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
'/Users/SRIRAMAPADMAPRABHA/Library/Python/3.7/lib/python/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
Models.py
class Question(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
question_number = models.AutoField(primary_key=True)
question_category=models.ForeignKey(Question_Category,related_name='questioncategory',on_delete=models.CASCADE)
question_title=models.CharField(max_length=250)
question_slug = models.SlugField(unique=True, max_length=250)
question_description=RichTextField()
question_tags = TaggableManager()
question_posted_at=models.DateTimeField(default=datetime.now,blank=True)
question_status= models.IntegerField(choices=STATUS, default=1)
question_updated_on= models.DateTimeField(auto_now= True)
def __str__(self):
return self.question_title
views.py
#login_required
def createQuestion(request):
if request.method == 'POST':
form = QuestionAskForm(request.POST)
if form.is_valid():
new_question=form.save(commit=False)
question_title = request.POST['question_title']
new_question.slug = slugify(new_question.question_title)
new_question=request.user
new_question.save()
form.save_m2m()
messages.success(request,'You question is succesfully submitted to the forum')
return redirect('feed')
else:
form = QuestionAskForm()
return render(request,'qanda/askyourquestion.html',{'form':form})
I want to submit both foreign key and as well as tag to the database. I am not able to do the tags. Please let me know your thoughts?
By writing:
new_question=request.user
now new_question is no longer a Question object, but it is simply the User object you use. You should edit the new_question.user object instead. For example with:
#login_required
def createQuestion(request):
if request.method == 'POST':
form = QuestionAskForm(request.POST)
if form.is_valid():
form.instance.slug = slugify(form.instance.question_title)
form.instance.user = request.user
form.save()
messages.success(request,'You question is succesfully submitted to the forum')
return redirect('feed')
else:
form = QuestionAskForm()
return render(request,'qanda/askyourquestion.html',{'form':form})
By using form.instance before saving the form, you prevent having to do the saving process yourself (saving the object and the many-to-many relations).
Note: Normally model fields have no prefix with the name of the model. This makes
queries longer to read, and often want uses inheritance of (abstract) models to
inherit fields, so using a prefix would make it less reusable. Therefore it
might be better to rename your field question_title to title.
I've just started playing with formsets. No idea what I'm doing at the moment.
I've got to the point where a form with formset is being saved to the database. However, if nothing is selected for the required field "ledger" then validation still passes, and Django throws up "Key error".
My forms.py:
class JournalEntryForm(forms.Form):
date = forms.DateField(widget=DateTypeInput())
description = forms.CharField(required=False)
class LineItemForm(forms.Form):
ledger = forms.ModelChoiceField(queryset=Ledger.objects.all())
description = forms.CharField(required=False)
project = forms.ModelChoiceField(queryset=Project.objects.all(), required=False)
cr = forms.DecimalField(decimal_places=2, required=False)
dr = forms.DecimalField(decimal_places=2, required=False)
My function in views.py. I've marked line 33 which is the line where the "key error" occurrs.
#login_required
def entries_new(request):
# Takes form and returns form set. So we now have a form set.
LineItemFormSet = formset_factory(LineItemForm, extra=2)
if request.method == 'POST':
journal_entry_form = JournalEntryForm(request.POST)
lineitem_formset = LineItemFormSet(request.POST)
if journal_entry_form.is_valid() and lineitem_formset.is_valid():
q0 = JournalEntry(user=request.user, date=journal_entry_form.cleaned_data['date'], type="JE")
q0.save()
for lineitem_form in lineitem_formset:
q1 = LineItem(
journal_entry=q0,
ledger=lineitem_form.cleaned_data['ledger'], #<---- This is line 33 referenced in the error
cr=lineitem_form.cleaned_data['cr'],
dr=lineitem_form.cleaned_data['dr'],
project=lineitem_form.cleaned_data['project'],
)
q1.save()
messages.success(request, "Journal entry successfully saved.")
return HttpResponseRedirect(reverse('journal:entries_show_all') )
else:
journal_entry_form = JournalEntryForm()
lineitem_formset = LineItemFormSet()
context = { 'journal_entry_form': journal_entry_form, 'lineitem_formset': lineitem_formset, }
return render(request, 'journal/entries_new.html', {'journal_entry_form': journal_entry_form, 'lineitem_formset': lineitem_formset})
The error I get in my browser:
KeyError at /journal/entries/new/
'ledger'
Request Method: POST
Request URL: http://localhost/journal/entries/new/
Django Version: 3.0
Exception Type: KeyError
Exception Value:
'ledger'
Exception Location: C:\Users\Philip\CodeRepos\Acacia2\Journal\views.py in entries_new, line 33
Python Executable: C:\Users\Philip\CodeRepos\Acacia2\venv\Scripts\python.exe
Python Version: 3.8.0
Python Path:
['C:\\Users\\Philip\\CodeRepos\\Acacia2',
'C:\\Users\\Philip\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\Philip\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\Philip\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\Philip\\AppData\\Local\\Programs\\Python\\Python38-32',
'C:\\Users\\Philip\\CodeRepos\\Acacia2\\venv',
'C:\\Users\\Philip\\CodeRepos\\Acacia2\\venv\\lib\\site-packages']
Server time: Thu, 26 Dec 2019 20:42:45 +0000
So after some digging, it turns out that Django does not validate any empty formsets. I added the following init to my form and now I get a nice formerror if an empty formset is submitted:
class LineItemForm(forms.Form):
ledger = forms.ModelChoiceField(queryset=Ledger.objects.all(),)
description = forms.CharField(required=False)
project = forms.ModelChoiceField(queryset=Project.objects.all(), required=False)
cr = forms.DecimalField(decimal_places=2, required=False)
dr = forms.DecimalField(decimal_places=2, required=False)
# This init disallows empty formsets
def __init__(self, *arg, **kwarg):
super(LineItemForm, self).__init__(*arg, **kwarg)
self.empty_permitted = False
I have no idea what the init does (arg, kwargs and super are all still a mystery to me). I copied it from another page. It works though.
Source : Django documentation
Default value for ModelChoiceField is None, even if you specified the queryset attribute. If the form is valid, to me it means than None in Ledger.objects.all() is True! Are you sure you do have Ledger objects in your database?
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
I am using Django 1.6. And I am experiencing the error
**Exception Type**: MultiValueDictKeyError
**Exception Value**:"'chat_room_id'"
in the mentioned part of the code. Can anyone help me out regarding this?
#login_required
def join(request):
'''
Expects the following POST parameters:
chat_room_id
message
'''
p = request.POST
r = Room.objects.get(id=int(p['chat_room_id']))
r.join(request.user)
return HttpResponse('')
Seems like chat_room_id is not in p. request.POST is a MultiValueDict. It has a .get() method to fetch the values. Use that with a default value so that if there is no value for the key, you can use a default value. E.g.
#login_required
def join(request):
'''
Expects the following POST parameters:
chat_room_id
message
'''
p = request.POST
room_id = p.get('chat_room_id', False)
# ------------------------------^ Returns False if `chat_room_id` is not in `p`
if room_id:
r = Room.objects.get(id=int(room_id))
r.join(request.user)
else:
# throw error
return HttpResponse('')
I'm having some trouble grokking Django forms and validation.
#views.py:
def create(request):
if request.method == 'POST':
form = CreateDocumentForm(request.POST)
if form.is_valid():
doc = Document.objects.create(name=form.cleaned_data['name'])
#snip
#forms.py:
class CreateDocumentForm(forms.ModelForm):
name = forms.CharField()
def clean_name(self):
cleaned_name = self.cleaned_data['name']
rgx = re.compile('^(\w|-|\.)+$')
if rgx.match(cleaned_name) == None:
raise ValidationError("invalidchars")
return cleaned_name
The logic is working properly, but I don't know how to tell which kind of VaidationError was raised. Also - This is handled by an Ajax request, so I won't be using templating in the repsonse. I need to get the status of what failed in this view.
thx
You generally won't see the ValidationErrors themselves. If you call form.is_valid, then the errors that occur during validation are all collected and returned to you as a dictionary, form.errors
You can check that dictionary for errors relating to any specific field. The result for any field with errors should be the string value of any ValidationErrors that were raised for that field.
In your view, then, if form.is_valid() returns False, then you can do this:
if 'name' in form.errors:
for err_message in form.errors['name']:
# do something with the error string