Reputation: 1
New to Django.This is my first code. I am trying to write a code for resturant that takes fields like name, cuisine, price, pic etc. It is supposed to get those fields and files and save it to the media folder. however the code does not work. some of the code is taken from chatgpt as well.
Following is the code for view.py file.
from django.shortcuts import render,redirect
from django.db import IntegrityError
from django.views import View
from django.http import HttpResponse
from .models import Menu
import os
from django.conf import settings
# Create your views here.
class newView(View):
def post(self, request):
name = request.POST.get('name')
cuisine = request.POST.get('cuisine')
price = request.POST.get('price')
food_type = request.POST.get('food_type')
desc = request.POST.get('desc')
pic = request.FILES.get('pic')
context = {
'menu_items': Menu.objects.all(),
'message': None
}
if not name or not cuisine or not price or not food_type or not desc:
context['message'] = "Please don't leave any fields empty!!"
return render(request, 'index.html', context)
try:
# Change the uploaded file name
pic_name = f"{name.replace(' ', '_')}.jpg" # Assuming the uploaded files are in JPEG format
m = Menu(name=name, cuisine=cuisine, price=price, food_type=food_type, desc=desc, pic=pic_name)
print(os.path.join(settings.MEDIA_ROOT, pic_name))
# Save the file to the storage with the new name
with open(os.path.join(settings.MEDIA_ROOT , pic_name), 'wb') as f:
for chunk in pic.chunks():
f.write(chunk)
m.save()
except IntegrityError:
context['message'] = "Duplicate Entry"
return render(request, 'index.html', context)
return redirect('index')
def get(self,request):
p=Menu.objects.all()
context={
'menu_items': p
}
return render(request, 'index.html',context)
def delete_item(request,item_name):
if request.method=="POST":
try:
m=Menu.objects.get(name=item_name)
m.delete()
except Menu.DoesNotExist:
pass
return redirect('index')
def home(request):
return render(request,'home.html')
def menu(request):
menu_items = Menu.objects.all()
grouped_menu = {}
for item in menu_items:
if item.food_type in grouped_menu:
grouped_menu[item.food_type].append(item)
else:
grouped_menu[item.food_type] = [item]
context = {
'grouped_menu': grouped_menu
}
return render(request, 'menu_template.html', context)
NExt file is for the models.py file:
from django.db import models
# Create your models here.
class Menu(models.Model):
name = models.CharField(max_length=100, primary_key=True)
cuisine = models.CharField(max_length=100)
price = models.IntegerField()
food_type = models.CharField(max_length=20,default="Not Specifiec")
desc = models.TextField(default="Description Not Available")
pic = models.ImageField(upload_to='media/menu_images/', default='menu_images/default_image.jpg')
def __str__(self):
return self.name + " : " + self.cuisine
tried changing the folder where the images are stored but didn't work
Upvotes: 0
Views: 22