models:
class UserDataUpdate(models.Model):
code = models.CharField(max_length=8)
address = models.CharField(max_length=50)
class UserSurvey(models.Model):
about_treatment = models.CharField(max_length=2)
user_data_update = OneToOneField(UserDataUpdate)
views:
#login_required
def generate_survey(request):
user_data_update = UserDataUpdate.objects.get(code=request.user.username)
if request.method == 'POST':
form = SurveyForm(request.POST)
if form.is_valid():
form.save()
return redirect('/success')
else:
form = SurveyForm(request.GET)
return render_to_response(
'survey.html',
{'form': form },
context_instance = RequestContext(request))
form:
class SurveyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SurveyForm, self).__init__(*args, **kwargs)
for field in self.fields.values():
field.widget = RadioSelect(choices=SURVEY_CHOICES)
class Meta:
model = Survey
exclude = ['user_data_update']
I just need a way to set the UserDataUpdate id (that already has been created) on a UserSurvey.
I'm getting this message on generate_survey request.POST:
user_data_update_app_usersurvey.user_data_update_id may not be NULL
It should be clear to you that you get the user_data_update value but then don't do anything with it. I guess you want to set it on the object that's created by the form:
if form.is_valid():
instance = form.save(commit=False)
instance.user_data_update = user_data_update
instance.save()
(I don't understand what all that stuff in the form's __init__ method is supposed to do. You only have one field in your form, anyway.)
Related
I can't find out how to do this, I have a list view, that when you click on one of the list objects, it takes you to an update page, but I can't work out how you pass the instance so to it so that and data posted goes to that instance on the database. CBV do this automatically in a hidden black box way, and I can't see how it is done for a function based view.
Model
class Project(models.Model):
date_published = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=128, unique=True)
slug = models.SlugField(max_length=64)
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
def __str__(self):
return self.title
Form
class ProjectUpdateForm(forms.ModelForm):
class Meta:
model = Update
fields = [
'project',
'category',
'update'
]
View
def project_update_view(request, slug):
obj = Project.objects.get(slug=slug)
form = ProjectUpdateForm(request.POST or None)
if form.is_valid():
form.save()
context = {
"form": form,
"object": obj
}
return render(request, 'project_portal/project_update.html', context)
url:
path('<slug:slug>/update/', project_update_view, name='project-update'),
So I want to be able to do away with the 'project' field in the Form because the user is already looking at that instance he shouldn't have to then pick it in the form.
Remove the project in the field, and set in in the view, like:
class ProjectUpdateForm(forms.ModelForm):
class Meta:
model = Update
fields = [
# 'project',
'category',
'update'
]
In the view, you can then set the project attribute of the instance manually:
def project_update_view(request, slug):
obj = Project.objects.get(slug=slug)
if request.method == 'POST':
form = ProjectUpdateForm(request.POST)
form.instance.project = obj
if form.is_valid():
form.save()
return redirect('success-url')
else:
form = ProjectUpdateForm()
context = {
"form": form,
"object": obj
}
return render(request, 'project_portal/project_update.html', context)
Some extra notes:
do not use request.POST or None, since a POST request can be valid and have no POST parameters;
in case the POST is successful, you should implement a Post/Redirect/Get pattern [wiki].
Sorry for the lengthy question. I have a complicated situation with django modelform validation. I have a model UserProject ready and created many objects. I also have another model Action_Inputs to accept multiple parameters, which is a onetoonefield relation with UserProject. I do need customed input argument for one field of Action_Inputs. But I cannot have the form valided.
models.py
class UserProject(models.Model):
pid = models.CharField(max_length=10, null=False, unique=True)
email = models.EmailField(max_length=254, null=False)
directory = models.CharField(max_length=255)
class Action_Inputs(models.Model):
userproject = models.OneToOneField(UserProject, null=False)
method = models.CharField(max_length=255)
file = models.FileField(upload_to='userdata')
Now I have the following ModelForm which takes a customed input argument jobid, catched from url, which is a string to get back to the previous UserProject pid:
class ActionInputsForm(ModelForm):
def __init__(self, jobid, *args, **kwargs):
super(ActionInputsForm, self).__init__(*args, **kwargs)
self.fields['userproject'].initial = jobid
class Meta:
model = Action_Inputs
fields = ['userproject', 'method', 'file'] # userproject will be hidden
def clean_userproject(self):
userproject = self.cleaned_data['userproject']
if len(userproject) != 10:
raise forms.ValidationError("---PID error.")
return UserProject.objects.get(pid=userproject)
def clean(self):
return self.cleaned_data
In my views.py
def parameters_Inputs(request, jobid):
if request.method == "POST":
form1 = ActionInputsForm(request.POST, request.FILES, jobid)
if form1.is_bound:
form1.save()
return render(request, 'goodlog.html', {'jobid': jobid})
elif request.method == "GET":
form1 = ActionInputsForm(jobid)
return render(request, 'inputsform.html',
{'form1': form1, 'jobid': jobid})
Now the request.POST['userproject'] is empty, which means the jobid has not been modified by init, the request.FILES looks correct but the validation is false. It says Unicode object has no attrite get, which is related to the uploaded file. Any idea about what is wrong? Thanks very much.
The following works:(thanks to Vladimir Danilov)
def __init__(self, jobid, *args, **kwargs):
super(ActionInputsForm, self).__init__(*args, **kwargs)
self.fields['userproject'].initial = UserProject.objects.get(pid=jobid)
def clean_userproject(self):
userproject = self.cleaned_data['userproject']
if not userproject:
raise forms.ValidationError("---UserProject not found.")
return userproject
def parameters_Inputs(request, jobid):
if request.method == "POST":
form1 = ActionInputsForm(jobid, request.POST, request.FILES)
.......
Not answer, but do you mean ActionInputsForm instead of Action_Inputs in these lines?
form1 = Action_Inputs(request.POST, request.FILES, jobid)
# ...
form1 = Action_inputs(jobid)
Also, you should write ActionInputsForm(jobid, request.POST, request.FILES).
Because in your case jobid will be request.POST.
I want to limit the choices of a ManyToManyField to those matching a ForeignKey. The form displays properly, but upon saving results in an error Select a valid choice. <choice> is not one of the available choices.
Before I was trying to limit the queryset by passing a parameter in the view to the form, and then using that parameter to filter the queryset.
Models:
class VenueEventTimeslot(models.Model):
venue = models.ForeignKey(Venue)
name = models.CharField(max_length=255)
class VenueEvent(models.Model):
venue = models.ForeignKey(Venue)
event_timeslots = models.ManyToManyField(VenueEventTimeslot)
class VenueEventForm(ModelForm):
event_timeslots = ModelMultipleChoiceField(queryset=None, widget=CheckboxSelectMultiple())
def __init__(self, *args, **kwargs): # limit timeslots to those of the venue only
venue_obj = kwargs.pop('venue_obj',None)
super(VenueEventForm, self).__init__(*args,**kwargs)
self.fields['event_timeslots'].queryset=VenueEventTimeslot.objects.filter(venue=venue_obj)
class Meta:
model = VenueEvent
fields = ['event_timeslots']
Views:
#login_required
def calendar(request, pk):
venue = Venue.objects.get(pk = pk)
if request.method == "POST":
form = VenueEventForm(request.POST)
if form.is_valid():
# form stuff
else:
form = VenueEventForm(venue_obj = venue)
context = {'venue':venue, 'form':form}
return render(request, ... , context)
However, if I pass the queryset from the view, it works perfectly.
Models:
class VenueEventTimeslot(models.Model):
# same as above
class VenueEvent(models.Model):
# same as above
class VenueEventForm(ModelForm):
class Meta:
model = VenueEvent
fields = ['date','client_name','event_timeslots']
widgets = {
'date': SelectDateWidget(),
'event_timeslots': CheckboxSelectMultiple(),
}
Views:
#login_required
def calendar(request, pk):
venue = Venue.objects.get(pk = pk)
if request.method == "POST":
form = VenueEventForm(request.POST)
if form.is_valid():
# form stuff
else:
form = VenueEventForm()
form.fields['event_timeslots'].queryset=VenueEventTimeslot.objects.filter(venue=venue)
context = {'venue':venue, 'form':form}
return render(request, ..., context)
Would anyone be able to shed some light on this?
I just solved a problem similar to this yesterday which is right here, How To Exclude A Value In A ModelMultipleChoiceField?, but I think the issue with your init function is the way it is formatted. Instead of venue=venue_obj, you need to change it to pk=venue_obj because it appear you are getting the pk of venue in the view instead of the venue attribute of VenueEvent , and I reformatted your form a bit to make it look cleaner.
forms.py
class VenueEventForm(ModelForm):
def __init__(self, *args, **kwargs): # limit timeslots to those of the venue only
venue_obj = kwargs.pop('venue_obj')
super(VenueEventForm, self).__init__(*args,**kwargs)
self.fields['event_timeslots'] = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=VenueEventTimeslot.objects.filter(pk=venue_obj))
class Meta:
model = VenueEvent
fields = ['event_timeslots']
views.py
#login_required
def calendar(request, pk):
venue = Venue.objects.get(pk = pk)
if request.method == "POST":
form = VenueEventForm(request.POST, venue_obj=venue)
if form.is_valid():
# form stuff
else:
print VenueEventForm.errors
else:
form = VenueEventForm(venue_obj=venue)
context = {'venue':venue, 'form':form}
return render(request, ... , context)
I have an edit view for one of my models.
#login_required
def edit(request, id):
''' Edit form '''
if id:
post = get_object_or_404(Post, pk=id)
if post.user != request.user:
return HttpResponseForbidden()
else:
post = Post()
if request.POST:
form = PostForm(request.POST, instance = post)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('posts_manage'))
else:
form = PostForm(instance = post)
return render_to_response('posts/add.html', {'form':form}, context_instance=RequestContext(request))
Everything works fine, all the post information is loaded correctly, but one of the fields, which is a select box, is not being selected with the value obtained from the DB. Other select boxes are selected to the appropriate value.
The field that is not being populated properly in the model definition:
class Post(models.Model):
...
BATHROOM_CHOICES = ((1,'1'),(1.5,'1.5'),(2,'2'),(2.5,'2.5'),(3,'3'),(3.5,'3.5'),(4,'4'), (4.5,'4.5'),(5,'5+'))
bathrooms = models.DecimalField(max_digits = 2,decimal_places = 1,choices = BATHROOM_CHOICES)
Relevant section inside add.html:
{{ form.bathrooms|bootstrap}}
forms.py
class PostForm(ModelForm):
class Meta:
model = Post
exclude = ('available','user',)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(PostForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit'] = False
obj = super(PostForm, self).save(*args, **kwargs)
if self.request:
obj.user = self.request.user
obj.save()
return obj
The data in the DB is not being matched by a choice in BATHROOM_CHOICES
BATHROOM_CHOICES = ((1,'1'),(1.5,'1.5'),(2,'2'),(2.5,'2.5'),(3,'3'),(3.5,'3.5'),(4,'4'), (4.5,'4.5'),(5,'5+'))
and
models.DecimalField(max_digits = 2,decimal_places = 1,
are contradicting.
Your model definition expects all values will have a decimal place of at least 1, and probably coerces values like whole number from 1 to 1.0 in the DB (depending on adapter implementation).
so then when it looks for a choice matching the value 1 !== 1.0 and so no value is selected.
Possible fix:
BATHROOM_CHOICES = ((1.0,'1'),(1.5,'1.5'),(2.0,'2'),(2.5,'2.5'),(3.0,'3'),(3.5,'3.5'),(4.0,'4'), (4.5,'4.5'),(5.0,'5+'))
#login_required
def post_review(request):
if request.method == 'POST':
formset = ReviewForm(request.POST)
if formset.is_valid():
formset.save(commit=False)
#formset.author = User.objects.get(pk=int(request.user.id))
formset.pub_date = datetime.datetime.now
formset.save()
return HttpResponseRedirect(reverse(review_index))
else:
formset = ReviewForm()
return render_to_response("review/post_review.html",
{"formset": formset}, context_instance=RequestContext(request),
)
I have this view, I want to auto set the current logged-in user in my review form author field. But I dont know how. Any ideas/hint pls?
Below is my form:
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ('title','category', 'body', )
widgets = {
'body': Textarea(attrs={'cols': 60, 'rows': 20}),
}
I've always done this by accepting a new kwarg in my form's __init__, and saving the value until save-time.
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ('title','category', 'body', )
widgets = {
'body': Textarea(attrs={'cols': 60, 'rows': 20}),
}
def __init__(self, *args, **kwargs):
self._user = kwargs.pop('user')
super(ReviewForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
inst = super(ReviewForm, self).save(commit=False)
inst.author = self._user
if commit:
inst.save()
self.save_m2m()
return inst
And then in my view:
def post_review(request):
# ... snip ...
if request.method == 'POST'
form = ReviewForm(request.POST, user=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/') #or whatever the url
else:
# Don't forget to add user argument
form = ReviewForm(user=request.user)
# ... snip ...
If Review.author isn't a required field, you can add a second value to the kwargs.pop call to set a default, like None. Otherwise, if the user kwarg isn't provided, it'll raise an error, effectively making it a required argument.
As an alternative solution, in Django 2+ using a form view - such as a CreateView or FormView, I can simply pass the self.request.user to my pre-saved form model:
class AppCreateView(CreateView):
model = models.App
fields = ['name']
success_url = '/thanks/'
def form_valid(self, form):
app_model = form.save(commit=False)
app_model.author = self.request.user
# app_model.user = User.objects.get(user=self.request.user) # Or explicit model
app_model.save()
return super().form_valid(form)
I agree the class based view is not important here. The important line is app_model.author = self.request.user.
The model is not special:
from django.db import models
from django.contrib.auth.models import User
class App(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255, help_text="Arbitrary name")
created = models.DateTimeField(auto_now_add=True, max_length=255)
I have a formset mixin which lets you pass extra arguments to the generated forms.
Just add the mixin as the first base class, set a dictionary named "form_kwargs" as a class attribute to describe the
arguments to pass.
from django.forms.formsets import BaseFormSet
class BaseKwargsFormSet(BaseFormSet):
"""
A formset mix-in to allow keyword arguments to be passed to constructed forms
For model_formsets, derive from this model *first* because django's formsets
can't grok the extra arguments.
To use, specify a dictionary with the kwargs & default values as an attribute
named "form_kwargs" on the formset base class.
example:
class BaseUserModelFormset (BaseKwargsFormSet, BaseModelFormSet):
form_kwargs = { 'user': None }
UserFormset = modelformset_factory (usermodel, form=userform,
formset=BaseUserModelFormset)
formset = UserFormset (request.POST or None, user=request.user)
"""
def __init__(self, *args, **kwargs):
form_kwargs = getattr(self, 'form_kwargs', {})
self.form_kwargs = dict((k, kwargs.pop(k, v)) for k, v in form_kwargs.items())
super(BaseKwargsFormSet, self).__init__(*args, **kwargs)
def _construct_form(self, index, **kwargs):
kwargs.update(**self.form_kwargs)
return super(BaseKwargsFormSet, self)._construct_form(index, **kwargs)