I am following a tutorial and I want to create an edit button for my input but when I click the edit button it returns the form but empty:
forms.py
class RecordingForm(forms.ModelForm):
class Meta:
model = Recording
fields = ['component', 'group', 'failure', 'degree_of_failure']
views.py
def edit_recording(request,slug, recording_id):
recording = get_object_or_404(Recording, pk=recording_id)
if request.method == "POST":
form = RecordingForm(request.POST, instance=recording)
if form.is_valid():
recording = form.save(commit=False)
recording.save()
return redirect('data:detail')
else:
form = RecordingForm(instance=recording)
template = 'data/create_recording.html'
context = {'form': form}
return render(request, template, context)
the form is empty :(
The answer is:
Daniel Roseman is correct about GET
And I changed these two in order to fix the NoReverseMatch
plant = get_object_or_404(Plant, slug=slug)
return redirect('data:detail', slug=plant.slug)
Related
In my model I have a field department which is a MultiSelectField and I give the blank=True to that field for some reasons. Now I want to check if user fills the field or not. I have tried to get data from request.POST and gave it a condition using len() function like this if len(field) == 0: but I got an error. Everything works just fine until I added teacher_year = request.POST['teacher_year']
models.py
class CustomUser(AbstractUser):
teacher_department = MultiSelectField(choices=department_choice, blank=True)
forms.py
class TeacherRegisterForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ['teacher_year', ...]
views.py
def teacherRegisterView(request):
form = TeacherRegisterForm()
template_name = "attendance/login-register/teacher_register.html"
if request.method == "POST":
form = TeacherRegisterForm(request.POST)
teacher_year = request.POST['teacher_year']
if len(teacher_year) == 0:
messages.warning(request, "Just a remind! You didn't select deparment!")
return redirect('teacher_register')
elif form.is_valid():
form.save()
messages.success(request, "Your account was created! You can log in now.")
return redirect('/')
return render(request, template_name, {'form': form})
the error I got
django.utils.datastructures.MultiValueDictKeyError: 'teacher_year'
MultiValueDict is inherited from normal dict. So you can use get() method with it:
teacher_year = request.POST.get('teacher_year') # if request.POST doesn't contain teacher_year it returns None
if teacher_year:
...
Here is
my form.py
class DepartamentForm(forms.ModelForm):
class Meta:
model = Department
fields = ['name','company','city', 'special_id','active']
def clean_code(self):
code = self.cleaned_data.get('special_id')
qm = Department.objects.filter(special_id=code)
if qm.exists():
raise forms.ValidationError("Email jest już używany!!" )
return code
my view.py
def dictionary_department_add(request):
current_user = request.user
if request.method == "POST":
form = DepartamentForm(request.POST)
if form.is_valid():
x_form = form.save(commit=False)
x_form.date_add = now.strftime("%Y-%m-%d %H:%M")
x_form.user_add = current_user.username
x_form.save()
return redirect('/dictionaries/dictionary_department/')
else:
return render(request, 'add_department.html',{form': form})
else:
form = DepartamentForm()
return render(request, 'add_department.html', {'form': form})
If I try to add a new position department using this code, the error isn't showed, and submit works for some reason.
I want that before submit form, method check if field special_id exists in database, and if exists than show message in form and stop submit
I am making a little image sharing website which is a lot like a blog. When I try to assign form.author = request.user, it doesn't work and the form on my website returns 'this field is required' error.
I tried even other similiar projects on github to check if the error is in the project but it seems not because I get errors there too. But the interesting part is when I try to print the request.user object it prints the object without a problem but when I try to assign it for some reason it returns null.
Then I tried twisting the code in every possible scenario but I couldn't debug it.
This is my models.py
class Meme(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE)
meme = models.ImageField(upload_to='memes/')
This is my view
def upload(request):
form = MemeUploadForm(request.POST or None)
if request.method == 'POST':
print(request.user)
if form.is_valid():
obj = form.save(commit=False)
obj.author = request.user
obj.save()
redirect('blog-index')
return render(request, 'blog/upload.html', {'form': form})
This is my form
class MemeUploadForm(ModelForm):
class Meta:
model = Meme
fields = ['title', 'meme']
When I try to get the view to return the request.user it gives me Attribue error: User' object has no attribute 'get' but when I try to print the request.user object it gives prints my object perfectly like there aren't any errors.
I found the problem and it was actually the imagefield that causes problems, because I didn't make the form 'file upload form' and the problem is not in request.user object.
Try this:
if request.method == 'POST':
form = MemeUploadForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.author = request.user
obj.save()
return HttpResponseRedirect('/blog-index')
return render(request, 'blog/upload.html', {'form': form})
I am new Django user. When I run program in Django I got this error please help.
Template Does Not Exist at /deals/
{'form': <DealsForm bound=False, valid=Unknown, fields=(name;pages;email)>}
view.py
class DealsForm(ModelForm):
class Meta:
model = Book
fields = ['name','pages','email']
def deals(request):
products = Product.objects.all()
form = DealsForm()
context = {'products': products}
if request.method == "POST":
form = DealsForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('products/deals')
else:
form = DealsForm()
return render('products/deals.html',{'form': form}, context_instance=context)
Your mistake was the arguments to the render function, it waits parameters like
render(request, 'name_of_template.html', context_dict)
Also, check your form variable it must be inside of the context dictionary, try adding it this way before pass it to render:
context['form'] = form
These things should work now.
I'm a Python/Django newbie and have been facing the following problem for several days now. I've got 2 ModelForms for a Model and the idea is that the data for one will help populate the multiplechoicefield of the second. The multiplechoice field for the second form populates ok but the problem is that the user's choices don't get saved. I've tried the save(commit=false) and save_m2m() but it hasn't fixed the issue.
models.py:
class Question(models.Model):
asker = models.ForeignKey(Student, related_name='asker+')
suggestedHelpers = models.ManyToManyField(Student, related_name='suggested')
chosenHelpers = models.ManyToManyField(Student, related_name='chosen')
class QuestionForm(ModelForm):
class Meta:
model = Question
exclude = ('chosenHelpers','suggestedHelpers', 'asker',)
class HelpersForm(ModelForm):
def suggesthelpers(self, question):
# populate chosenHelpers field according to data from QuestionForm
class Meta:
model = Question
exclude = ('suggestedHelpers', 'asker', 'questionSubj', 'Qtext',)
views.py
def askq_page(request):
question = Question(asker=Student.objects.get(user=request.user))
if request.method == 'POST':
form = QuestionForm(request.POST, instance=question)
if form.is_valid():
question = form.save()
# process data
question.save()
form2 = HelpersForm(instance=question)
form2.suggesthelpers(question)
variables = {'form':form2, 'qid':question.id}
return render_to_response('choosehelper.html', variables,context_instance=RequestContext(request))
else:
variables = RequestContext(request, {'form': QuestionForm()})
return render_to_response('askq.html', RequestContext(request, {'form': QuestionForm(instance=question)}))
def choosehelper_page(request, form='', qid=''):
question = Question.objects.get(id=qid)
if request.method == 'POST':
form2 = HelpersForm(request, instance=question)
# here lies the problem- the data gathered from form2 is not saved i.e. the multiple choices chosen by user are not returned
if form2.is_valid():
question = form2.save()
form2.save_m2m()
helpers = question.chosenHelpers.all()
for helper in helpers:
sentQ = ReceivedQ(question=question)
sentQ.student = helper
sentQ.save()
return render_to_response('questionsent.html', {'helpers': helpers, 'qid': question.id, 'qtext': q}, context_instance=RequestContext(request))
else:
form2 = HelpersForm(instance=question)
form2.suggesthelpers(question)
return render_to_response('choosehelper.html', RequestContext(request, {'form': form2, 'qid': qid}))