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.
Related
I implemented a django-form with a formset. When I create a new object it works. But I faced to a problem with editing form when I don't change formset data (only data outside formset). Formset raises errors: id requeired. If I mark formset fields to delete and then add new fields it works too. Please, explain me what's going wrong and how to solve this problem. Thanks!
My formset:
IngredientsFormSet = forms.inlineformset_factory(
Recipe,
RecipeIngredientsDetails,
fields="__all__",
can_delete=True,
min_num=2,
max_num=50,
extra=0,
)
And my view-function:
def recipe_edit(request, recipe_id=None):
if recipe_id:
recipe = get_object_or_404(Recipe, id=recipe_id)
else:
recipe = Recipe()
if request.method == "POST":
form = RecipeCreateForm(data=request.POST, files=request.FILES)
formset = IngredientsFormSet(data=request.POST,
prefix=INGREDIENT_FORMSET_PREFIX)
if form.is_valid() and formset.is_valid():
recipe = form.save(commit=False)
recipe.author_id = request.user.id
recipe.save()
form.save_m2m()
formset.instance = recipe
formset.save()
return redirect(reverse_lazy("index"))
context = {"form": form, "formset": formset}
return render(request, template_name="recipe-create.html",
context=context)
form = RecipeCreateForm(instance=recipe)
formset = IngredientsFormSet(
instance=recipe,
prefix=INGREDIENT_FORMSET_PREFIX,
)
context = {
"form": form,
"formset": formset,
}
return render(request, context=context, template_name="recipe-create.html")
Update:
When I set value of the hidden form-field with id="ingredient-INITIAL_FORMS" to zero the errors disappear. This value is the initial number of forms in formset, the question is how to validate them.
I suppose that problems are related to the management_form feature, but what is exact?
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 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)
I am using django for saving in database. In my view function, I used:
form = RecipeForm(instance=Recipe)
where Recipe is the name of my model.
When I go to the url, I get the following error:
__init__() got an unexpected keyword argument 'instance'
I have searched around and found that 'instance' is specifically for model forms. Is there any alternative for forms.Form. If so, can anyone point me in the right direction?
EDIT:
This is my full function in views.py
def recipe_edit(request, pk):
recipe = get_object_or_404(Recipe, pk=pk)
if request.method == "POST":
form = RecipeForm(request.POST, instance=Recipe)
if form.is_valid():
recipe = form.save(commit=False)
recipe.user = request.user
recipe.save()
return redirect('recipe_detail', pk=recipe.pk)
else:
form = RecipeForm(instance=Recipe)
return render(request, 'recipe_edit.html', {'form': form})
And this is my form in forms.py
class RecipeForm(forms.Form):
title= forms.CharField(max_length=500)
description = forms.CharField(max_length=500)
You can pass a initial dictionary when instantiating the form.
initial = {'title': recipe.title, 'description': recipe.description}
form = RecipeForm(initial=initial)
model:
class locations(models.Model):#table
Name = models.CharField(max_length=50,default='Joes quick stop', unique=True)
shop_code = models.CharField(max_length=5,default='AB005',unique=True)
manager = models.ManyToManyField(users)
ast_manager = models.ManyToManyField(users, blank=True, related_name='ast_mng')
sales_manager = models.ManyToManyField(users, blank=True, related_name='sales_mng')
forms:
class locations(models.Model):
Name = models.CharField(max_length=50,default='Joes quick stop', unique=True)
shop_code = models.CharField(max_length=5,default='AB005',unique=True)
manager = models.ManyToManyField(users)
ast_manager = models.ManyToManyField(users, blank=True, related_name='ast_mng')
sales_manager = models.ManyToManyField(users, blank=True, related_name='sales_mng')
class locationsForm(ModelForm):
class Meta:
model = locations
Views
def locations(request):
locations = locations.objects.values().filter(id=request.session['location'])
data=locations[0]
if request.method == 'GET':
if request.session['Manager']== True:
form = locationsForm(initial=data)
context = {'locations': locations, 'form': form}
return render(request, 'locations/locations.html', context)
elif request.method == 'POST':
form=locationsForm(request.POST, instance=data)
if form.is_valid():
cd=form.cleaned_data
form.save()
form = locationsForm()
locations= locations.objects.values().filter(id=request.session['depot'])
context = {'locations': locations}
return render(request, 'locations/locations.html', context)
else:
context = {'locations': locations, 'form': form}
return render(request, 'locations/locations.html', context)
I am trying to display a form that is populated with the relevant data but the user can change and then save/update the form. The above code does a good job of displaying the form with the relevant data but when the user tries to submit it the system tries to save a new record instead of updating the old and fails. I never get past if form.is_valid():
Your problem is that you are converting your locations objects into a list of dictionaries. And then passing a dictionary into the form as instance.
This is happening because you are calling the .values() method on the queryset. That method returns a special ValuesQuerySet which basically looks like a list of dictionaries. Not a list of locations objects.
The instance parameter on the form needs to be an object, not a dictionary. So just simply remove the .values() calls, and it should work. Like this:
def locations(request):
locations = locations.objects.filter(id=request.session['location'])
first_location=locations[0]
if request.method == 'GET':
if request.session['Manager']== True:
form = locationsForm(instance=first_location)
context = {'locations': locations, 'form': form}
return render(request, 'locations/locations.html', context)
elif request.method == 'POST':
form=locationsForm(request.POST, instance=first_location)
if form.is_valid():
cd=form.cleaned_data
form.save()
form = locationsForm()
locations= locations.objects.values().filter(id=request.session['depot'])
context = {'locations': locations}
return render(request, 'locations/locations.html', context)
else:
context = {'locations': locations, 'form': form}
return render(request, 'locations/locations.html', context)