How can i set image path while saving it - django

when i upload the image from the form it is just saving name of in database not saving the image and uploading to the path, but when i upload the image from database it stores perfectly
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',include('students.urls')),
path('admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
# Create your models here.
class student_registration(models.Model):
registration_number = models.CharField(primary_key=True,max_length=100)
student_name = models.CharField(max_length=100)
student_father_name = models.CharField(max_length=100)
student_image=models.FileField(default='default.jpg', upload_to='media', blank=True)
views.py
from django.shortcuts import render
from .models import student_registration
from django.contrib import messages
from django.conf import settings
# Create your views here.
def student_registeration(request):
if ("registration_no" in request.POST and "student_name" in request.POST
and "student_fname" in request.POST and "student_image" in request.POST):
registration_no = request.POST["registration_no"]
student_name = request.POST["student_name"]
student_fname = request.POST["student_fname"]
student_image = (settings.MEDIA_URL + request.POST["student_image"],
'JPEG')
s = student_registration(registration_no,student_name, student_fname,
student_image)
s.save()
messages.success(request, f'Your account has been created! You are now
able to log in')
return render(request,'students/student_registration.html')
else:
return render(request, 'students/student_registration.html')

The file upload is stored in request.FILES not request.POST. You can retrieve it in the same way and assign it to the student_image field:
s = student_registration(
registration_number=registration_no,
student_name=student_name,
student_father_name=student_fname,
student_image=request.FILES['student_image'] # Retrieve from request.FILES
)
s.save()
You should also make sure that your form is set to enctype="multipart/form-data.

Related

Django redirect another view from another app form

contact/views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
def contactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
# return redirect('success')
return redirect('PostList') #another view from another app
return render(request, "contact.html", {'form': form})
# def successView(request):
# return HttpResponse('Success! Thank you for your message.')
contact/urls.py
from django.contrib import admin
from django.urls import path
from .views import contactView
urlpatterns = [
path('contact/', contactView, name='contact'),
# path('success/', successView, name='success'),
]
blog/views.py
from django.views import generic
from .models import Post, PostImage
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
# context['image_list'] = PostImage.objects.all()
# context['image_list'] = self.get_object().postimage_set.all()
context['image_list'] = PostImage.objects.filter(post__slug=self.kwargs.get('slug'))
return context
blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
]
I need the following in the SIMPLEST DRY manner possible; how do I write this redirect inside contact/views.py?
return redirect('PostList') #another view from another app
PostList is a class-based view from another app called blog. It is the homepage essentially.
for reference..
https://ordinarycoders.com/blog/article/django-messages-framework
In your project folder (eg, my_project/my_project) you should have a urls.py with something like this
path("admin/", admin.site.urls),
path("", include("blog.urls")),
path("", include("contact.urls"))
This allows django to look through all url files in the order listed. So long as all your url names and patterns are unique, then your view should be able to simply do
from django.shortcuts import redirect
from django.urls import reverse
return redirect(reverse('home'))
'home' being the name value of the ListView.
(NB: if you have various applevel urls.py files with path(''... django will take the first one it hits)

Django - missing 1 required positional argument: '_id'

im getting an error
BlogDetailView() missing 1 required positional argument: '_id'
when im trying to access the function BlogDetailView.
views.py :
from django.http.response import Http404
from .models import BlogModel,CommentModel
from .forms import SearchForm,CommentForm
from django.shortcuts import render,redirect
def BlogDetailView(request,_id):
try:
data = BlogModel.objects.get(id = _id)
comments = CommentModel.objects.filter(blog = data)
except BlogModel.DoesNotExist:
raise Http404('Data does not exist')
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
Comment = CommentModel(your_name= form.cleaned_data['your_name'],
comment_text=form.cleaned_data['comment_text'],
blog=data)
Comment.save()
return redirect(f'/blog/{_id}')
else:
form = CommentForm()
context = {
'data': data,
'form': form,
'comments': comments,
}
return render(request,'Test_one/detailview.html',context)
urls.py :
from django.conf.urls import url
from django.urls.conf import path
from blogapp.views import BlogDetailView, BlogListView
from . import views
app_name = "Blogapp"
urlpatterns = [
url(r'^blogs/', views.BlogDetailView, name="blogs"),
url(r'^blog/<int:_id>', views.BlogListView, name="blog"),
]
Can anyone solve this problem?
I think you wrote code wrongly, logically a blog list doesn't need an id to fetch (you want all blog posts so probably don't need id) and you need to fetch a specific blog post so you need an id to fetch this. so I think this is the right code that you tried to write:
from django.conf.urls import url
from django.urls.conf import path
from blogapp.views import BlogDetailView, BlogListView
from . import views
app_name = "Blogapp"
urlpatterns = [
url(r'^blogs/<int:_id>', views.BlogDetailView, name="blogs"),
url(r'^blog/', views.BlogListView, name="blog"),
]

Download BinaryFiled Data

how to download BinaryField Data/file using template. like we did for FileField.
<td><a href={{certificate.bytes.url}} download></a>
I past all url.py and view.py file below please look This may give extract view of my code. and please help me with this i am new to Django. ............................................................................................................................................................
url.py
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.defaults import page_not_found
urlpatterns=[
path('',views.index, name = 'index'),
url(r'^list/$', views.list, name='list'),
url(r'^list/create$', views.certificate_create, name='certificate_create'),
url(r'^list/(?P<id>\d+)/update$', views.certificate_update, name='certificate_update'),
url(r'^list/(?P<id>\d+)/delete$', views.certificate_delete, name='certificate_delete'),
path('download',views.download, name = 'download'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So, we need Django models which contains BinaryField for example.
models.py
class Person(models.Model):
name = models.CharField(max_length=55)
surname = models.CharField(max_length=55)
image = models.BinaryField()
class Meta:
db_table = 'person'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('download/<int:pk>/', views.download, name='download'),
]
views.py
import io
from django.shortcuts import render
from django.http import FileResponse
from .models import Person
def index(request):
# there are listed all models.
persons = Person.objects.all()
return render(request, 'index.html', {'persons': persons})
def download(request, pk):
# this url is for download
try:
obj = Person.objects.get(pk=pk)
except Person.DoesNotExist as exc:
return JsonResponse({'status_message': 'No Resource Found'})
get_binary = obj.image
if get_binary is None:
return JsonResponse({'status_message': 'Resource does not contian image'})
if isinstance(get_binary, memoryview):
binary_io = io.BytesIO(get_binary.tobytes())
else:
binary_io = io.BytesIO(get_binary)
response = FileResponse(binary_io)
response['Content-Type'] = 'application/x-binary'
response['Content-Disposition'] = 'attachment; filename="{}.png"'.format(pk) # You can set custom filename, which will be visible for clients.
return response
index.html
{% for person in persons %}
{{ person.name }}<br />
{% endfor %}
This is solution to send binary file from server and download. All components are shown. Good luck !

why I have issues in importing views in the urls.py file?

from employee import views
does not work!...the server is giving a page not found (404) response
here is the project structure:
employee
migrations folder
....other files
views.py
hrdjango
__init__.py
settings.py
urls.py
I feel like the urls can't access my views
this is the views.py
from .models import Employee
# Create your views here.
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return render(request,"show.html",{'employees':employees})
def edit(request, id):
employee = Employee.objects.get(id=id)
return render(request,'edit.html', {'employee':employee})
def update(request, id):
employee = Employee.objects.get(id=id)
form = EmployeeForm(request.POST, instance = employee)
if form.is_valid():
form.save()
return redirect("/show")
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
path('admin/', admin.site.urls),
path('emp', views.emp),
path('show',views.show),
path('edit/<int:id>', views.edit),
path('update/<int:id>', views.update),
path('delete/<int:id>', views.destroy),
]
urls.py
I am having unresolved import 'employee'message
Is this the project urls.py or the app-level urls.py? If this is your app level urls.py, then the import should be from . import views. If it is the project-level urls.py, then post up your file structure so we can see if the import structure is wrong.
I think the better solution would be to use separate urls.py file for separate apps and then include them to your root urls.
create a urls.py in your app.
in your root urls.py
from django.urls import path,include
urlpatterns = [
...,
...,
path('employee/', include('employee.urls')),
]

Django redirecting to a different view in another app

There are many similar questions to mine on Stack Overflow, but none which solve my problem.
I have a class-based view which accepts files, and once a valid file is found, I would like the website to redirect the user to a template inside a different app, passing in some parameters.
I've seen others put an extra path in 'urlpatterns' and get the view from there. But doing this only makes a GET signal on my command prompt, but not actually changing the web url.
views.py
from django.shortcuts import render, redirect # used to render templates
from django.http import JsonResponse
from django.views import View
from .forms import UploadForm
from .models import FileUpload
class UploadView(View):
def get(self, request):
files_list = FileUpload.objects.all()
return render(self.request, 'upload/upload.html', {'csv_files': files_list})
def post(self, request):
form = UploadForm(self.request.POST, self.request.FILES)
if form.is_valid():
csv_file = form.save()
data = {'is_valid': True,
'name': csv_file.file.name,
'url': csv_file.file.url,
'date': csv_file.uploaded_at}
# REDIRECT USER TO VIEW PASSING 'data' IN CONTEXT
return redirect('graph:chart', file_url=csv_file.file.url)
else:
data = {'is_valid': False}
return JsonResponse(data)
urls.py
from django.urls import path
from . import views
app_name = "upload"
urlpatterns = [
path('', views.UploadView.as_view(), name='drag_and_drop'),
]
urls.py (of other app)
from django.urls import path
from . import views
app_name = "graph"
urlpatterns = [
path('', views.page, name='chart'),
]
You can specify an app name and use exactly the redirect shortcut as you started:
https://docs.djangoproject.com/en/2.1/topics/http/urls/#naming-url-patterns
in the other app urls.py define app_name = 'other_app', and then use redirect('other_app:url_name', parameter1=p1, parameter2 = p2)
you can name easily your parameters either using path (Django >=2.0) or url (re_path for Django >=2.0), for instance:
from django.urls import path
from . import views
urlpatterns = [
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
]