Cannot view the image uploaded on the admin panel - python

Picture gets uploaded on the django admin panel but when i click on the image on the panel it shows the page not found error.
forms.py
class ApproveImgForm(forms.ModelForm):
class Meta:
model = ApprovImg
fields = ['photo']
urls.py
path('w_p.html', views.WProduct_list, name='WProduct_list'),
views.py
def WProduct_list(request, category_slug=None):
category = None
categories = Category.objects.all()
wproducts = Product.objects.filter()
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
wproducts = Product.objects.filter()
if(request.method=='POST'):
form = ApproveImgForm(request.POST, request.FILES)
form.save()
context = {
'category': category,
'categories': categories,
'wproducts': wproducts,
}
return render(request, 'shop/w_p.html', context)
models.py
class ApprovImg(models.Model):
photo=models.ImageField(upload_to='products/%Y/%m/%d')
def __str__(self):
return str(self.photo)
w_p.html
<tr>
<td>{{ product.name }}</td>
<td> {{ product.price }}</td>
<td><form action="w_p.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit">
</form>
</td>
</tr
Can someone please help?

You should inherit from ModelForm.
class ApproveImgForm(forms.ModelForm):
class Meta:
model = ApprovImg
fields = "__all__" # not recommended, you should specify the fields.
# views.py
def upload_file(request):
if request.method == 'POST':
form = ApproveImgForm(request.POST, request.FILES)
if form.is_valid():
# file is saved
form.save()
return HttpResponseRedirect('/home/')
else:
form = ApproveImgForm
return render(request, 'upload_image.html', {'form': form})
# urls.py
urlpatterns = [path('upload', upload_file, name='upload')]
# upload_image.html
<form action="{% url 'upload' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.photo.label_tag }} {{ form.photo.help_text }}</p>
<p>
{{ form.photo.errors }}
{{ form.photo }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>

Related

The Django form could not be submitted accordingly

views.py
#login_required(login_url='login/')
def add_country(request):
if request.method == 'POST':
form = CountryForm(request.POST,request.FILES)
if form.is_valid():
new_form = form.save(commit=False)
new_form.edited_by = request.user
new_form.save()
return redirect('country_details')
else:
form = CountryForm()
context = {'form':form}
return render(request,'add_country.html',context)
models.py
class Countries(models.Model):
CONTINENTS = [
('Asia','Asia'),
('Europe','Europe'),
('Africa','Africa'),
('Oceania','Oceania'),
('North America','North America'),
('South America','South America'),
]
name = models.CharField(max_length=75)
continent = models.CharField(max_length=50,choices=CONTINENTS,null=True)
landmark = models.CharField(max_length=100,null=True)
food = models.CharField(max_length=100,null=True)
entertainment = models.CharField(max_length=100,null=True)
flag = models.FileField(upload_to='flags', default='default.png',null=True)
image = models.FileField(upload_to='travel', default='default.png',null=True)
edited_by = models.OneToOneField(User,on_delete=models.CASCADE,null=True)
last_updated = models.DateTimeField(auto_now_add=True,null=True)
def __str__(self):
return self.name
add_country.html
<form method="POST" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form.name.label }}<br>
{{ form.name }}<br><br>
{{ form.landmark.label }}<br>
{{ form.landmark }}<br><br>
{{ form.food.label }}<br>
{{ form.food }}<br><br>
{{ form.entertainment.label }}<br>
{{ form.entertainment }}<br><br>
{{ form.flag.label }}<br>
{{ form.flag }}<br><br>
{{ form.image.label }}<br>
{{ form.image }}<br><br>
<input type="submit" class="btn btn-primary" value="Add">
</form>
I have an issue that after I added the edited_by to assign the currently logged in user into that column then the form could not be submitted and only stayed on the same page instead of redirecting to the page that I want. I have tried different ways to make the form being submitted such as put request.method == "POST" and the page didn't work. However before I added edited_by into the models the form could be submitted accordingly and the data is being updated. May I ask what is the method to assign the user into the column edited_by after that user has added a post?
I think you have included edited_by field in your forms too.
If you are handling this field by yourself in the views then remove this field from your forms.
class CountryForm(forms.ModelForm):
class Meta:
model = Country
exclude = ['edited_by'] # or specify only required fields in form
Now your view will work fine.
Note: You can display your form's errors with {{form.errors}} in your template.

django modelform how to know input type is checkbook?

My modelform is a dynamically generated modelform,I want to know the type of is_true in the modelForm. The type of the input tag is the checkbook type.
If I know the type=‘checkbox’ of the is_true field, add a class attr to him separately.
The default type='checkbox’ interface is too ugly
models
class Employee(AbstractBaseUser):
"""
用户表
"""
username = models.CharField(max_length=30, verbose_name='姓名')
email = models.EmailField(verbose_name='邮箱', unique=True)
is_true = models.BooleanField(default=False, verbose_name='是否超级用户')
views
class ModelFormDemo(ModelForm):
class Meta:
model = self.model
if self.list_editable:
fields = self.list_editable
else:
fields = '__all__'
excluded = self.excluded
def __init__(self, *args, **kwargs):
super(ModelFormDemo, self).__init__(*args, **kwargs)
def add_view(self, request):
form = ModelFormDemo()
if request.method == "POST":
res_dict = {'status': 1, 'msg': 'success'}
form = ModelFormDemo(request.POST)
if form.is_valid():
obj = form.save()
else:
res_dict['msg'] = form.errors
res_dict['status'] = 2
return JsonResponse(res_dict)
return render(request, "xadmin/add_view.html", locals())
html
<form class="layui-form" method="post">
{% csrf_token %}
{% for field in form %}
{% if field.name == 'employee' %}
<input type="hidden" name="employee" value="{{ user.id }}">
{% else %}
<div class="layui-form-item">
<label class="layui-form-label">{{ field.label }}</label>
<div class="layui-input-inline">
{{ field }}
</div>
</div>
{% endif %}
{% endfor %}
<div class="layui-form-item">
<div class="layui-input-block">
<input type="button" class="layui-btn" lay-filter="add" lay-submit="" value="add">
</input>
<button type="reset" class="layui-btn layui-btn-primary">reset</button>
</div>
</div>
</form>
You can use the Widget.attrs arg in your form __init__ method.
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

form.is_valid always return false

form.is_valid in views.py always return false. I have used Django forms to create a form and html to implement it.
I will upload this photo to imgur using imgurpython later, but first this should work.
views.py
def upload_view(request):
usr = check_validation(request)
if usr:
if request.method == "GET":
form = PostForm()
return render(request, 'upload.html', {'form': form})
elif request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
pic = form.cleaned_data.get('image')
title = form.cleaned_data.get('caption')
post = PostForm()
post.user = usr
post.caption = title
post.image = pic
post.save()
return redirect('feed/')
else:
return render(request, 'upload.html', {'error_msg' : "Invalid Inputs"})
else:
return redirect('/login/')
models.py
class Post(models.Model):
user = models.ForeignKey(User)
image = models.FileField(upload_to='user_images')
caption = models.CharField(max_length=240)
image_url = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['user', 'image', 'caption']
template - upload.html
<form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;">
{% csrf_token %}
<p class="text-16">Upload to aperture.</p>
{{ form }}
<p class="text-16">{{ error_msg }}</p>
<input class="login-btn" type="submit" value="Upload"/>
</form>
Try this,
<form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;">
{% csrf_token %}
{{ form }}
<input class="login-btn" type="submit" value="Upload"/>
</form>
If this doesn't work, print the request.POST and request.FILES then update the answer with the contents.
Your context has only one variable named form so you have to use that only to make your form work.
<form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;">
{% csrf_token %}
<p class="text-16">Upload to aperture.</p>
<input type="file" accept="image/*" value="{{ form.image }}" name="image" class="login-btn"/><br/>
<input placeholder="Caption" class="input-default all-curve" rows="3" value="{{ form.caption }}" name="caption" />
<p class="text-16">{{ form.error_msg }}</p>
<input class="login-btn" type="submit" value="Upload"/>
</form>

Can't get past Django MultiValueDictKeyError on specific form id?

So, everytime I submit my form, I always get this error
MultiValueDictKeyError at /template/ 'form-21-id'
Here is my views.py:
class SomeTemplate(TemplateView):
template_name = 'template/index.html'
def get_context_data(self, **kwargs):
context = super(AttendanceTemplate, self).get_context_data(**kwargs)
instruction = Instruction(self.request.user.username)
sections_list = self.request.GET.getlist('sections_list')
term = self.request.GET.get('term', instruction.term)
enrollments = Enrollment.objects.using('api').prefetch_related('profile').filter(section_id__in=['111111'], term=term)
attendanceQuery = Enrollment.objects.using('api').prefetch_related('student').filter(section_id__in=['111111'], term=term)
#logger.error(dir(attendanceQuery))
#logger.error(attendanceQuery.values())
for enrollment in attendanceQuery:
#logger.error(enrollment.student.first_name)
attendance, created = Attendance.objects.update_or_create(
section_id=enrollment.section_id,
term=enrollment.term,
first_name=enrollment.student.first_name,
last_name=enrollment.student.last_name,
email_address=enrollment.student.email_address,
meeting_date=timezone.now(),
section_info=3,
)
something = Attendance.objects.filter(section_id__in=['111111'], term=term)
formset = AttendanceFormSet(queryset=something)
combined = zip(enrollments, formset)
context['combined'] = combined
context['formset'] = formset
return context
def post(self, request):
formset = AttendanceFormSet(request.POST)
logger.error(formset.errors)
if formset.is_valid():
formset = formset.save();
return render_to_response("template/index.html", {'formset': formset},context_instance=RequestContext(request))
else:
return HttpResponse(request.POST)
Here is my index.html file:
<form method="POST" action="">
{% csrf_token %}
{{ formset.management_form }}
{% for enrollment, form in combined %}
{{ form.id }}
{% for hidden in combined %}
{{ hidden.hidden_fields }}
{% endfor %}
<div class="wrapper-formset">
<div>
{{ form.first_name.value }}
{{ form.last_name.value }}
{{ form.email_address.value }}
</div>
<div class="clear-all"></div>
</div>
{% endfor %}
<button type="submit" class="save btn btn-default">Save</button>
</form>
I've included the following key form properties in my template as well:
form.id
management form
hidden fields
What am I missing? Doing it wrong? DB issue?

UpdateView with Multiple Formset not working

I tried creating a generic UpdateView for a model with generic relations with 2 other models, based on the CreateView provided in this tutorial.
The form and formsets are populated as expected, but when I save I get redirected to the model detail page and changes are not saved.
My question is similar to this one but the suggestions provided are not helpful because they are specific to the former question.
Here is my code :
# models.py
class Ingredient(models.Model):
...
content_type = models.ForeignKey(ContentType, editable=False)
object_id = models.PositiveIntegerField(editable=False)
content_object = GenericForeignKey()
class Step(models.Model):
Same as Ingredient
class Recipe(models.Model):
...
ingredients = generic.GenericRelation(Ingredient)
steps = generic.GenericRelation(Step)
# forms.py
class RecipeForm(forms.ModelForm):
class Meta:
model = Recipe
IngredientFormSet = generic_inlineformset_factory(Ingredient, extra=1)
StepFormSet = generic_inlineformset_factory(Step, extra=1)
# views.py
class RecipeUpdate(UpdateView):
model = Recipe
form_class = RecipeForm
template_name = 'app_recipes/recipe_add.html'
def get(self, request, *args, **kwargs):
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
ingredient_form = IngredientFormSet(instance = self.object)
step_form = StepFormSet(instance = self.object)
return self.render_to_response(self.get_context_data(
form=form,
ingredient_form=ingredient_form,
step_form=step_form))
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
ingredient_form = IngredientFormSet(self.request.POST, instance=self.object)
step_form = StepFormSet(self.request.POST, instance=self.object)
if (form.is_valid() and ingredient_form.is_valid() and step_form.is_valid()):
return self.form_valid(form, ingredient_form, step_form)
else:
return self.form_invalid(form, ingredient_form, step_form)
def form_valid(self, form, ingredient_form, step_form):
self.object = form.save()
ingredient_form.instance = self.object
ingredient_form.save()
step_form.instance = self.object
step_form.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form, ingredient_form, step_form):
return self.render_to_response(self.get_context_data(
form=form,
ingredient_form=ingredient_form,
step_form=step_form))
def get_success_url(self):
return reverse('recipe_detail', kwargs={'pk': self.object.pk})
I am using the same template used by CreateView :
...
<script src="{{ STATIC_URL }}js/jquery.formset.js"></script> # django-dynamic-formset
<script type="text/javascript">
$(function() {
$(".inline.{{ ingredient_form.prefix }}").formset({
prefix: "{{ ingredient_form.prefix }}",
})
$(".inline.{{ step_form.prefix }}").formset({
prefix: "{{ step_form.prefix }}",
})
})
</script>
...
<form action="." method="post">
{% csrf_token %}
<div>
{{ form.as_p }}
</div>
<fieldset>
<legend>Recipe Ingredients</legend>
{{ ingredient_form.management_form }}
{{ ingredient_form.non_form_errors }}
{% for form in ingredient_form %}
{{ form.id }}
<div class="inline {{ ingredient_form.prefix }}">
{% for field in form.visible_fields %}
<div>
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
</div>
{% endfor %}
</fieldset>
<fieldset>
<legend>Recipe Steps</legend>
{{ step_form.management_form }}
{{ step_form.non_form_errors }}
{% for form in step_form %}
{{ form.id }}
<div class="inline {{ step_form.prefix }}">
{% for field in form.visible_fields %}
<div>
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
</div>
{% endfor %}
</fieldset>
<input type="submit" value="Add recipe" class="submit" />
</form>
...
NB : I use django-dynamic-formset in the template to dynamically add and remove forms in formsets.
Thank you

Categories