My form isn't saving the models that I need it to. My form:
class RewardForm(forms.Form):
quantity = forms.IntegerField(max_value=10, min_value=1, label=_('quantity'), initial=1)
reward = forms.CharField(max_length=50, label=_('reward'))
reward_denomination = forms.ModelChoiceField(queryset=Reward_Denomination.objects.all(), widget=forms.RadioSelect)
def clean_reward(self):
data = self.cleaned_data.get('reward')
try:
reward = Reward.objects.get(reward_name=data)
except ObjectDoesNotExist:
raise forms.ValidationError(_('Reward does not exist'), code='invalid')
return data
def clean_reward_denomination(self):
data = self.cleaned_data.get('reward_denomination')
try:
denomination = Reward_Denomination.objects.get(denomination=data)
except ObjectDoesNotExist:
raise forms.ValidationError(_('Denomination does not exist'), code='invalid')
return data
def save(self, request, commit=True):
user = request.user
data = self.cleaned_data
'try:
post_reward = data['reward']
post_denomination = data['reward_denomination']
quantity = data['quantity']
except LookupError:
raise Http404
reward = Reward.objects.get(reward_name=post_reward)
denomination = Reward_Denomination.objects.get(denomination=post_denomination)
user_points = Points.objects.filter(affiliate__id=user.id).aggregate(total_points=Sum('points'))
user_points = user_points['total_points']
try:
total_cost = (quantity * denomination.cost)
except ArithmeticError:
raise Http404
quote_price = -total_cost
if user_points >= total_cost:
reward_order = Points.objects.create(affiliate=user, points=quote_price, from_reward=True, from_offer=False)
status_coded = Status_Code.objects.create(short_name="Pending", name="The order is currently being reviewed", description="The order is in queue")
redeem_order = Redeem.objects.create(affiliate=user, status_code=status_coded, quantity=quantity, reward=reward, price=total_cost)
return reward_order
My Views:
class Reward_Detail(DetailView):
model = Reward
slug_field = 'reward_slug'
context_object_name = 'reward'
template_name = 'omninectar/reward.html'
#Detail Stuff
class RedeemReward(SingleObjectMixin, FormView):
template_name = 'omninectar/reward.html'
slug_field = 'reward_slug'
form_class = RewardForm
model = Reward
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super(RedeemReward, self).post(request, *args, **kwargs)
def get_success_url(self):
return reverse('omni:reward_confirmation')
class RewardBeautify(View):
def get(self, request, *args, **kwargs):
view = Reward_Detail.as_view()
return view(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
view = RedeemReward.as_view()
return view(request, *args, **kwargs)
So I initially thought that the FormView would handle the form processing (validate, and, if valid, run form.save(), etc). I'm following the FormView, SingleObjectMixin example on the Django website. I don't receive any errors when I try and submit the form, but no objects are created either. I've tried defining a form_valid method that runs the save method, I've tried putting it inside the post method in the formview, etc. Can anyone spot the error/errors? Thanks!
I'm new to view classes too and I had almost the same problem with Django 1.6.
You should add
def form_valid(self, form):
form.save()
return super(RedeemReward, self).form_valid(form)
method overriding to your RedeemReward class. This worked for me.
If you look to Django source code, you will see that there is no form saving in FormView class inheritance chain.
I am not sure if this will help or not, but I had issues finding code showing how to save the data from a FormView model. This is what I came up with. I hope it helps and you can apply it to your code.
forms.py
class JobCreateForm(forms.Form):
title = forms.CharField(label='Job Title', max_length=500)
number = forms.IntegerField(label='Job Number: ')
comps = forms.ModelMultipleChoiceField(label='Comparable Sales',
required=False, queryset=m.ComparableSale.objects.all())
details = forms.CharField(label='Job Details:', max_length=200,
required=False, widget=forms.Textarea(attrs={'rows':6, 'cols':20}))
Views.py
class JobCreateView(generic.FormView):
template_name = 'form_templates/createjob_form.html'
form_class = f.JobCreateForm
model = models.Job
success_url = '/'
def form_valid(self, form):
comps = form.cleaned_data['comps']
title = form.cleaned_data['title']
number = form.cleaned_data['number']
details = form.cleaned_data['details']
job = models.Job(title=title, number=number, details=details)
job.save()
print(comps)
if comps != []:
job.comps.add(*comps)
return super(JobCreateView, self).form_valid(form)
You can write your own ModelFormView using the mixins provided by Django (specifically, the ModelFormMixin). Then your form will be saved on a successful post.
from django.views.generic.base import TemplateResponseMixin
from django.views.generic.edit import ModelFormMixin, ProcessFormView
class BaseModelFormView(ModelFormMixin, ProcessFormView):
pass
class ModelFormView(TemplateResponseMixin, BaseModelFormView):
pass
Related
I have recently learning about Validators and how they work but I am trying to add a function to my blog project to raise an error when a bad word is used.
I have a list of bad words in a txt and added the code to be in the models.py the problem is that nothing is blocked for some reason I am not sure of.
Here is the models.py
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
---------------other unrelated------------------------
def validate_comment_text(text):
with open("badwords.txt") as f:
censored_word = f.readlines()
words = set(re.sub("[^\w]", " ", text).split())
if any(censored_word in words for censored_word in CENSORED_WORDS):
raise ValidationError(f"{censored_word} is censored!")
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField(max_length=300, validators=[validate_comment_text])
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now=True)
here is the views.py:
class PostDetailView(DetailView):
model = Post
template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html
def get_context_data(self, *args, **kwargs):
context = super(PostDetailView, self).get_context_data()
post = get_object_or_404(Post, slug=self.kwargs['slug'])
comments = Comment.objects.filter(
post=post).order_by('-id')
total_likes = post.total_likes()
liked = False
if post.likes.filter(id=self.request.user.id).exists():
liked = True
if self.request.method == 'POST':
comment_form = CommentForm(self.request.POST or None)
if comment_form.is_valid():
content = self.request.POST.get('content')
comment_qs = None
comment = Comment.objects.create(
post=post, user=self.request.user, content=content)
comment.save()
return HttpResponseRedirect("blog/post_detail.html")
else:
comment_form = CommentForm()
context["comments"] = comments
context["comment_form"] = comment_form
context["total_likes"] = total_likes
context["liked"] = liked
return context
def get(self, request, *args, **kwargs):
res = super().get(request, *args, **kwargs)
self.object.incrementViewCount()
if self.request.is_ajax():
context = self.get_context_data(self, *args, **kwargs)
html = render_to_string('blog/comments.html', context, request=self.request)
return JsonResponse({'form': html})
return res
class PostCommentCreateView(LoginRequiredMixin, CreateView):
model = Comment
form_class = CommentForm
def form_valid(self, form):
post = get_object_or_404(Post, slug=self.kwargs['slug'])
form.instance.user = self.request.user
form.instance.post = post
return super().form_valid(form)
Here is my trial which didn't work
def validate_comment_text(sender,text, instance, **kwargs):
instance.full_clean()
with open("badwords.txt") as f:
CENSORED_WORDS = f.readlines()
words = set(re.sub("[^\w]", " ", text).split())
if any(censored_word in words for censored_word in CENSORED_WORDS):
raise ValidationError(f"{censored_word} is censored!")
pre_save.connect(validate_comment_text, dispatch_uid='validate_comment_text')
I am new learner so if you could provide some explanation to the answer I would be grateful so that I can avoid repeating the same mistakes.
I'm sure there are many ways to handle this, but I finally decided to adopt a common practice in all my Django projects:
when a Model requires validation, I override clean() to collect all validation logic in a single place and provide appropriate error messages.
In clean(), you can access all model fields, and do not need to return anything; just raise ValidationErrors as required:
from django.db import models
from django.core.exceptions import ValidationError
class MyModel(models.Model):
def clean(self):
if (...something is wrong in "self.field1" ...) {
raise ValidationError({'field1': "Please check field1"})
}
if (...something is wrong in "self.field2" ...) {
raise ValidationError({'field2': "Please check field2"})
}
if (... something is globally wrong in the model ...) {
raise ValidationError('Error message here')
}
The admin already takes advantages from this, calling clean() from ModelAdmin.save_model(),
and showing any error in the change view; when a field is addressed by the ValidationError,
the corresponding widget will be emphasized in the form.
To run the very same validation when saving a model programmatically, just override save() as follows:
class MyModel(models.Model):
def save(self, *args, **kwargs):
self.full_clean()
...
return super().save(*args, **kwargs)
Proof:
file models.py
from django.db import models
class Model1(models.Model):
def clean(self):
print("Inside Model1.clean()")
def save(self, *args, **kwargs):
print('Enter Model1.save() ...')
super().save(*args, **kwargs)
print('Leave Model1.save() ...')
return
class Model2(models.Model):
def clean(self):
print("Inside Model2.clean()")
def save(self, *args, **kwargs):
print('Enter Model2.save() ...')
self.full_clean()
super().save(*args, **kwargs)
print('Leave Model2.save() ...')
return
file test.py
from django.test import TestCase
from project.models import Model1
from project.models import Model2
class SillyTestCase(TestCase):
def test_save_model1(self):
model1 = Model1()
model1.save()
def test_save_model2(self):
model2 = Model2()
model2.save()
Result:
❯ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
Enter Model1.save() ...
Leave Model1.save() ...
.Enter Model2.save() ...
Inside Model2.clean()
Leave Model2.save() ...
.
----------------------------------------------------------------------
Ran 2 tests in 0.002s
OK
Destroying test database for alias 'default'...
Validators run only when you use ModelForm. If you directly call comment.save(), validator won't run. link to docs
So either you need to validate the field using ModelForm or you can add a pre_save signal and run the validation there (you'll need to manually call the method, or use full_clean to run the validations).
Something like:
from django.db.models.signals import pre_save
def validate_model(sender, instance, **kwargs):
instance.full_clean()
pre_save.connect(validate_model, dispatch_uid='validate_models')
i am using django formset to save multiple form at a time.but data is not saving in my database.I am using class based views.This is the model where i want to save my data.
Model
class Period(AbstractBaseModel):
validators = [ScreenMethodValidator, ChainIntegrityValidator]
chain = models.ForeignKey(
'customers.Chain',
help_text=_('chain to which period belongs to'),
verbose_name=_('chain')
)
start_date = models.DateTimeField(
default=datetime.datetime.now,
help_text=_('Starting date of a period'),
verbose_name=_('start date')
)
end_date = models.DateTimeField(
default=datetime.datetime(1970, 01, 01),
help_text=_('Ending date of a period'),
verbose_name=_('end date')
)
year = models.IntegerField(
default=0,
help_text=_('Financial year'),
verbose_name=_('year'),
null=True,blank=True
)
description = models.TextField(
help_text=_('Description of a period'),
verbose_name=_('description'),
null=True,blank=True
)
class Meta:
app_label = 'accounting'
and View
class PeriodCreate(RequestPassingFormViewMixin, WammuCreateView):
model = Chain
template_name = 'dashboard/period_form.html'
form_class = ChainForm
def get_object(self):
chain = Chain.objects.get(pk=self.kwargs['chain_pk'])
return chain
def get_success_url(self):
return reverse('dashboard_period_list', kwargs={'chain_pk': self.object.chain.id, })
def get_context_data(self, **kwargs):
context = super(PeriodCreate, self).get_context_data(**kwargs)
return context
def get_form_kwargs(self, *args, **kwargs):
kwargs = super(PeriodCreate, self).get_form_kwargs(*args, **kwargs)
chain = get_object_or_404(Chain, pk=self.kwargs['chain_pk'])
period = Period(chain=chain)
kwargs['instance'] = period
return kwargs
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
PeriodInlineFormSet = inlineformset_factory(Chain, Period,
form=PeriodInlineForm,
can_delete=True,
extra=12)
PeriodInlineFormSet.form = staticmethod(curry(PeriodInlineForm, request=request, chain=self.object))
period_formset = PeriodInlineFormSet()
return self.render_to_response(
self.get_context_data(form=form,
period_inline_formset=period_formset))
def post(self, request, *args, **kwargs):
self.object = Chain()
form = self.get_form(self.form_class)
PeriodInlineFormSet = inlineformset_factory(Chain, Period,
form=PeriodInlineForm,
can_delete=True,
extra=12)
PeriodInlineFormSet.form = staticmethod(curry(PeriodInlineForm))
if form.is_valid():
self.object = form.save(commit=False)
period_formset = PeriodInlineFormSet(request.POST, instance=self.object)
if period_formset.is_valid():
self.object.save()
period_formset.save()
return super(PeriodCreate, self).form_valid(form)
else:
return self.render_to_response(
context=self.get_context_data(form=form, period_inline_formset=period_formset))
else:
period_formset = PeriodInlineFormSet(request.POST,instance=self.object)
return self.render_to_response(
context=self.get_context_data(form=form, period_inline_formset=period_formset))
and use the following link to see my other code related to this issue where i have tried to use django formset and faced an argument error which has been solved
but now data is not saving in data base when i am trying to post data.surely the error is occurring in my post method,but as i am not used to work with django formset,i can't figure it out after a long findings.
django __init__ method causing argument error
I have a update view:
class GeneralUserUpdateView(UpdateView):
model = GeneralUser
form_class = GeneralUserChangeForm
template_name = "general_user_change.html"
def dispatch(self, *args, **kwargs):
return super(GeneralUserUpdateView, self).dispatch(*args, **kwargs)
def post(self, request, pk, username):
self.pk = pk
self.username = username
self.gnu = GeneralUser.objects.get(pk=self.pk)
#form = self.form_class(request.POST, request.FILES)
return super(GeneralUserUpdateView, self).post(request, pk)
def form_valid(self, form, *args, **kwargs):
self.gnu.username = form.cleaned_data['username']
self.gnu.email = form.cleaned_data['email']
self.gnu.first_name = form.cleaned_data['first_name']
self.gnu.last_name = form.cleaned_data['last_name']
self.gnu.address = form.cleaned_data['address']
self.gnu.save()
return redirect("user_profile", self.pk, self.username)
Here in this view I want to pass a context like:
context['picture'] = GeneralUser.objects.get(pk=self.pk)
I did trying get_context_data but I cant access pk in there..
Am I doing the update right?? How can I pass that context in there??
You shouldn't be overriding post at all. All of that logic should happen in get_context_data.
In fact, none of your overrides are needed. Everything that you do in form_valid will be done already by the standard form save. And overriding dispatch just to call the superclass is pointless.
Your view should look like this only, with no overridden methods at all:
class GeneralUserUpdateView(UpdateView):
model = GeneralUser
form_class = GeneralUserChangeForm
template_name = "general_user_change.html"
context_object_name = 'picture'
(although it seems a little odd that you want to refer to an instance of GeneralUser as "picture").
Edit to redirect to a specific URL, you can define get_success_url:
def get_success_url(self):
return reverse("user_profile", self.kwargs['pk'], self.kwargs['username'])
I have this url is http://127.0.0.1:8000/upload/picturelist/1, which makes user_id = 1,
In my urls.py
url(r'^picturelist/(?P<user_id>\d+)$', views.pictureList),
In my view.py
def pictureList(request, user_id):
if int(user_id) != request.user.id:
raise PermissionDenied
How can I make this function based view to use createview?
class pictureList(CreateView):
You could do something like this:
In urls.py: url(r'^picturelist/(?P<user_id>\d+)$', views.MakeItView.as_view()),
In views.py:
class MakeItView(CreateView):
model = myModel
template_name = 'whatever.html'
def get_context_data(self, **kwargs):
context = super(MakeItView, self).get_context_data(**kwargs)
if int(self.kwargs['user_id']) != self.request.user.id:
raise PermissionDenied
return context
I've never used CreateView, but here's what I gather from reading the docs:
You could do it by defining form_valid:
view:
class pictureList(CreateView):
model = YourModelHere
fields = ['whatever','fields','you','want','edited']
def form_valid(self, form):
record = form.save(commit = False)
# assuming the user id is associated
# to the model with fieldname user_id
if (self.request.user == record.user_id):
record.save()
return HttpResponseRedirect(self.get_success_url())
# not sure if this works:
return self.form_invalid()
Then the template would be at 'yourappname/yourmodelhere_form.html'.
See CreateView for an example.
I have a FormView that is basically a product page. You can view product details and request the product from a form on that page. I want the page to be set up so that anyone can view the page, but only people that are logged in can request the product. To do this, I added a login_required decorator to the post function in the FormView, but I get the error:
'QueryDict' object has no attribute 'user'
How can I code this view/form so it acts as I described?
View:
class RedeemReward(SingleObjectMixin, FormView):
template_name = 'reward.html'
slug_field = 'reward_slug'
form_class = Redeem_Reward
model = Reward
#method_decorator(login_required)
def post(self, request, *args, **kwargs):
return super(RedeemReward, self).post(request, *args, **kwargs)
def form_valid(self, form):
form_class = self.get_form_class()
form = self.get_form(form_class)
#form = self.get_form(self.get_form_class())
#form.save(self.request.POST)
form.save(self.request.POST)
return super(RedeemReward, self).form_valid(form)
def get_success_url(self):
return reverse('reward_confirmation', args=(self.object.reward_slug, self.object.reward_code))
def dispatch(self, *args, **kwargs):
self.object = self.get_object()
return super(RedeemReward, self).dispatch(*args, **kwargs)
Form:
class Redeem_Reward(forms.Form):
quantity = forms.IntegerField(label=_('Quantity'), error_messages={'invalid':'Must be a valid number'})
reward_name = forms.CharField(max_length=50, widget=forms.HiddenInput(), label=_('Reward Name'), error_messages={'invalid':'Invalid reward'})
def clean_quantity(self):
"""
Validate that the user entered a valid number.
"""
return self.cleaned_data['quantity']
def clean_reward_name(self):
"""
Validate that this reward code exists.
"""
try:
existing_reward = Reward.objects.get(reward_name=self.cleaned_data['reward_name'])
except ObjectDoesNotExist:
raise forms.ValidationError(_("The reward you requested does not exist."))
return self.cleaned_data['reward_name']
def save(self, request, *args, **kwargs):
"""
Save all of the required data.
"""
user = request.user
#user_points = Points.objects.filter(affiliate__id=user.id).annotate(total_points=Sum('points'))
user_points = Affiliate.objects.filter(points__affiliate__id=user.id).annotate(total_points=Sum('points'))
user_points = user_points[0].total_points
error_message = {'lookuperror':'You need to provide a valid quantity',
'insufficient_points':"You don't have enough points for this purchase."}
try:
quantity = self.cleaned_data['quantity']
reward_name = self.cleaned_data['reward_name']
rewards = Reward.objects.get(reward_name=reward_name)
except LookupError:
raise Http404
try:
points_cost = -(rewards.reward_cost * quantity)
except ArithmeticError:
raise Http404
quote_price = -(points_cost)
if user_points >= quote_price:
reward_order = Points.objects.create(affiliate=user, reward=rewards, points=points_cost, from_reward=True, from_offer=False, from_referral=False)
status_cost = Status_Code.objects.create(short_name="Pending", name="The order is currently being reviewed", description="The order is in queue")
redeem_order = Redeem.objects.create(affiliate=user, reward=rewards, status_code=status_code)
redeem_details = Redeem_Details.objects.create(redeem=redeem_order, quantity=quantity, quote_price=quote_price)
return HttpResponseRedirect(reverse('reward_confirmation', args=(redeem_details.redeem_code,)))
else:
return render(request, 'reward.html', {'error_message':error_message['insufficient_points']})
You're passing self.request.POST to your form's save method, which is set to expect a request as its first argument. Or at least something that has a user attribute. If you pass in self.request instead, you will no longer get that particular error.
It is odd that you're reinstantiating form in your form_valid method, which receives the bound form as an argument.
You're returning HttpResponse objects from your form's custom save method, which is nonstandard. But as long as you're doing that, you should return them from your form_valid method.
In summary, something like this:
def form_valid(self, form):
return form.save(self.request)