I have created a django app where user uploads multiple pdf files and it converts to png and displays the images. I am using ModelForms for this purpose. The upload and the convert part is working fine but how do I display the Images sequentially?
What I want is to display one image and when the user clicks next, the next image should be displayed. Below is my app code:
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserUploadModel(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE, null = True)
file = models.FileField(upload_to = 'file_uploads/%d%m%Y')
views.py
from django.shortcuts import render, redirect
from app1.forms import UserUploadForm
from app1.models import UserUploadModel
from app1.convert import convert_file
from app1.transfer import move_dir
import os
from project1 import settings
# Create your views here.
def home(request):
if request.method == 'POST':
form = UserUploadForm(request.POST, request.FILES)
if form.is_valid():
f = form.save()
f.user = request.user
f.save()
ff = request.FILES.getlist('file')
f_list = []
for i in ff:
file_instance = UserUploadModel(file = i)
file_instance.save()
f_list.append(file_instance.file.path)
[convert_file(j) for j in f_list]
src_dir = os.getcwd()
dest_dir = os.path.join(src_dir, 'media/converted_files')
move_dir(src_dir, dest_dir, '*.png')
return redirect('app1-display')
else:
form = UserUploadForm()
return render(request, 'app1/home.html', {'form' : form})
def display(request):
return render(request, 'app1/display.html')
home.html
{%extends "app1/base.html"%}
{%block content%}
<form method="POST" enctype="multipart/form-data">
{%csrf_token%}
{{form.as_p}}
<input type="submit">
</form>
{%endblock content%}
You can display all user's image in your template and then use javascript to hide and show images :
app1/display.html
{% extends "app1/base.html" %}
{% block content %}
{% for image in request.user.useruploadmodel_set.all %}
<image src={{ image.url }} style="width: 100%{% if not forloop.first %}; display: none{% endif %}" />
{% endfor %}
<button id="nextBtn">Next</button
<script>
$(() => {
$("#nextBtn").click(() => {
$('image:visible').hide().next().show()
})
})
</script>
{% endblock %}
I've used jquery because I'm more used to it but that could be done with another framework or vanilla JS.
Why not using a JS carousel library ?
Related
I ran into a problem I have questions that are related to items_buy_id , there are also choices that are related to question_id questions
Questions items_buy_id It turns out to connect
And with the choice you will not contact as it should
My models.py
from django.db import models
from datetime import datetime
from phonenumber_field.modelfields import PhoneNumberField
from django_resized import ResizedImageField
from email.policy import default
from django.utils.translation import gettext_lazy
class Items_buy(models.Model):
class Meta:
db_table = 'items_buy'
verbose_name = 'Телефон который покупаем'
verbose_name_plural = 'Телефоны которые покупаем'
image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона')
model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ')
text = models.TextField(max_length=500, verbose_name='Текст')
max_prise_iphone = models.FloatField(verbose_name='Максимальная цена telefoha')
image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy')
def __str__(self):
return self.model_produkt
class Question(models.Model):
class Meta:
db_table = 'question'
verbose_name = 'Вопрос к телефону'
verbose_name_plural = 'Вопросы к телефону'
items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
title = models.CharField(max_length=150,verbose_name='Заголовок вопросa')
question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text')
max_prise_qustion = models.FloatField(verbose_name='Максимальная цена')
def __str__(self):
return self.title
class Choice(models.Model):
class Meta:
db_table = 'choice'
verbose_name = 'Выбор ответа'
verbose_name_plural = 'Выбор ответов'
#items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
question_id = models.ForeignKey(Question, on_delete=models.RESTRICT)
title = models.CharField(max_length=1000, verbose_name='Заголовок выбора')
points = models.FloatField(verbose_name='Цена ответа')
#lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа')
def __str__(self):
return self.title
My urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
path('',views.home, name ='home'),
path('sell_iphone/', views.sell_iphone, name = 'sell_iphone'),
path('sell_iphone_page/<int:pk>/', views.sell_iphone_page, name= 'sell_iphone_page'),
path("getqestion/<int:pk>/", views.getqestion, name = 'getqestion'),
]
My html
{% load static %}
{% block content %}
<head>
<link rel="stylesheet" href="{% static 'css/qestion.css' %}" type="text/css">
</head>
<body>
{% include 'navbar.html' %}
<div class="bar">
{% for question in test %}
<div class="bar_infor_bar">
<div class="bar_infor_bar_title">{{question.title}} </div>
<div class="wraper_sell_in_line_img_class2_qestion_text">{{question.question_text}}</div>
{% for choiceses in choice %}
<div class="bar_infor_button_nav">
<button class="bar_infor_button">{{choiceses.title}}</button>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</body>
{% endblock %}
My views.py
from django.shortcuts import render, redirect
from .models import Items_buy, Question, Choice, Answer, Orders
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
def home(request):
return render(request, 'home.html')
def sell_iphone(request):
limit = request.GET.get('limit')
if limit == None:
limit = 40
limit = int(limit)
iphone = Items_buy.objects.filter()
count = iphone.count()
page = request.GET.get('page')
paginator = Paginator(iphone, 1)
try:
iphone = paginator.page(page)
except PageNotAnInteger:
page = 1
iphone = paginator.page(page)
except EmptyPage:
page = paginator.num_pages
iphone = paginator.page(page)
#pages = list(range(1, (paginator.num_pages + 1)))
iphone = Items_buy.objects.all()
#iphone = iphone[0:limit]
context = {'iphone':iphone, 'count':count, 'paginator':paginator, }
return render(request, 'sell_iphone.html', context)
def sell_iphone_page(request,pk ):
iphones = Items_buy.objects.filter(id=pk)
#question = Question.objects.all()
context = {'iphones':iphones, }
return render(request, 'sell_iphone_page.html', context)
`def getqestion( request, pk):
test = Question.objects.filter(items_buy_id = pk)
choice = Choice.objects.filter(question_id = pk)
context = {'test':test,'choice':choice}
return render(request, 'getqestion.html', context)`
I'm having a problem with the def getqestion function. I linked the question to the product, but the answer to the question didn't work at all
When using select choice = Choice.objects.filter(question_id = pk)
enter image description here
When using select choice = Choice.objects.all()
enter image description here
When using select choice = Choice.objects.filter(id = pk)
enter image description here
And you need 1.test1 to include: da, net, HY TAKOE
And 1.test2 included: 2,1,3
Thanks in advance to anyone who can suggest how to do this!!!
In my case it helped
views.py
class getqestion(generic.DetailView):
model = Items_buy
template_name = 'getqestion.html'
context_object_name = 'testing'
html
<div>
{% for testings in testing.question_set.all %}
<h1>{{testings.titles}}</h1>
<h3>{{testings.question_text}}</h3>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% csrf_token %}
<form action="{% url 'vote' testings.id%}" method="post">
{% for choice in testings.choice_set.all %}
<input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{choice.title}}</label>
{% endfor %}
{% endfor %}
</div>
<input type="submit" value="vote">
</form>
The page should display a feedback form and links created in the admin panel. Created models:
from django.db import models
class ContactModel(models.Model):
# feedback form
name = models.CharField(max_length=50)
email = models.EmailField()
website = models.URLField()
message = models.TextField(max_length=5000)
create_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.name} - {self.email}'
class ContactLink(models.Model):
# links
icon = models.FileField(upload_to='icons/')
name = models.CharField(max_length=200)
def __str__(self):
return self.name
I connected the models to the admin panel:
from django.contrib import admin
from .models import ContactModel, ContactLink
#admin.register(ContactModel)
class ContactModelAdmin(admin.ModelAdmin):
list_display = ['id', 'name', 'email', 'create_at']
list_display_links = ('name',)
admin.site.register(ContactLink)
Everything works correctly, you can create links in the admin panel.
Below views.py:
from django.shortcuts import render
from django.views import View
from .models import ContactLink
class ContactView(View):
def get(self, request):
contacts = ContactLink.objects.all()
form = ContactForm()
return render(request, 'contact/contact.html', {'contact': contacts, 'form': form})
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('contact/', views.ContactView.as_view(), name='contact'),
path('feedback/', views.CreateContact.as_view(), name='feedback'),
]
I go through the for loop through the code to return links from the admin panel:
#links
<div class="contact__widget">
<ul>
{% for contact in contacts %}
<li>
<img src="{{ contact.icon.url }}">
<span>{{ contact.name }}</span>
</li>
{% endfor %}
</ul>
</div>
#feedback form
<form action="{% url 'feedback' %}" method="post">
{{ form }}
<button type="submit" class="site-btn">Submit</button>
</form>
The Feedback form works fine, but links are not displayed at all on the page... Where could the error be?
Screenshot
The view must reference to the correct variable name. Use contact with an s in:
return render(request, 'contact/contact.html', {'contacts': contacts, 'form': form})
I am trying to upload pic for specific user but nothing happened when i select image and upload it . it not store in db and not even in media folder
setting.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
View.py
def uploadPic(request):
if request.method == 'POST' and 'SESSION_KEY' in request.session:
form = Profile(
user_id=request.session['SESSION_KEY'],
profile_pic=ProfileForm(request.POST, request.FILES)
)
form.save()
return redirect('home')
else:
form = ProfileForm()
return render(request, 'upload.html', {
'form': form
})
Model.py
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(null=True, blank=True, upload_to='image/')
Form.py
class ProfileForm(forms.ModelForm):
class Meta:
model = ProfileModel
fields = ['profile_pic']
Template
{% extends 'home.html'%}
{% block content %}
{%if user.is_authenticated%}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
{% endif %}
{% endblock %}
Firstly in your form you set model = ProfileModel but your model is Profile correct that:
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['profile_pic']
Next in your view in case of a POST request your view is completely wrong. You try to make an instance of Profile and call it form and save it. This is likely failing. Also I assume you write 'SESSION_KEY' in request.session in an attempt to check if the user is logged in, instead use request.user.is_authenticated or in fact disallow anonymous users from accessing your views by using the login_required decorator. Change it like so:
from django.contrib.auth.decorators import login_required
#login_required
def uploadPic(request):
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('home')
else:
form = ProfileForm()
return render(request, 'upload.html', {'form': form})
Note: The indentation of my answer is 4 spaces which is different from your indentation. It is best to indent by 4 spaces for readability. Check about indentation in PEP 8 which is the Style Guide for Python Code.
models.py
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.CharField(max_length=100, unique=True)
post_pic = models.ImageField(upload_to ='media/post_pics/', default =None )
body = models.TextField()
posted = models.DateTimeField(db_index=True, auto_now_add=True)
#author = must be logged in, populate from login details
forms.py
class postForm(forms.Form):
title = forms.CharField(max_length=100)
slug = forms.CharField(max_length=100)
post_pic = forms.ImageField()
body = forms.CharField(widget=SummernoteWidget())
views.py
def write_detail(request):
template_name = 'blog/write.html'
if request.method == 'POST':
post_form = postForm(request.POST)
if post_form.is_valid():
new_post = Blog(title=title,slug=slug,post_pic=post_pic,body=body)
new_post.save()
return HttpResponseRedirect(blog.get_absolute_url())
else:
post_form = postForm()
return render(request, template_name, {'post_form': post_form})
write.html
{% extends 'blog/base.html' %}
{% load static %}
{% block back-img %}'{% static 'blog/assets/img/intro.jpg' %}'{% endblock back-img %}
{% block titdes %}Write{% endblock titdes %}
{% block title %}Write{% endblock title %}
{% block pagedes %}A django powered community blog{% endblock pagedes %}
{% block body%}
<form method = "POST">
{{ post_form.as_p }}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Publish</button>
</form>
{% endblock %}
I have set up this form so that authors can write articles to the blog without accessing the admin panel and I believe it should work but it isn't saving to the database.
I have tried to work on the views over and over but don't know what else to do. Please don't delete my question just ask any question that can help you help me.
in your forms.py
try
from .models import Blog
class postForm(forms.Form):
title = forms.CharField(max_length=100)
slug = forms.CharField(max_length=100)
post_pic = forms.ImageField()
body = forms.CharField(widget=SummernoteWidget())
class Meta:
model = Blog
fields = ('title', 'slug', 'post_pic', 'body')
PS. Iam new to Django, i hope this help you.
It looks like you just need to save the form, but you're creating a new Blog object with values that we can't see defined anywhere.
new_post = Blog(title=title,slug=slug,post_pic=post_pic,body=body)
title, slug, etc don't get defined.
What you should do, is change it to a ModelForm so that django does all the hard work;
class postForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'slug', 'post_pic', 'body')
widgets = {
'body': SummernoteWidget(),
}
Then in your view you just need to do;
def write_detail(request):
template_name = 'blog/write.html'
if request.method == 'POST':
post_form = postForm(request.POST)
if post_form.is_valid():
post_form.save()
return HttpResponseRedirect(blog.get_absolute_url())
else:
# GET request
post_form = postForm()
return render(request, template_name, {'post_form': post_form})
The summernote docs for forms (and modelforms) is here
Don't forget, that when using a widget like this that comes with media, you need to add the form's media to the template.
You can access it in the HTML using either {{ form.media }} to get all CSS and JS, or individually as {{ form.media.js }} and {{ form.media.css }}
You can see how they do it in the summernote app playground
class postForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'slug', 'post_pic','body')
widgets = {
'body':SummernoteWidget(),
}
Sorry guys you can actually use django summer note with a model form. I used it before but the editor was not appearing so I changed it to the one I previously posted but after reading another answer on stack overflow. I found out that I didn't add this code below to my HTML files or just inside my base.html
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.3/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.3/summernote.js"></script>
Thanks guys
I'm trying to create a delete view for my product form, my problem is with the submit button, it doesn't delete my object, it just redirects me to previous page.
This a Windows 7 machine, Python 3.7.1, Anaconda 2018.12
I've tried eliminating the line: if request.method == "POST"
And without that line the object is eliminated, so I think the problem is with the if statement or the POST method, but couldn't solve it
views.py:
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ProductForm, RawProductForm
from .models import Product
def product_delete_view(request, id):
obj = get_object_or_404(Product, id=id)
if request.method == "POST":
obj.delete()
return redirect('../')
context = {
"object": obj
}
return render(request, "products\\product_delete.html", context)
product_delete.html:
{% extends 'base.html' %}
{% block try %}
<form action='.' method='POST'>{% csrf_token %}
<h1>Do you want to delete the product "{{ object.title }}"?</h1>
<p>
<input type="submit" value="Yes" />
Cancel
</p>
</form>
{% endblock %}
The idea is that when I click "Yes", the object disappears, but instead I am redirected to the page of the actual object I wanted to delete