AttributeError at has no attribute 'objects' - django

AttributeError type object 'Data_Point ' has no attribute 'objects'plz check and correct me
AttributeError at /
type object 'myProduction' has no attribute 'objects'
model":
from django.db import models
from django.contrib.auth.models import User
class Production(models.Model):
title=models.CharField(max_length=120)
def __str__(self):
return self.title
My Form
from django import forms
from.models import Production
class myProduction(forms.ModelForm):
class Meta:
model=Production
fields =['title']
class Raw_Pro(forms.Form):
title = forms.CharField()
My View
from django.shortcuts import render
from .form import myProduction,Raw_Pro
def my_index(request):
my_form=Raw_Pro()
if request.method=='POST':
my_form=Raw_Pro(request.POST)
if my_form.is_valid():
myProduction.objects.create(my_form.cleaned_data)
else:
print(my_form.errors)
context={"form":my_form}
return render(request, "index.html",context)

You make some mistakes here:
myProduction here is your ModelForm (defined in forms.py), not your model (this is Production, defined in `models.py);
you here use Raw_Pro as form, which is not a ModelForm, which is likely not what you want to use;
in case of a successful form, you can use mymodelform.save() to create/edit the object; and
if the creation is successful, you should redirect to a page, for example the same page. By not doing so, a refresh of the user, would trigger a POST with the same parameters.
from django.shortcuts import render
from .form import myProduction
def my_index(request):
if request.method == 'POST':
my_form = myProduction(request.POST)
if my_form.is_valid():
my_form.save()
return redirect(my_index) # or somewhere else
else:
my_form = myProduction()
context = {"form":my_form}
return render(request, "index.html",context)
Note: as specified by PEP-8 [Python-doc], you should use camelcase starting with an Uppercase for class names. So you better rename your myProduction class to MyProduction, or much better ProductionForm, since then it is clear what that class is doing.

Related

Django rich text editor inside django template not for Admin

How can I set rich text editor inside Django Template without using crispy form {{form.media}}. I am not using crispy form right now. What to do.
I don't think there's any other method to do this. But, I can provide you the simplest solution.
Create a forms.py file inside your Django APP
from django.forms import ModelForm
from .models import Order
class OrderForm(ModelForm):
class Meta:
model = Order
fields = ['description']
Here, Order is your Model Name.
Inside your views.py
from django.shortcuts import render
from order.models import Order
from .forms import OrderForm
# Create your views here.
def post_order(request):
if request.method == "GET":
order_form = OrderForm()
required_dict = {
'form':order_form,
}
return render(request, "themes/order/order_post.html",required_dict)

How to render the Form (in a template tag) automatically created by CreateView

How do I render a Form automatically created by CreateView CBV?
Setup
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView
from .models import Journal
from django.urls import reverse
class CreateJournal(LoginRequiredMixin, CreateView):
model = Journal
template_name = 'journals/journal_list.html'
fields = ('journal_name',)
def get_success_url(self):
return reverse('home')
def form_valid(self, form):
form.instance.journal_user = self.request.user
return super(CreateJournal, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(CreateJournal, self).get_context_data(**kwargs)
context['Journals'] = Journal.objects.filter(journal_user=self.request.user)
return context
urls.py
urlpatterns = [
path('', CreateJournal.as_view(), name='journals'),
path('<slug:slug>', JournalEntriesList.as_view(), name='to-journal-entries'),
]
As you can see I do not have a specific form mentioned, here, that is because I don't have one. CreateView creates one automatically. As you can see, this view (which does two jobs right now, help user create an object and at the same time displays all the objects) is now rendering to 'to-journals/journal_list.html`.
I want to display the same thing (both the View and the Form) on the "home" page or any other page.
Current template tag only gets the data from the database (context)
My current attempt looks like this:
journal_tags.py
register = template.Library()
#register.inclusion_tag('template_tags/journal_list.html', takes_context=True)
def get_journals(context):
journals = Journal.objects.filter(journal_user=context['request'].user)
return {'journals': journals}
This successfully renders all the existing journals to any page I want. Now, how do I also render the form, that CreateView created for me.
Failed Approach
One approach I tried is to add the for argument to the function like so:
journal_tags.py
#register.inclusion_tag('template_tags/journal_list.html', takes_context=True)
def get_journals(context):
journals = Journal.objects.filter(journal_user=context['request'].user)
return {
'journals': journals,
'form': CreateJournal,
}
This doesn't work because CreateJournal is a view and not the form. My question is how do I render the form created by class CreateJournal(LoginRequiredMixin, CreateView)?
Thanks for taking the time to look at this. I really appreciate the help of our community! Have a great day!
journal_tags.py
register = template.Library()
#register.inclusion_tag('template_tags/journal_list.html', takes_context=True)
def get_journals(context, self):
journals = to_journal.objects.filter(journal_user=context['request'].user)
return {
'journals': journals,
'form': JournalForm
}
Where JournalForm is as ModelForm created in models.py
class JournalForm(ModelForm):
class Meta:
model = to_journal
fields = ['journal_name']

Custom validation is not working inside forms.py

I want to validate my email field like: if email contains [gmail.com,outlook.com,yahoo.com] then I want to raise validation Error. But it's not working, I don't know what i am doing wrong. plz help me
views.py
from django.shortcuts import render
from django.views.generic import View
from access.utils import is_valid
from access.mixin import HttpResponseMixin
import json
from access.forms import Employer_Form
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
#method_decorator(csrf_exempt,name = 'dispatch')
class Emp_Registration_view(View,HttpResponseMixin):
def post (self,request,*args,**kwargs):
data = request.body
json_data = is_valid(data)
if not json_data:
return self.render_http_response(json.dumps({'msg':'Please send valid json only'}),status=400)
emp_data = json.loads(data)
form= Employer_Form(emp_data)
if form.is_valid():
form.save(commit=True)
return self.render_http_response(json.dumps({'msg':'Registered Successfully'}))
if form.errors:
return self.render_http_response(json.dumps(form.errors),status=400)
forms.py
from access.models import Employer_Registration
from django import forms
class Employer_Form(forms.ModelForm):
def clean_email(self):
email = self.cleaned_data['emp_email']
email_lists = ['gmail.com','yahoo.com','outlook.com','hotmail.com']
data = emp_email.split('#')
if data in email_lists:
raise forms.ValidationError("email is not valid")
return email
class Meta:
model = Employer_Registration
fields = '__all__'
Your method should be named clean_emp_email, because the field is named emp_email. Otherwise it won't be called.
Seems like you are splitting on # so if you split example#gmail.com it will be [example , gmail.com] and that you are comparing in this line exactly
if [example , gmail.com] in email_lists
so it is not found I suggest you to do you can omit splitting and find in substring as
for i in email_lists:
if i in self.cleaned_data['emp_email']:
raise forms.ValidationError("email is not valid")
After #Alexandr Tatarinov answer you should also call the clean_field_name or simply clean

Django Form Primary Key on save() method - getting NoneType traceback

I was using the q&a at
Get Primary Key after Saving a ModelForm in Django.
It's exactly on point with what I need to do.
I have the following model:
class meetingEvent(models.Model):
'''
A meeting event
'''
name = models.CharField(max_length=64, help_text="a name for this meeting")
account_number = models.ForeignKey(account)
meeting_type = models.ForeignKey(meetingType)
meeting_group = models.ForeignKey(meetingGroup)
start_time = models.DateTimeField(help_text="start time for this event")
end_time = models.DateTimeField(help_text="end time for this event")
created_time = models.DateTimeField(auto_now_add=True)
listed_products = models.ForeignKey(product)
additonal_notes = models.TextField(help_text="additional notes for this meeting")
def __unicode__(self):
return self.name
I have the following form:
class meetingEventForm(forms.ModelForm):
"""
to create a new meeting event.
"""
portal_user = forms.CharField(help_text="username to access portal data")
portal_pass = forms.CharField(widget=forms.PasswordInput, help_text="password to add access portal data")
def save(self, commit=True):
super(meetingEventForm, self).save(commit=commit)
class Meta:
model = meetingEvent
I have the following view:
def meeting_event(request):
if request.method == 'POST':
form = meetingEventForm(request.POST)
if form.is_valid():
new_agenda=form.save()
return HttpResponseRedirect(reverse('agenda_detail', args=(new_agenda.pk,)))
else:
form = meetingEventForm()
return render_to_response('agendas/event.html',{'form':form,}, context_instance=RequestContext(request))
I've confirmed that this makes it into the database cleanly.
However, I get the following error:
Traceback:
File "/usr/lib/python2.6/site-packages/Django-1.5.2-py2.6.egg/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/Django-1.5.2-py2.6.egg/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/var/www/html/tamtools/agendas/views.py" in meeting_event
44. return HttpResponseRedirect(reverse('agenda_detail', args=(new_agenda.pk,)))
Exception Type: AttributeError at /agendas/add/
Exception Value: 'NoneType' object has no attribute 'pk'
Has something changed in Django 1.5 that I don't know about? new_agenda should be a meetingEventForm type, shouldn't it?
You overwrite save methid in modelform, but you forgot to return model.
return super( ....
You don't need to override the ModeForm save method, since you aren't doing anything special with it. Your ModelForm should look like:
class MeetingEventForm(forms.ModelForm):
"""
to create a new meeting event.
"""
class Meta:
model = meetingEvent
I also changed the class name to conform with the Python style guide.
You also have two extra fields in the form that have nothing to do with your model. There could be two reasons - one, you need to save these fields in another model, or the second option is that you want someone to authorize themselves before they can add a new event.
Since the second one seems more plausible, restrict access to the form from your view:
from django.contrib.auth.decorators import login_required
from django.shorcuts import render, redirect
#login_required()
def meeting_event(request):
form = MeetingEventForm(request.POST or {})
context = {'form': form}
if request.method == 'POST':
if form.is_valid():
new_agenda = form.save()
return redirect('agenda_detail', args=(new_agenda.pk,))
else:
return render(request, 'agendas/event.html', context)
else:
return render(request, 'agendas/event.html', context)
As this is a common task, and you are using django 1.5, why not use the generic class based views?
Your code will be reduced, and you don't have to worry about the mundane details:
First, in your views.py, create a class that inherits from the generic CreateView which is used to display a model form for a model, let the user fill it in, and save the details:
from django.views.generic.edit import CreateView
class CreateMeetingRequest(CreateView):
template_name = 'agendas/event.html'
model = meetingRequest
Now, to map the view to a url, we add it to urls.py. Since we also want the user to be logged in before they can add a meeting request - the login_required decorator takes care of that for us. It will check if the user is logged in - if not, redirect the user to a login form and once they have logged in, redirect them back to the form:
from django.contrib.auth.decorators import login_required
from .views import CreateMeetingRequest
urlpatterns = patterns('',
# your other views
url(r'meeting-request/add/$',
login_required(CreateMeetingRequest.as_view()), name='add-meeting-req'),
)
Finally, we need to tell the view where to go once the form is successful. CreateView will check if the model has a get_absolute_url method, and call that. So in your models.py:
from django.core.urlresolvers import reverse
class meetingRequest(models.Model):
# your normal fields
def get_absolute_url(self):
return reverse('agenda_detail', args=(self.pk,))

404 Error while processing radio buttons in a form . How to debug?

This is my views.py
from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django import forms
def TestLayer(request):
users = User.objects.all()
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
user = form.cleaned_data['user']
rad1=form.cleaned_data['radio1']
rad2=form.cleaned_data['radio2']
test = Permission()
test.user = user
test.val = rad1 + rad2
test.save()
return render_to_response('testlayer.html',{'user':users})
else:
form = TestForm()
return render_to_response('testlayer.html', {'user':users})
This is my forms.py
from django import forms
from django.forms.widgets import RadioSelect
class TestForm(forms.Form):
user = forms.CharField(max_length=100)
RADIO_CHOICES1 = [['1','Radio 1'],['2','Radio 2']]
RADIO_CHOICES2 = [['3','Radio 2'],['4','Radio 2']]
radio = forms.ChoiceField( widget=RadioSelect(), choices=RADIO_CHOICES1)
radio = forms.ChoiceField( widget=RadioSelect(), choices=RADIO_CHOICES2)
My urls.py is this
url(r'^tests/','test.views.TestLayer',name='testlayer'),
When I click submit button the form is either not getting processed or its throwing a 404 error . Is my view correct according to the form and template ? I have generated the template from the forms .
There are a few things I noticed about your view and form code...
First, your TestForm class defines "radio" twice, instead of the two fields you're looking for in the form's cleaned data collection in the view: radio1, radio2
Second, you're not passing the form to the template in your view.
Third, there's no need to return render_to_response twice, or to even have the condition where you're creating a new instance of the test form. Instead try this:
#views.py
from django.conf import settings
from django.shortcuts import render #assumes Django 1.3
#these imports seem to be missing...
from your_app.forms import TestForm
from your_app.models import Permission
def test_layer(request):
users = User.objects.all()
form = TestForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
cleaned_data = form.cleaned_data
user = cleaned_data.get('user')
radio1 = cleaned_data.get('radio1')
radio2 = cleaned_data.get('radio2')
test = Permission()
test.user = user
test.val = radio1 + radio2
test.save()
return render(request, 'testlayer.html', {'user':users, 'form' : form})
#forms.py
from django import forms
class TestForm(forms.Form):
user = forms.CharField(max_length=100)
RADIO_CHOICES1 = [['1','Radio 1'],['2','Radio 2']]
RADIO_CHOICES2 = [['3','Radio 2'],['4','Radio 2']]
radio1 = forms.ChoiceField( widget=forms.RadioSelect(), choices=RADIO_CHOICES1)
radio2 = forms.ChoiceField( widget=forms.RadioSelect(), choices=RADIO_CHOICES2)
Also, your URL pattern doesn't end with $, and you can prefix your patterns to avoid repeating the path to your view function(s):
#urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('test.views',
url(r'^tests/$','test_layer', name='testlayer'),
)
Lastly, your view function name was title-cased: TestLayer. In Python, it's a convention that function names, variables, etc, are lower-cased with underscores separating words, and classes are title-cased.
Hope that helps you out.