Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write a query to get the number of times a choice is selected by users
I want to count the number of times a choice is selected by users. Here is my model models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from multiselectfield import MultiSelectField class MedicalHistory(models.Model): Anxiety = 'Anxiety' Arthritis = 'Arthritis' Asthma = 'Asthma' Anemia = 'Anemia' Cancer = 'Cancer' Corona_virus = 'Corona_virus' Diabetes = 'Diabetes' Ebola = 'Ebola' HIV = 'HIV' ILLNESS_CHOICES = ( (Anxiety, "Anxiety"), (Arthritis, "Arthritis"), (Asthma, "Asthma"), (Anemia, "Anemia"), (Cancer, "Cancer"), (Corona_virus, "Corona_virus"), (Diabetes, "Diabetes"), (Ebola, "Ebola"), (HIV, "HIV"), ) user = models.ForeignKey(User, on_delete=models.CASCADE) illness = MultiSelectField(choices=ILLNESS_CHOICES, max_length=50) symptoms = models.CharField(max_length=100) additional_info = models.CharField(max_length=100) disability = models.BooleanField(default=False) medications = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} Medical History' Here I have a number of illnesses I want users to select from. A user can select more tan one illness. I want each illness to have a count, and every time the illness is selected it adds to the count. In my view I have views.py def pie_chart(request): labels = [] data = [] queryset = MedicalHistory.objects.values('illness').annotate(count=Sum('user')).order_by('-count') for entry in queryset: labels.append(entry['illness']) data.append(entry['count']) return JsonResponse(data={ 'labels': labels, 'data': data, }) <QuerySet [{'illness': ['Asthma', 'Diabetes', 'Ebola'], 'count': 3}, {'illness': ['Anemia', 'Covid-19'], 'count': 2}]> The query … -
Django setup elasticsearch client with password auth
My Django application uses elasticsearch to index several ressources. Now I wanted to protect my elasticsearch instance with as password wich is working fine if I use "curl -u" or so. Anyways from the elasticsearch_dsl documentation, found here: https://elasticsearch-dsl.readthedocs.io/en/latest/configuration.html I do not understand what I have to do in order to setup elasticsearch that way that it uses a password for authentication and where do I have to place this code?! Is smb. maybe able to pass show me some snippets of his configuration? My current state looks like this: settingy.py ELASTICSEARCH_DSL = { 'default': { 'hosts': env.str('ELASTICSEARCH_HOST') + str(':') + env.str('ELASTICSEARCH_PORT'), }, } ELASTICSEARCH_DSL_SIGNAL_PROCESSOR = 'django_elasticsearch_dsl.signals.RealTimeSignalProcessor' documents.py from django_elasticsearch_dsl import Document, Index, fields from elasticsearch_dsl import analyzer from App.models import Post # elasticsearch index posts = Index('posts') html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @posts.document class PostDocument(Document): ... more index stuff According to the docs I have to manually setup a default client connection where I can also pass the password and username for authentication wich to me seems not to be possible at settings.py at moment. Kind regards -
image is not showing in django templates am new in django and working on a project...i idid lots of rid of this error but nothing happen
am trying to show pic in django tempate but its not working here is my settings.py where the path of static and media file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR , "media") this is my model.py the image is store under static/img folder class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) image_of_load = models.ImageField(default='',upload_to='static/img') weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) this is my html template for showing user posted data {% extends "post.html" %} {% block content %} {% load static %} {% for loader in Loader %} <h4>Loader Id- {{loader.id}}</h4> Username-{{user.username}} <h3>Sender name-{{loader.sender_name}}</h3> </h4> <p class="card-text"> <h4>pick up station-{{loader.pick_up_station}}</h4> </p> <img src="{{ loader.image.url }}" alt="image"> <p class="card-text">{{loader.destination_station}}</p> <p class="card-text">{{loader.phone_number}}</p> <p class="card-text">{{loader.receiver_name}}</p> <p class="card-text">{{loader.sending_item}}</p> <p class="card-text">{{loader.weight}}</p> <p class="card-text">{{loader.quantity}}</p> <p class="card-text">{{loader.pick_up_time}}</p> <p class="card-text">{{loader.drop_time}}</p> <p class="card-text">{{loader.paid_by}}</p> <p class="card-text">{{loader.created_at}}</p> <a class="btn btn-primary" href="{% url 'Loader:Delete' loader.id %} ">delete</a> <a class="btn btn-primary" href="{% url 'Loader:Update' loader.id %} ">update</a> </div> {% endfor %} {% endblock content %} … -
WebSocket connection to <heroku-app>' failed: Error during WebSocket handshake: Unexpected response code: 500
I deployed django-channels project on heroku. The project works fine locally but on heroku it doesn't function, i-e no websocket connection is established. my consumers.py is: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'quiz_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) my routing.py is: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import quiz_app.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( quiz_app.routing.websocket_urlpatterns ) ), }) my Procfile is : web: daphne quizbackend.asgi:application --port $PORT --bind 0.0.0.0 -v2 And I am using in-memory layer for testing purpose, which is : CHANNEL_LAYERS={ "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } also my heroku logs --tail are : 2020-04-09T11:16:08.616718+00:00 app[web.1]: ^ 2020-04-09T11:16:08.616718+00:00 app[web.1]: 2020-04-09T11:16:08.616903+00:00 app[web.1]: 2020-04-09 11:16:08,616 INFO failing WebSocket opening … -
Django CSRF Token is not getting set
So i am using VueJS and Django. Axios to make a get request. When i try to retrieve the CSRF token and log it, it shows me it is null. here is my serializer: class VehicleSerializer(serializers.ModelSerializer): seller = serializers.SerializerMethodField() class Meta: model = Vehicle fields = ('vehicle_id', 'color', 'model', 'year', 'category', 'manufacturer', 'seller') def get_seller(self, instance): return instance.seller.customer.username My Viewset: class VehicleListCreateAPIView(ListCreateAPIView): serializer_class = VehicleSerializer permission_classes = [IsAuthenticated] queryset = Vehicle.objects.all() def perform_create(self, serializer): request_user = self.request.user try: seller = Seller.objects.get(customer = request_user) except Seller.DoesNotExist: seller = Seller.objects.create(customer = request_user) serializer.save(seller = seller) My urlpattern: path('vehicles/', VehicleListCreateAPIView.as_view()), The code from django documentation to retrieve a token: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); export { csrftoken }; -
Django admin page and CSS
I'm very new to django. I just did the very basic step for creating a project which has one application. I started the server using python manage.py runserver which ended up giving me my home page. but when I opened the admin page it was not with proper CSS as it is supposed to be. I went through some solutions like adding the following code so that my static files are added correctly. STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' But this doesn't reflect anything after running python manage.py collectstatic. Do I need something else to done further? This is the settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(9szxe#x0q67)^wc6us01*i$=1)!&f7)530%73=pvzzhwp23gp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'technicalCourse.apps.TechnicalcourseConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { … -
attempt to write a readonly database - Django app deployed on App Engine (SQLite3 DB)
I have hosted Django app using App Engine standard environment. When I try to login, it gives me 'attempt to write a readonly database' error . I have added URL to ALLOWED HOSTS and added in admin credentials in DATABASE in settings.py. Everything else works as intended. app.yaml # [START django_app] runtime: python37 service: hellotest1 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # required when static routes are defined, but can be omitted (along with # the entire handlers section) when there are no static files defined. - url: /.* script: auto # [END django_app] settings.py - DATABASES and ALLOWED_HOSTS ALLOWED_HOSTS = ['url'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'USER': 'admin', 'PASSWORD': 'admin', } } -
Django IIS Active Directory Single Sign On (SSO)
I have application written in Django, hosted with IIS on my intranet with Active Directory. Following this stackoverflow topic https://stackoverflow.com/a/26987622/4992056 I managed to create basic domain authentication. Unfortunately this solution reqiures login with domain account credentials everytime I rerun browser what is not ideal user experience and brings security issues (browser prompts user to save their domain account credentials). I would like to have true single sign-on feature that means: when user is signing in with his domain account, he/she should also be signed in to the web app without prompting for password. Thanks in advice for your answers. Best regards, Wojtek -
IntegrityError in database stored vlaues in django?
''' My problem is database values can't stored properly In below I uploded views functions file,model file as an images. so in model there are three fields but database stored only image stored and other vlaues strored by default get null values so can you help to solving my problem.. ''' userproblem.html <form method="POST" action="/uploadoc/" enctype="multipart/form-data" data-toggle="validator"> {% csrf_token %} <div id="progressbarwizard"> <ul class="nav nav-pills bg-light nav-justified form-wizard-header mb-3"> <li class="nav-item"> <a href="#account-2" data-toggle="tab" class="nav-link rounded-0 pt-2 pb-2"> <i class="mdi mdi-account-circle mr-1"></i> <span class="d-none d-sm-inline">Query Form</span> </a> </li> </ul> <div class="tab-content b-0 mb-0"> <div class="tab-pane" id="account-2"> <div class="row"> <div class="col-md-5"> <label class="col-md-12 col-form-label">Query Types: <span class="text-danger">*</span></label> <div class="col-md-8"> <input type="text" class="form-control" data-validate="true" name="queryn" placeholder="Enter Query Types"> </div> </div> <div class="col-md-5"> <label class="col-md-12 col-form-label">Description of Query: <span class="text-danger">*</span></label> <div class="col-md-12"> <textarea type="text" class="form-control" data-validate="true" name="querydec" placeholder="Description of Query"></textarea> </div> </div> </div><!-- /.First row end --><br> <div class="row"> <div class="col-md-5"> <label for="Emailadrress" class="col-md-12 col-form-label">Upload Your File: <span class="text-danger"></span></label> <div class="col-md-12"> <div class="input-group-append"> <input type="file" id="img" name="img" accept="image/*"> </div> </div> </div> <div class="col-md-6"> <label for="Emailadrress" class="col-md-12 col-form-label">Solutions: <span class="text-danger"></span></label> <div class="col-md-12"> <div class="input-group-append"> <textarea type="text" name="querysol" placeholder="Solutions of Query"></textarea> </div> </div> </div> </div> <!-- /.second row end --> </div><br> <div class="row"> <div class="col-12"> … -
How to run a function witth (request) every hour?
i have function: def coins_costs_load(request): response = requests.get( 'https://explorer-api.minter.network/api/v1/coins').json()['data'] for coin in response: coin_crr = coin['crr'] coin_id = coin['symbol'] obj = CoinCosts.objects.create( crr=coin_crr, coin_id_id=coin_id) obj.save() It works great and everything is fine. But how to automatically run a function every hour? I tried all the methods, and the shedule plugin, and the built-in tools. They do not work with the request argument. Gives an error message. And if you remove the argument, also an error... Please help! Thanks! -
Django ModelForm save to another database
I have a set up with multiple databases: let's call them db1, db2 and db3. db1 is default. I now have a ModelForm that is meant to save an object Customer to db2. class CustomerCreateForm(ModelForm): class Meta: model = Customer fields = ["name", "type"] My view: if "create" in request.POST: f = CustomerCreateForm(data=request.POST) customer = f.save(commit=False) # Error -> no table 'customer' on database 'db1' customer.date_joined = datetime.now() customer.save(using='db2') It appears that the save() method does not have a using argument. How can I save an instance of Customer to db2? -
saving to django models using ajax
I am trying to save a users data into the database. Iam trying to get one input from the user that is the answer, then I want to get the question that has been assigned to the user that is the First_question variable. I tried to track if the selected_answer and assigned_question has been parsed to the view and it did. but then I get an error: NOT NULL constraint failed: study_answer.question_id [246, None, None, 30.0, '2020-04-09 13:53:36.008824', '2020-04-09 13:53:36.008849'] self sql ('INSERT INTO "study_answer" ("participant_id", "question_id", "answer", ' '"completion_time", "created_at", "updated_at") VALUES (%s, %s, %s, %s, %s, ' '%s)') from my understanding it seems that both question_id and answer_id are not being able to be parsed. although when I printed them I got the answer as in text and the question id. views.py participant = get_object_or_404(Participant, user=request.user) selected_choice = request.POST.get('selected_choice') assigned_question = request.POST.get('assigned_question') completion_time = 30 answer = Answer(participant=participant, question=assigned_question, answer=selected_choice, completion_time=completion_time) answer.save() template.html <p name="question" id="{{First_question.id}}"> {{First_question}} </p> {% for i in all_choices %} <input type="radio" id="{{ i.id }}" name="choice" value="{{ i.choice_text }}"> <label for="{{ i.id }}">{{ i.choice_text }}</label> {% endfor %} <button type="button" id="Submitbutton" class="btn btn-primary" onclick=Nextquestion() >Next</button> </div> <script> function Nextquestion(){ selected_choice = $("input[type='radio'][name='choice']:checked").val(); assigned_question = … -
how to Convert ruby on rails code to Django?
i want convent this code from ruby on rails to django just example class HomeController < ApplicationController include BusinessPlans include CreditRepairPlan include FinancePlan skip_before_action :verify_authenticity_token, only: [:get_plan,:get_credit_repair_plan, :get_finance_plan] before_action :authenticate_user! def index end def upgrade end -
Matching database columns in the filtering in Django
I'd like to match database columns in the query. How is this possible? For example select * from docs where mlal_id_no=8 AND column1= column2 qs = docs.objects.filter(mlal_id_no=8,column1=column2) -
Can't use django 2.2 with django-oscar-wagtail for wagtail cms
I am using: django 2.2 django-oscar 2.0.4 I can't use wagtail<2.6 since I am using django 2.2( django2.2 support is with wagtail 2.6 ). And django-oscar-wagtail require wagtail <2.4. Can you give me some ideas to use wagtail with django-oscar? -
Django get user like from friend list
I'm a Django beginner, I have a friend field in Profile Model which list all my friend users. And also these friends liked my post. How do I get the names of only those users in my friends list to display in the post they liked. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) friends = models.ManyToManyField('Profile',related_name='my_friends') class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL) likes = models.ManyToManyField(User, related_name='image_likes') def home(request): #...... -
custom context processor not working for displaying cart items
This is my custom context code for displaying cart def cart(request): return {'cart': Cart(request)} and added this line to the context_processors in settings 'appname.context_processor.cart', but not getting out put on base.html templates template code {% with total_items=cart|length %} {% if cart|length > 0 %} Your cart: <a href="{% url 'cart_detail' %}"> {{ total_items }} item{{ total_items|pluralize }}, ${{ cart.get_total_price }} </a> {% else %} Your cart is empty. {% endif %} {% endwith %} -
Django channels page stuck on loading
I created a simple Django Channels consumer that connects to a Redis channel and receives some data from this channel, i want to send this data to the frontend. The consumer is able to connect to the consumer and receives the data; the problem is that if i try to load the page when the consumer is running, the page will be stuck on loading. I'm sure this happens because the connection to the Redis channel is a blocking operation, or it could be a problem with threads. I'm new to this concepts, so i decided to make a question for it. Here is my consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): self.send({ 'type': 'websocket.accept' }) self.receive(event) def receive(self, event): channel = 'TEST' params = urllib.parse.parse_qs(self.scope.get('query_string', b'').decode('utf-8')) pubsub = connection.pubsub(ignore_subscribe_messages=True) pubsub.subscribe(channel) for message in pubsub.listen(): # self.send({ # 'type': 'websocket.send', # 'text': message['data'], # }) print(message['data']) async def websocket_disconnect(self, event): redis_url = 'redis://localhost:6379/0' connection = redis.StrictRedis.from_url(redis_url, decode_responses=True) channel = 'TEST' pubsub = connection.pubsub(ignore_subscribe_messages=True) pubsub.unsubscribe(channel) print('DISCONNECTED!') So what happens is that i can see the data being printed to my console, but if i try to leave that page and reach a different part of my site, the page will get … -
Django is searching the URL in the wrong application
My application is currently using a external app supplied URLs . I decided to override some of their views , this however resulted in the issue whereby django is searching for the URL in the wrong directory. Heres some of my code to explain the problem : url.py(not the root config , however its in my main app) urlpatterns = [ path('pipeline/<process_pk>/documents/<task_pk>/assign/', #<---- this is the URL and view that i overrode OverrideTaskView.as_view(), {'flow_class': Pipeline, 'flow_task': Pipeline.documents}, name="pipeline:{}__assign".format(Pipeline.documents.name)), path('pipeline/', include((pipeline_urls,'pipeline'))), #<--- this is the app-supplied URLs views.py class OverrideTaskView(CoreAssignTaskView,FormView): #<--- im inheritting the view from the third party app form_class=AssignForm action_name = 'assign' def post(self, request, *args, **kwargs): if '_assign' or '_continue' in request.POST: self.activation.assign(self.request.user) return HttpResponseRedirect(self.get_success_url()) #<---- this is where it calls the faulty code else: return self.get(request, *args, **kwargs) def get_success_url(self): #<--- in this get success url the self.request.resolver is returning the wrong value """Continue on task or redirect back to task list.""" url = self.activation.flow_task.get_task_url( self.activation.task, url_type='guess', user=self.request.user, namespace=self.request.resolver_match.namespace + ':' + 'pipeline') back = self.request.GET.get('back', None) if back and not is_safe_url(url=back, allowed_hosts={self.request.get_host()}): back = '/' if '_continue' in self.request.POST and back: url = "{}?back={}".format(url, urlquote(back)) elif back: url = back return url The piece of code … -
Помогите пожалуйста , не могу понять Django rest_framework
После удаления объекта User , выводится только id , как вывести все филды данного обяекта id = serializers.PrimaryKeyRelatedField(queryset=CommunicationObject.objects.all(), many=True) def delete_many(self): for i in self.validated_data['id']: i.delete() -
Django view as API with Get method save twice records from Firefox
I made a simple view for searching one product in my ecommerce website.. The view (an API) wait a GET parameter (as http://example.com/search/12345) after I would like to save the searched parameter (with a create queryset) in a specific model for obtain search history. But if I call the view/api from last Firefox version, I get two records in database, from Edge only one. Deepening the topic the problem is the idempotency expected from HTTP RFC on Get method. Some browsers can do more than one request... I need to preserve GET method for search api but I need saving the searched string. What I can use GET parameter for searching and SAVE it in database only one? without CSRF/Cookie/User-Agent? P.S. I don't post code because it is needless. -
Password reset confirm not work in Rest-Auth
I use rest-auth for backend with django rest framework. In urls: path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls'))-at when I access to http://localhost:8000/rest-auth/password/reset/ I get an email field. After providing email, I get NoReverseMatch at /rest-auth/password/reset/. Mainly, Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. How can I fix this?? I tried in urls: from rest_auth.views import PasswordResetConfirmView url(r'^rest-auth/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm') Now I get an email and when I go to the link I get four field (New password1, New password2, Uid, Token) but (Uid and Token field are empty). How can I get this 2 field (Uid and Token) filled with url's Uid and Token?? -
Django Not letting save Time in Hour:Minute formate
I am trying to save time in this formate '13:21' . but django not letting me to do so and giving this exception ["'13 : 53' value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."] my field is duration = models.TimeField(null=True , blank=True) my setting.py is TIME_INPUT_FORMATS = ('%H:%M',) -
best way to integrate Vue.js to Django application in production
i have a Django application in production hosted using digital ocean, the project is huge and has been live for 4 months now, i need to a add a few frond end features to one of the site pages using Vue.js but i am still wondering on which way is better to integrate vue.js and vuetify, which is the best method, using the cdn link or a webpack installation? -
How do i upload a image from user side to media folder from views and models in django? [closed]
my views.py file from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect from mcatagory.models import sub_catagory, product from PIL import Image # Create your views here. def addproduct(request): scat = sub_catagory.objects.all() # scat = sub_catagory.objects.raw( # 'SELECT id FROM mcatagory_sub_catagory WHERE catagory_id_id=%s',[sub_catagory]) added = False if request.method == 'POST': p_name = request.POST.get("p_name") p_price = request.POST.get("p_price") p_desc = request.POST.get("p_desc") img = request.POST.get("image") s_cat = request.POST.get("s_cat_id") status = 0 data = product(p_name=p_name,p_price=p_price, p_desc=p_desc, image=img, sub_catagory_id=s_cat, status=status) data.save() added = True print("Thai Gayu !!!") return render(request, 'customer/rentproduct.html', {'sub_catagory': scat, 'added': added}) else: return render(request, 'customer/rentproduct.html', {'sub_catagory': scat})