Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Django App to RDS database using AWS ElasticBeanStalk
I am using eb deploy to try and load a Django application and connect it to an RDS database. Within settings I have the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } And I have all these set within the Environment's Configuration > Software > Environment Properties. The RDS database exists and is available. I have added the Enviornments Instances Security Groups to the RDS database. I am getting the following error when I try to deploy. Traceback (most recent call last): File "./src/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor self.ensure_connection() File "/opt/python/run/venv/local/lib64/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection … -
how to run a function from a link withing popup modal bootstrap
I have a django project that includes a popup modal where the modal has tabs as links one of these tabs once the user clicked it must perform a function and retrieve data from the database. The problem is that once the user clicked the tab nothing happen as is the function isn't initialize. urls.py path("events/<int:id>/", getEvents, name = "getEvents"), views.py def getEvents(request,id): q1 = cursor.execute('SELECT Person_.ID FROM Person_ WHERE Person_.ID = {0}'.format(id)) print('q1==>',q1) qresult = q1.fetchone() print("qresult==>",qresult) print("query is not empty!") eventQ = cursor.execute('SELECT Person_.ID, Person_.Full_Name, Events.ID, Events.Event_Title, Events.Event_Details, Links.document_id from Person_, Events, Links where ( Person_.ID = {0}) and (Person_.ID = Links.A_Person or Person_.ID = Links.B_Person) and (Events.ID = Links.A_Event or Events.ID = Links.B_Event) ORDER BY Events.ID DESC '.format(id)) resultEvents = eventQ.fetchall() return render(request,'pictureCard.html',{ "resultEvents":resultEvents, "qresult":qresult, }) pictureCrads.html <!-- Popup Modal --> {% for obj in object_list %} <div id="popModel{{obj.0}}" class="modal fade modal-rtl" role="dialog"> <div class="modal-dialog modal-lg"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header Modal-Pic"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">{{ obj.1 }}</h4> <a href="{% static 'img/logo_title/icon-AddressBar.png' %}" data-toggle="modal" data-target="#test2"><img src="{% static '/img/card/1.png'%}"/></a> </div> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact{{ obj.0 }}" role="tab" aria-controls="contact" aria-selected="false">contact us</a> </li> <li class="nav-item"> <a class="nav-link" id="event-tab" … -
What does <int:question_id> do?
I am learning Django and there's an expression in code "int:question_id" which I'm not getting. from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] -
Name 'x' is not defined
Im having a problem when I try to migrate this shows up. mysite\profesores\admin.py", line 18, in admin.site.register(Profesor, ProfesorAdmin) NameError: name 'ProfesorAdmin' is not defined admin.py # -*- coding: utf-8 -*- from django.contrib import admin from profesores.models import Profesor # Register your models here. class Profesor(admin.ModelAdmin): list_display = ('nombre', 'apellido', 'nacionalidad', 'especialidad') list_filter = ('fecha_publicacion',) date_hierarchy = 'fecha_publicacion' ordering = ('-fecha_publicacion',) class Trainer(admin.ModelAdmin): list_display = ('nombre', 'apellido', 'nacionalidad') list_filter = ('nombre',) date_hierarchy = 'nombre' ordering = ('nombre',) admin.site.register(Profesor, ProfesorAdmin) admin.site.register(Trainer, TrainerAdmin) models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Profesor(models.Model): nombre = models.CharField(max_length=30) apellido = models.CharField(max_length=40) nacionalidad = models.CharField(max_length=25) especialidad = models.CharField(max_length=60) class Meta: ordering = ["nombre"] verbose_name_plural = "Profesores" def __unicode__(self): return '%s %s' % (self.nombre, self.apellidos) class Trainer(models.Model): nombre = models.CharField(max_length=40) apellidos = models.CharField(max_length=40) nacionalidad = models.CharField(max_length=40) class Meta: verbose_name_plural = "Trainers" def __unicode__(self): return '%s %s' % (self.nombre, self.apellidos) -
Django Rest Framework - Automatically create new model B instance each and every time new model A instance is created
As said in the title. I want my django rest framework to create new model B object instance - with foreign key to model A , each and every time new model A object instance is created, so that they have foreign key relation. Currently i use ViewSets. Thanks for help in advance. -
Save two model instances in one updateview
Am trying to update the User model and UserProfile model in one view but it's not working. No error is shown and no changes are made to the objects. What am I not doing right. Here is my models.py: class UserProfile(models.Model): """User information not related to authentication""" user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE) age = models.IntegerField() # other fields ignored Here is my serializer.py: class UserSerializer(ModelSerializer): first_name = CharField(max_length=20) last_name = CharField(max_length=20) email = EmailField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) username = CharField(max_length=32,validators=[UniqueValidator(queryset=User.objects.all())]) password = CharField(min_length=8, write_only=True) confirm_password = CharField(write_only=True) def create(self, validated_data): user = User.objects.create_user( validated_data['username'], email = validated_data['email'], first_name = validated_data['first_name'], last_name = validated_data['last_name'] ) password = validated_data['password'] confirm_password = validated_data['confirm_password'] if password != confirm_password: raise ValidationError({'password': 'Passwords must match'}) else: user.set_password(password) user.save() return user class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'confirm_password') class UserProfileSerializer(ModelSerializer): username = CharField(source='user.username') first_name = CharField(source='user.first_name') last_name = CharField(source='user.last_name') email = CharField(source='user.email') class Meta: model = UserProfile exclude = ('user',) # fields = '__all__' # depth = 1 def update(self, instance, validated_data): user = instance.user instance.user.username = validated_data.get('username', instance.user.username) instance.user.email = validated_data.get('email', instance.user.email) instance.user.first_name = validated_data.get('first_name', instance.user.first_name) instance.user.last_name = validated_data.get('last_name', instance.user.last_name) instance.save() # user.save() return instance Here is view.py: class UserProfileUpdate(UpdateAPIView): queryset = … -
Render ajax post to HTML in Django
I am writing an page that with a form of several inputs wrapped in selectize.js on the top. By clicking a button, I wish to return some queries info based on inputs. I am using ajax to post inputs to avoid page reloading. I am following DJANGO render new result values from AJAX request to HTML page to render the queried result cat_result based on ajax post data in HTML. def cat_select(request): cat_result=[] cat_selected=[] cat_name=['l2','l3'] cat_selected=list(map(lambda x:request.POST.get(x, '').split(','), cat_name)) cat_result=c_result(["US"],cat_selected) #list of tuples I want to get print(cat_selected) print(cat_result) html=render_to_string('esearch/result.html', {'cat_result': cat_result},request) return JsonResponse({'cat':cat_result,'html':html},safe=False) This is the function that works with the main base.html that works for data input, which result.html extend from. def search_index(request): ##something to populate input options for l2 and l3 print(results) context = {'l2':l2, 'l3':l3} return render(request, 'esearch/base.html', context) base.html <form id="cat_select">{% csrf_token %} <input class="site" name="site" type="text"> <input class="l2" name="l2" id="l2" type="text" style="width:30%"> <input class="l3" name="l3" id="l3" type="text" style="width:50%"> <br> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="cat_submit">Submit</button> </form> <script type="text/javascript"> $(document).on('submit','#cat_select',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/cat_select', data:{ l2:$('#l2').val(), l3:$('#l3').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(){ alert ("selected!") } }); }); </script> result.html {% extends "esearch/base.html" %} {% block title %} Result {% endblock %} {% block content … -
i want to insert data in a new model after calling is through a post method , how do in do that when a i call it through the template?
models.py from django.db import models class booking(models.Model): fname=models.CharField( max_length=50) lname=models.CharField( max_length=50) email=models.EmailField(max_length=254) city=models.CharField(max_length=50) state=models.CharField(max_length=50) pin=models.IntegerField() def __str__(self): return self.fname class approved(models.Model): fname=models.CharField( max_length=50) lname=models.CharField( max_length=50) email=models.EmailField(max_length=254) city=models.CharField(max_length=50) state=models.CharField(max_length=50) pin=models.IntegerField() def __str__(self): return self.fname views.py def adminp(request): if 'form_rejected' in request.POST and request.method=="POST": print("Went into reject") p=booking.objects.filter(id=request.POST.get('object_id','')).delete() print(p) elif 'form_approved' in request.POST and request.method=="POST": print("went in approve") fname= booking.objects.filter(fname=request.POST.get('object_fname','')).values_list('fname') lname= booking.objects.filter(lname=request.POST.get('object_lname','')).values_list('lname') email= booking.objects.filter(email=request.POST.get('object_email','')).values_list('email') city= booking.objects.filter(city=request.POST.get('object_city','')).values_list('city') state= booking.objects.filter(state=request.POST.get('object_state','')).values_list('state') pin= booking.objects.filter(pin=request.POST.get('object_pin','')).values_list('pin') app= approved(fname=fname,lname=lname,email=email,city=city,state=state,pin=pin) app.save() print(fname,pin) x=booking.objects.all() params={'pro': x} return render(request,'dbms/adminpanel.html',params) template <form action="" method="POST"> {% csrf_token %} <div class="col"><p>Firstname: {{i.fname}}</p></div> <div class="col"><p>Lastname: {{i.lname}}</p></div> <div class="col"><p>Email: {{i.email}}</p></div> <div class="col"><p>City: {{i.city}}</p></div> <div class="col"><p>Pin: {{i.pin}}</p></div> <input type="hidden" name="object_fname" value="{{ i.fname }}"> <input type="hidden" name="object_lname" value="{{ i.lname }}"> <input type="hidden" name="object_email" value="{{ i.email }}"> <input type="hidden" name="object_city" value="{{ i.city }}"> <input type="hidden" name="object_state" value="{{ i.state }}"> <input type="hidden" name="object_pin" value="{{ i.pin }}"> <input class="btn btn-success mx-2" name="form_approved" type="submit" value="Approve"> <input type="hidden" name="object_id" value="{{ i.id }}"> <input class="btn btn-danger mx-2" name="form_rejected" type="submit" value="Reject"> <!--Added attribute name="form_rejected"--> OUTPUT after printing output of fname and pin: went in approve <QuerySet [('snaTYE',)]> <QuerySet [(939393,)]> when I print fname just to check it gives me a queryset which can't be inserted, so how do either insert the following in approved database or … -
NoReverseMatch in url pattern-data is in tuple form
django url pattern not recognized due to tuple entry i want to put a hyperlink in html code to redirect to a page with sending a data with it. hyperlink path is dynamic so i used {% url "check" book.id %} in html code. book.id gives correct data but it appers in tuple format ('12',) when i call perticular page by writing static url like http://127.0.0.1:8000/check/12/ it works fine "check" as view area and 12 as argument passed how to use a dynamic path views.py def add(request): book = Readdata.objects.all() return render(request, 'result.html', {'books': book}) def check(request,id): return render(request,'result.html',{'result': id}) urls.py urlpatterns = [ url('add', views.add, name='add'), url(r'^check/(\d+)/$', views.check, name="delete_book"), url(r'^check', views.check, name="check"), url('', views.index, name="index") ] html <a href="{% url 'check' book.age %}">click </a> not working <a href="http://127.0.0.1:8000/check/21/">click </a> working error- Reverse for 'check' with arguments '(21,)' not found. 1 pattern(s) tried: ['check'] -
Logging cron jobs in Django
I would like to log all cron job errors into a database table. Is it a good idea to log errors into a db table and what would you suggest me to do? Is it possible to do it with built-in logging module? P.s. I am using python 2.7 and django 1.11 (Yea, I know I should migrate to Py3 and Django 2 :D) -
How to build full url of object in django template using `obj.get_absolute_url'?
I am trying to feed "sharethis" data-url with the full url (domain + absolute_url) of the object. Currently, I am doing this in django template: <div class="sharethis-inline-share-buttons" data-url="http://www.my-domain.com{{program.get_absolute_url}}"></div> However, I want a better method to get this part: http://www.my-domain.com The reason I am looking for this is that the first method does not return a relevant url in development using localhost. it would return, as an example, this (fictional) url: http://www.my-domain.com/objects/object_slug-object_pk/ while I expect this: 127.0.0.1.com:8000/objects/object_slug-object_pk/ -
Как реализовать посекундное обновление страницы в django
Мне нужно реализовать посекундное обновление страницы, для обновления графика, без подтверждения пользователем. Есть идеи? Что я имею: все встало на моменте рекурсии, решил реализовать пока что проверку посекундного обновления. Ранее сталкивался с проблемой рекурсии тэмплейтов, но успешно нашел обходной путь, но сейчас, к сожалению не вижу его. Изначально пытался реализовать на js, но там спрашивают подтверждение обновления страницы, что при отрисовке графика каждую секунду меня не устраивает. Да можно было воспользоваться более сложными графиками, а не google charts, но это тоже меня не устраивает, так как мой уровень знания js не очень то хорош. PYTHON from django.shortcuts import render from django.views.generic.edit import FormView from django.contrib.auth.forms import UserCreationForm from django.shortcuts import redirect from django.http import HttpResponseRedirect from django.urls import reverse from .models import Profile from .models import Profile2 from .forms import forma from .forms import forma0 from math import sqrt import time ... def ac1 (request,category): # материнская функция к timerecus понадобиться дальше idc=decode(category) pf= Profile2.objects.get(id=idc) time=0 timerecus(request,time) ... def timerecus(request,timer): time.sleep(1) if(timer<=60): timer=timer+1 return HttpResponseRedirect(reverse('timerecus',args=(request,timer))) return render(request,'ac1.html',context={'num':timer}) HTML <meta charset="utf-8" /> <title>lichkab</title> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['time', 'action'], ['1', 378.280], ['2', 378.260], ['3', 378.320], ['4', 378.320] ]); var … -
User Password Automatically changes in django after 15 days
I am facing a serious issue in production, that password of users table is automatically changes after 15 days or probably 2 weeks we are using:- server:- AWS server EC2 instance database:- MYSql Usertable :- Django auth table please look into this on priority -
Type error when trying to run django app on localhost
I am trying to deploy a Django app to heroku. I was able to successfully run the app on my local and I did several steps to migrate and run to heroku. After which I ran into this error when I try to run it in local and the application failed to run on Heroku. I am actually not able to determine where the problem is, is it the last line which says about str expected not function call. I am sharing the screenshot for my error. -
Django - collectstatic using incorrect declaration of STATIC_ROOT
my declaration of STATIC_ROOT doesn't seem to be used when I execute the command collectstatic: Printing from the terminal I get the correct path: STATIC_ROOT: [..]/Dev/bidding_tool_project/project/staticfiles from the python console: settings.STATIC_ROOT: Dev/staticfiles Would you have any idea how/why this happens ? -
how to retrieve data from database using raw SQL not django ORM
I have a django project that is connected to SQL server database and when i tried to click button to retrieve data from the database the system crash . i am trying to convert the below syntax in ORM into raw sql: dbEntry = Person_.objects.get(pk =pk) Note : I am not using ORM once i tried to perform the task the system crash and display: getEvents() got unexpected keyword argument "id" urls.py path("events/<int:id>/",getEvents,name = "getEvents"), views.py def getEvents(request,pid): q1 = cuesor.execute("Select Person_.ID FROM Person_ WHERE ID = pid") print("q1=",q1) qresult = q1.fetchone() print("qresult",qresult) return render(request,"connect.html",{"qresult":qresult}) list.html <form method = "GET" action = "{% url 'getEvents' obj.0 %}"# obj is the iterator --- 0 is the first field in the table == ID <button class = "btn btn-primary">get details</button> </form> display.html {% for row in qresult %} <p> {{ row.0 }} </p> {% endfor %} -
save user instance to another model after post_save django
i have to two models CustomUser and artist and what i am trying to achieve that when i create user it should automatically create artist. i don't want to add OneToOne field in artist model i just want to fill these field name, artist_category, artist_image, bio with post_save when CustomUser created. custom user model class CustomUser(AbstractBaseUser, PermissionsMixin): artist_choice = [ (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ] artist_category = models.IntegerField(choices=artist_choice, null=True) mobile_number = PhoneNumberField(null=True) city = models.CharField(blank=True, max_length=50) bio = models.TextField(blank=True) email = models.EmailField(max_length=100, unique=True) name = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) last_login=models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) country = CountryField() USERNAME_FIELD = 'email' EMAIL_FIELD='email' REQUIRED_FIELDS=[] objects=UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) name = models.CharField(max_length=100) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return self.name -
returning "non_field_errors": in Postman
There is validation in StorySerializer, which works fine. In Postman during creating story with 3+ genres it returns { "non_field_errors": [ "Max genres: 2" ] } class StorySerializer(serializers.ModelSerializer): .... def validate(self, data): if len(data['genres']) > 2: raise ValidationError('Max genres: 2') return data Can I change non_field_errors to another name? -
How to add show password icon in django-bootstrap4 login form?
I'm designing the user interface of a login page using django-bootstrap4 form. I need some help on how to add a show password icon using font-awesome in the form field. I tried adding the addon_after parameter as said in the docs (https://django-bootstrap4.readthedocs.io/en/latest/templatetags.html) but the icon did not show up. Here is the snippet of my html template: <form method="post"> {% csrf_token %} {% bootstrap_form form addon_after='<span><i class="fas fa-eye-slash"></i></span>' %} <button class="btn btn-success ml-0" type="submit">Sign In</button> <div><a href="{% url 'password_reset' %}">Forgot password?</a></div> </form> -
Django Found another file with destination path
I am trying to deploy the app on GCP but when I run the following command: python manage.py collectstatic It returns: Found another file with the destination path 'admin\css\autocomplete.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin\css\base.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. And many other like this. Here's my Settings.py STATIC_URL = 'https://storage.googleapis.com/yantra-packs/static/' # STATIC_URL = '/static/' # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/'), ] Where is it that I am providing two paths for the static files? -
How to specify the login_url to login for django generic views
login_required decorator directly taking url from settings.LOGIN_URL. In which how can i specify login url with parameter login_url. Is this possible to specify both login_url and TemplateView.as_view() in login_required decorator urlpatterns = [ url(r'^$', login_required(TemplateView.as_view(template_name='foo_index.html')) ] -
two forloop inside in one table row
I have 2 loops from views which is generates in my table. <tr style='height:19px;'> <th id="703183278R33" style="height: 19px;" class="row-headers-background"> <div class="row-header-wrapper" style="line-height: 19px;">34</div> </th> <td class="s46"></td> <td class="s51" colspan="3">Subject</td> <td class="s51" colspan="4">Teacher</td> <td class="s51" colspan="6">Room and Schedule</td> <td class="s0"></td> </tr> {% for sensie in teacher %} <tr style='height:19px;'> <th id="703183278R34" style="height: 19px;" class="row-headers-background"> <div class="row-header-wrapper" style="line-height: 19px;">35</div> </th> <td class="s46"></td> <td class="s51" colspan="3">{{sensie.Subjects}}</td> <td class="s51" colspan="4">{{sensie.Employee_Users}}</td> {% endfor %} {% for room in roomsched %} <td class="s51" colspan="6">{{room.Classroom}}-{{room.Day_Name}}</td> </tr> {% endfor %} how do i make it so that it gets formatted in table properly? just like this Subject Teacher Room and Schedule math example-Teacher room1-mwf -
I want to do different actions on clicking different buttons, the code i have written is not working?
#Template# <form action="" method="POST"> {% csrf_token %} <div class="col"><p>Firstname: {{i.fname}}</p></div> <div class="col"><p>Lastname: {{i.lname}}</p></div> <div class="col"><p>Email: {{i.email}}</p></div> <div class="col"><p>City: {{i.city}}</p></div> <div class="col"><p>Pin: {{i.pin}}</p></div> {% csrf_token %} <input type="hidden" name="Approve" value="{{ i.fname }}"> <input class="btn btn-success mx-2" type="submit" value="Approve"> <input type="hidden" name="Reject" value="{{ i.id }}"> <input class="btn btn-danger mx-2" type="submit" value="Reject"> </form> #Views.py# def adminp(request): if 'Reject' in request.POST and request.method=="POST": print("Went into reject") p=booking.objects.filter(id=request.POST.get('Reject','')).delete() elif 'Approve' in request.POST and request.POST.method=="POST": print("went into approve") x=booking.objects.all() print(x) params={'pro': x} return render(request,'dbms/adminpanel.html',params) How do i resolve the above code? In views.py always the request goes in reject itself also onclicking approve ,help please. -
What libraries should I use to develop custom shopping malls with 'react' and 'react native'?
I'm studying 'Django', 'React' and 'React-Native'. I want to develop a custom shopping mall with my personal portfolio. ex) spreadshirt https://www.spreadshirt.com/create-your-own The features I want to develop are: Image overlay Text overlay Color change Save and edit your history Because I'm studying 'React' and 'React-Native', I want to develop using 'React' and 'React-Native'. What libraries should I use to develop custom shopping malls with 'react' and 'react native'? -
Call a method for each model linstance
I have a Category model. I want to make a directory for the category everytime I create a new category. I have a method in my model called create_directory. class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() slug = models.SlugField(max_length=200, unique=True, default=1) def create_directory(self): gallery_path = os.path.abspath( os.path.join(settings.MEDIA_ROOT, Category.slug)) if not os.path.isdir(gallery_path): os.mkdir(gallery_path) class Meta: verbose_name_plural = "Categories" unique_together = ("category_title", "slug") def __str__(self): return self.category_title I want to call create_directory each time I create a category in the Admin panel.