Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display/render User's name stored in an external model without refreshing the page?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) I was reading … -
Django-models - display object in Django admin by FK description
I'm using the following models in Django: Model 1 class Location(models.Model): GID = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) fAccountGID = models.ForeignKey( Account, on_delete=models.CASCADE, verbose_name='Account code') MainDescription = models.CharField( verbose_name='Description/title', max_length=100) ... def __str__(self): return self.MainDescription Model 2 class Review(models.Model): Code = models.AutoField(primary_key=True) fLocationGID = models.ForeignKey( 'Location', on_delete=models.CASCADE, verbose_name='Location') ... def __str__(self): return 'Review for ' + self.FirstName When a review is saved in my database, in Django admin it is displayed as 'Review for ' + the FirstName: What would be the approach if I would like to display as 'Review for ' + 'MainDescription' from the Location model? Thanks -
django inlinecss not loading css file correctly
I'm using django-inlinecss to style emails. Here's a snippet of my email template: {% extends "base/email.html" %} {% block content %} {% load inlinecss %} {% inlinecss "base/css/email.css" %} <p class="c-c-test">test</p> {% endinlinecss %} {% endblock %} When rendering the template, an error occurs saying: No such file or directory: '/usr/src/project/static/base/css/email.css' Although, trying to use the same css file path (i.e. "base/css/emails.css") with static template tag works fine. What am I doing wrong here? -
Url filtering in Django Rest Framework
I created a Django Rest Framework API endpoint. Here is the view i created for my api endpoint: class myApiList(generics.ListCreateAPIView): queryset = tst.objects.using.all() serializer_class = mySerializer filter_backends = [DjangoFilterBackend] filterset_fields = ('Status',) This code lets me add filters when retrieving data from the API endpoint using Jquery on a standard webpage. So, if on my page i want to show only the records with the status Free i will retrieve this endpoint: ("/myApi/?Status=Free") But what if i want to show not only the items with the status Free, but also those with the status Pending? I tried this, but it's not working, as it will only show the records with the status Pending ("/myApi/?Status=Free&Status=Pending") Is there a way to solve this? Should i change something in the URL or do i have to make some changes from my Django Backend? -
Is there any way to change the sorting in a django admin autocomplete field?
I have one model CompletedDiscipline and this model has a FK term_year. I'm trying to modify the ordering of this field, I don't want to use ordering in class_meta I tried to use formfield_for_foreignkey, it worked out in parts because autocomplete_fields doesn't let this method work well, is there any way to make it work? or override sorting within autocomplete def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'term_year': kwargs['queryset'] = TermYear.objects.order_by('term__course_offer__course__nome', 'year', 'number', 'term__name') return super().formfield_for_foreignkey(db_field, request, **kwargs) autocomplete_fields = [ 'student_curriculum', 'discipline', 'term_year', 'teacher', ] -
How to intialize form value to its previously submitted value in Django after pressing submit button?
I dont want to reset my form values after submitting through GET method. I want to put the same value as previous submitted value. -
Django can't import external libraries
So I am using Django version 2.26, and Python 3.7.3. Whenever I try to import or include an external library in my app within my project (specifically background_task in this case, but this error works with celery and a lot of others), it says 'no module named' even though it is installed. And when I run the Django shell and import it works. My settings.py file looks like this: 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/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # removed here # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ '*', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'background_task', 'projects', 'blog', 'landingpage', 'workspace', ] 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 = 'portfolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["portfolio/templates/"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'portfolio.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, … -
How do I correct the following code in django, It's give an error "Forbidden (CSRF token missing or incorrect.)"
<script> var CSRF_TOKEN = '{{ csrf_token }}'; function getQuestion(str) { if(str!="select subject") { var req=new XMLHttpRequest(); req.open("post","/addQuestion/",true); str=encodeURIComponent(str); req.setRequestHeader("Content-type","application/x-www-form-urlencoded"); req.send("subject="+str); req.onreadystatechange=function() { if(req.status==200 && req.readyState==4) { document.getElementById("formdiv").innerHTML=req.responseText; document.getElementById("formdiv").style.overflowY="scroll"; } } } } </script> -
How to find the exact path requesting a Django api?
I want to get one single user of an user list by his id, to get his detail information. When I want to get the user list it works out fine. I have this path of the api docs: http://123//users/ and I can retrieve the list with this function in my front-end: private url = 'http://123'; // simplified for question ... // get a list of users getList(): Observable<any> { return this.http.get(`${this.url}/users`); } When it comes to get one user I have this path of the api docs: http://123//users/{id}/ while id is an integer. But when I want to get the user with this function: // get a user's profile getUserDetails(id): Observable<any> { return this.http.get(`${this.url}/users/${id}/`); } I get an 404 error and that the details were not found. Would the path in my function be correct to fetch the api data? Or am I doing something wrong? The strange thing is that it works with the list but not with one user, although I'm using the same scheme. -
How to display django category name instead of Category object (1)
Here is the problem. I've added a category section into my django blog. When I'm trying to add new category, there is a problem with user localization. When I'm adding the category, for example django, it shows like this: image 1 in the admin panel the same: image 2 but I actually add a normal category name: image 3 The funny thing is that, after I posted content with category in my web-app, it's looking normally: image 4 I want something like this, maybe someone have solution: wanted result Some code: models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='posts') image = models.ImageField(upload_to='images', default="images/None/no-img.jpg") def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=20) views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Post from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView def home(request): content = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', content) def blog_category(request, category): posts = Post.objects.filter(categories__name__contains=category).order_by('-date_posted') content = { 'category': category, 'posts': posts } return … -
Verify django loaddata progress
I'm trying to migrate from sqlite to a google managed postgres db. It worked locally with a postgres db that runs within docker, but when I try python manage.py loaddata db.json for the remote db the cursor just blinks forever but I don't know if something is happening. How can I verify that the process is doing something? I'm using cloud_sql_proxy to connect to the db. -
Is there a way to prompt the user for a value without refreshing the page from views.py in Django?
I'm currently attempting to modify a page that essentially keeps track of when a user enters/leaves an area. Currently all the logic works fine, but I would like to add the functionality to ask a user to enter their own estimate of the time they entered/left in the case they forgot to do so, since these instances get flagged upon submission. What I'm having trouble with, is actually getting the "popup" to display. I'm not sure how to accomplish this from the views.py, where I added the comment. I guess I need a way to just render that extra html on top of the page, without refreshing, until after they submit the edited_timestamp. I'm fairly new to Django/Python, and I have a very basic understanding of how this all works, so I apologize in advance if my suggestions on handling this are a bit off. These is a summarized version of what the models look like: models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) edited_timestamp = models.DateTimeField(null=True, blank=True) time_exceptions = models.CharField(max_length=2, blank=True) time_in = models.DateTimeField(help_text="Time in", null=True, blank=True) … -
Extremely slow queryset lookup in Django with mysql as backend DB
My view has a search bar, which searches extremely slowly. There are four tables that I'm trying to pull information from Restaurant, Food, Menu, Quality. The view sent a pk for food. I also have a local_zip and radius variable to find restaurant near a user. I use this to limit the number of restaurants. Then, I filter the objects by food selected and restaurants near them. Then I pull some quality info on the restaurants. When I run it in the shell, it's actually normal speed. No one line takes super long, not sure why it's so slow on the server. Here is the code that I runs very slowly: local_zip = request.session['local_zip'] radius = request.session['radius'] in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius(local_zip, radius)] list_ids = ['13', '427', '428'] #('ZIP', radius in miles) # Restaurants table has about 500 observations find_objects = Restaurants.objects.filter(Q(zipcode__in=in_radius) | Q(id__in=list_ids)).distinct() # Menu table is large with about a million observation objects_selected = Food.objects.filter(menu__menuid=pk) table = objects_selected.filter(restaurants__in=find_objects).order_by('price').prefetch_related('restaurants') #Food table has 10k objects food_info = Food.objects.filter(foodid=pk) # quality has about 600K objects quality_info = Quality.objects.filter(food__foodid=pk,locality = str(5))[:1] -
How to Set Multi-Select choices in admin django
I have a model class Event(models.Model): event_name = models.CharField(max_length=100, default="") event_organizer = models.ForeignKey(Organizer, on_delete=models.CASCADE) event_type = models.ForeignKey(Type, on_delete=models.CASCADE) event_city = models.ForeignKey(Citie, on_delete=models.CASCADE) event_tag = models.ForeignKey(Tag, on_delete=models.CASCADE) I have a field event_tag. During add event form in admin panel i want to select multiple tags. how to do that and how to save them -
unable to auto-fill data during update in dependent dropdowns
So I have been following this tutorial related to dependent dropdowns which can be found here and I seem to have gotten stuck at the last part the else if statement and am unable to implement the same in my project postlog models.py: from django.db import models # Create your models here. class FlightNum(models.Model): fl_no =models.CharField(max_length=5,primary_key=True) def __str__(self): return self.fl_no class Destination(models.Model): fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE,related_name='fl1') dest= models.CharField(max_length=15,blank=True) def __str__(self): return self.dest class Parking(models.Model): fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE,related_name='fl2') park_bay= models.CharField(max_length=3) def __str__(self): return self.park_bay class DepartureTime(models.Model): fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE,related_name='fl3') dep_time= models.CharField(max_length=9) def __str__(self): return self.dep_time class Flight(models.Model): fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE, primary_key=True, related_name='fl4') park_bay= models.ForeignKey(Parking, on_delete=models.CASCADE) dest= models.ForeignKey(Destination, on_delete=models.CASCADE) dep_time= models.ForeignKey(DepartureTime, on_delete=models.CASCADE) inbound= models.CharField(max_length=15,blank=True) airline= models.CharField(max_length=15) arr_time= models.TimeField() status models.py: from django.db import models from postlog.models import FlightNum,Destination,Parking,DepartureTime # Create your models here. class FlightStatus(models.Model): CLEANING_CHOICES = ( ('Yes', 'Yes'), ('No','No'), ) fl_no= models.OneToOneField(FlightNum,on_delete=models.CASCADE,related_name='fli_no',primary_key=True) park_bay= models.ForeignKey(Parking,on_delete=models.CASCADE,related_name='parki_bay') catering= models.CharField(max_length=9) fuel= models.IntegerField() pas_cnt= models.IntegerField() dest= models.ForeignKey(Destination,on_delete=models.CASCADE,related_name='desti',null=True) dep_time=models.ForeignKey(DepartureTime,on_delete=models.CASCADE,related_name='dept_time') Cleaning = models.CharField( max_length=3, choices=CLEANING_CHOICES) status forms.py: from django.forms import ModelForm from status.models import FlightStatus from postlog.models import FlightNum,Destination,Parking,DepartureTime class StatusForm(ModelForm): class Meta: model = FlightStatus fields = ('fl_no', 'park_bay', 'catering', 'fuel', 'pas_cnt', 'dest','dep_time', 'Cleaning') labels = { 'fl_no': ('Flight Number'), 'park_bay': ('Parking Bay'), 'catering': ('Catering'), 'fuel': ('Fuel'), 'pas_cnt': ('Passenger Count'), 'dest': … -
Extract the coordinates from the LineStringField
I've this simple model from GeoDjango for a line vector: from django.contrib.gis.db import models class LineBuffer(models.Model): geom = models.LineStringField() def __int__(self): return self.pk @property def coordinates(self): return str(self.geom.x) + ', ' + str(self.geom.y) I need to create a buffer using Turf.js; the results will be redered using MapBox. With this view I create my map: def line_mapbox_turf_buffer(request): geometry = LineBuffer.objects.all() context = { 'geometry': geometry, } template = 'buffer/reading/line_mapbox_turf_buffer.html' return render(request, template, context) I try to generate the GeoJSON var data_source = { "type": "FeatureCollection", "features": [{% for d in geometry %} { "type": "Feature", "properties": { "pk": "{{ d.pk }}" }, "geometry": { "type": "LineString", "coordinates": [{{ d.coordinates }}] } {% if forloop.last %}} {% else %}}, {% endif %}{% endfor %} ] } But I see this: { "type": "Feature", "properties": { "pk": "1" }, "geometry": { "type": "LineString", "coordinates": [ [14.364295, 14.3662612, 14.3681209, 14.3702697, 14.3730481, 14.3742791, 14.3763224], [40.8086793, 40.8101317, 40.8118721, 40.8139257, 40.8165981, 40.8177693, 40.8206666] ] } } Instead of this: { "type": "Feature", "properties": { "pk": "1" }, "geometry": { "type": "LineString", "coordinates": [ [14.364295,40.8086793], [14.3662612,40.8101317], [14.3681209,40.8118721], [14.3702697,40.8139257], [14.3730481,40.8165981], [14.3742791,40.8177693], [14.3763224,40.8206666] ] } } I think that my problem is the property coordinates. How I can extract … -
End an event at midnight with Python and Django
Guys, I'm working on a project on which Python 2.7 and Django 1.11.26 are used I need to make a change to a condition where events are discarded at the actual event starting time and make them discard at the end of the day (midnight) this is the line of code concerned: show_card = lambda card: card.item.start_datetime >= timezone.now() -
what does " get_object().highlighted " do , refferering GenericAPIView
class SnippetHighlight(generics.GenericAPIView): queryset = Snippet.objects.all() renderer_classes = [renderers.StaticHTMLRenderer] def get(self, request, *args, **kwargs): # snippet = self.get_object() return Response(self.get_object().highlighted) -
How do I look into Django based Database for Emails or phone Validation from Angular Front End
I am working on a project consist of Django and Angular Integration. I have created RestApi in Django and receiving Data in JSON format. I added Resgistration module in Angular in which **I want to add Validation for non repeating email and phone number which calls Django api and checks for the validation ** <-- how to do this :/ Django Model class Employee(models.Model): DESIGNATION = ( ('Admin', 'Admin'), ('PM', 'Project Manager'), ('TL', 'Team Leader'), ('Dev','Developer'), ('QA', 'Quality Analyst') ) employeeid = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_no = models.BigIntegerField(unique=True) date_of_birth = models.DateField() email = models.EmailField(unique=True) password = models.CharField(max_length=50) designation = models.CharField(max_length=50,choices=DESIGNATION, default='Dev') dept_id = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) Django URL from which Angular receive JSON response url(r'^employee/list/$', views.employee_list), url(r'^employee/details/(?P<pk>\d+)/$', views.employee_detail), -
i try to add new products but it shows following erroe :no such table: main.auth_user__old
I tried instaling latest django and latest sqlite but the error is not solved error: OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\bhand\PycharmProjects\website\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Users\bhand\PycharmProjects\website\venv\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\bhand\PycharmProjects\website', 'C:\Users\bhand\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\bhand\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\bhand\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\bhand\AppData\Local\Programs\Python\Python37-32', 'C:\Users\bhand\PycharmProjects\website\venv', 'C:\Users\bhand\PycharmProjects\website\venv\lib\site-packages', 'C:\Users\bhand\PycharmProjects\website\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg', 'C:\Users\bhand\PycharmProjects\website\venv\lib\site-packages\pip-19.0.3-py3.7.egg'] Server time: Fri, 8 Nov 2019 12:17:12 +0000 -
How to pass one django template with a 'for loop' into another one using 'include' statement?
I am working on FAQs page where questions and answers are passed to a template sections based on their categories. I would like to reduce amount of html and use section div as a template <div id="{{id}}"> <div class="h2">{{category}}</div> {% for q in faqs %} {% if q.category == '{{category}}' %} <ul class="collapsible"> <li> <div class="collapsible-header">{{q.question}}></div> <div class="collapsible-body"><span>{{q.answer}}</span></div> <div class="divider"></div> </li> </ul> {% endif %} {% endfor %} </div> My main html contains following code: {% with id='m_faq'%} {% with category='Methodology'%} {% include 'main/faqs_section.html' %} {% endwith %}{% endwith %} I am only able to pass variables id and category. Is there a way to the for loop as well? -
Image is not acting like a link
I have wrapped my <img> in the anchor tag but it isn't acting like a link. However the <p> is acting as a link. How do I get it so that I do not need the <p> tag to be there and the image to still work as the same link? There is currently no cursor change on hovering over the image <div class="container"> {% for item in page.client_images.all %} {% image item.image fill-150x150-c100 %} <a href="{{ item.caption }}"> <img src="{{ img.url }}" class="item" alt="{{ img.alt }}"> <p>{{ item.caption }}</p> </a> {% endfor %} </div> -
sorting and ordering in custom fields in Django admin and change_list
I'm trying to add a custom ordering in Django admin change_list. I made custom fields in django admin and ordering is not straight forward as those fields are custom made and is not directly accessible from Django models.py '''class abc(BaseParamsAdmin): # change_list_template = 'admin/logistics_admin/agent_performance_today_changelist.html' list_display = ['field_engineer', 'leads_assigned','leads_rescedule', 'leads_complete', 'leads_failed', 'current_lead', 'time_spent', 'reassign', 'route'] list_display_links = None list_filter = [ManagerListFilter, RegionAutoFilter] ordering = ('_field_engineer',) search_fields = ['name'] def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} response = super().changelist_view(request, extra_context) _cl = response.context_data['cl'] # additional data on the basis of fes on page qs = _cl.result_list._clone() self.get_fe_stats(qs) extra_context['title'] = 'Control Panel' return response def get_queryset(self, request): qs = super().get_queryset(request) qs = self._filter_base(request, qs) qs = self.orders_complete.annotate(_leads_completed=Count(order_status_id__in=Orders.STATUS_COMPLETE)) qs = qs.only("id","username","name","role_id","role__id") return qs def _filter_base(self, request, qs): is_superuser = request.user.is_superuser if not is_superuser: logistic_user = CustomUserAuthMapping.get_authenticated_user(request.user.id) if not logistic_user: raise Exception('No mapping found for this Manager..') if logistic_user.user.role.id == LogisticUtils.ROLE_SR_MANAGER: region_ids = UserRegion.get_users_for_region_manger_distinct(logistic_user.user.id,LogisticUtils.ROLE_SR_MANAGER) qs = qs.filter(user_region__region_id__in=region_ids,user_region__is_active=1).distinct() else: qs = qs.filter(manager=logistic_user.user) return qs def field_engineer(self, obj): #return obj.name # url_red = reverse('admin:fe_performance', args=(obj.id,)) # return format_html('<a href="{}">{}</a>&nbsp;', url_red, obj.name) url_red = ("%s?user=%s&created_at__gte=%s&created_at__lte=%s") % (reverse('admin:logistics_admin_ordershistoryfb_changelist'), obj.id,LogisticUtils.subtractDateOnly(30),LogisticUtils.getDateOnly()) return format_html('<a href="{}">{}</a>&nbsp;', url_red, obj.name) field_engineer.admin_order_field = '_field_engineer' def leads_assigned(self, obj): #return self.orders_assign.get(obj.id, 0) order_assign = OrdersHistory.objects.filter(assign_at__date=LogisticUtils.getDateOnly(), user_id=obj.id, … -
How to Handle Exception HTTP 400 | Django Rest Framework
I tried to remove the worksheet in Google docs file. I am using Pygsheets to perform this process. There's only one sheet in that file. So we can't remove the sheet. so it will throw the Error. How i handle it Separately. Below is i tried something. but its not working def deleteWorksheets(file_name=None, sheet_name=None): try: sheet = client.open(file_name) delete_worksheet = sheet.worksheet_by_title(sheet_name) sheet.del_worksheet(delete_worksheet) except urllib.error.HTTPError: print("You can't remove") Below error is shown. How to handle it Separately . <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/ returned "Invalid requests[0].deleteSheet: You can't remove all the sheets in a document."> -
How can I get the primary key of the last insered quote?
I have 2 views: display_quote and quote_create. def display_quote(request, pk): items_quote = Quote.objects.filter(pk=pk) items_quote_line = LineQuote.objects.all().filter(num_quote_id=pk) form = QuoteLineForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() total = 0 for item in items_quote_line: total = total + item.get_price() context = {'items_quote': items_quote, 'items_quote_line': items_quote_line, 'form': form, 'total':total } return render(request, 'quote/quote_display.html', context) def quote_create(request): form = QuoteForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return render(request, 'quote/quote_create.html', {'form': form}) After creating a quote, I want to redirect to "display_quote" (the quote creted). Error obtained: The view quote.views.quote_create didn't return an HttpResponse object. It returned None instead.