Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why dont return SerializerMethodField data in django rest framework datatables?
im using django rest framework datatables , i want to show all customers data on tables , but its only return price_per_gallon !? here's my code : models.py from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField class User(AbstractUser): phone_number = PhoneNumberField(unique=True,region="PS") def __str__(self): return self.username serializers.py from rest_framework import serializers from customers.models import Customer from orders.models import Order class CustomerSerializer(serializers.ModelSerializer): customer_name= serializers.SerializerMethodField() customer_PhoneNumber = serializers.SerializerMethodField() customer_lastOrderDate = serializers.SerializerMethodField() # customer_allsales = serializers.SerializerMethodField() def get_customer_name(self,obj): return obj.user.get_full_name() def get_customer_PhoneNumber(self,obj): return str(obj.user.phone_number) def get_customer_lastOrderDate(self,obj): if Order.objects.filter(madeBy=obj.user).exists(): return Order.objects.filter(madeBy=obj.user).latest('order_date').order_date else: return "theres no orders" class Meta: model = Customer fields = ['price_per_gallon','customer_name', 'customer_PhoneNumber', 'customer_lastOrderDate'] views.py for serializer from .serializers import CustomerSerializer from customers.models import Customer from rest_framework.decorators import api_view from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import generics from rest_framework.permissions import IsAdminUser class CustomerListView(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer # permission_classes = [IsAdminUser] table html : <table id="example" data-server-side="true" data-ajax="http://127.0.0.1:8000/customers/api/list/?format=datatables" class="table table-hover"> <thead> <tr> <th data-data="customer_name">#</th> <th data-data="customer_PhoneNumber" >الاسم</th> <th data-data="customer_lastOrderDate" >رقم الهاتف</th> <th data-data="price_per_gallon">مجموع المشتريات</th> </tr> </thead> </table> </div> </div> <script> $('#example').DataTable() </script> {% endblock %} error msg : error img any help ? ( dont read this its a dummy text because of validation on post it … -
External Swagger UI run on django Wagatil
I have swagger UI built on Flask, which works fine. However I want to access the documentation from a Django Wagtail application. I would imagine there is a straight forward way to do this from the swagger.json. I came across this but it's not too clear I then went to documentation hoping it would be clear. However there is no clarity about how this works with my external link. Any pointers how I can easily reference my Flask Swagger Docs will be helpful. -
Not Found: /manifest.json after merging the two django backend and react frontend
I tried merging the react-frontend and django-backend. I ran npm run build and got the build folder and set it up with django like this settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'noteitdown/build') ], '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', ], }, }, ] STATICFILES_DIR = [ os.path.join(BASE_DIR, 'noteitdown/build/static') ] urls.py (of the project folder) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('authapi/', include('authapi.urls')), path('',include("home.urls")), ] urls.py (of the home app that shall handle the request) urlpatterns = [ path('', views.home, name='home') ] views.py/home def home(request): return render(request, 'index.html') The error that I get when I run python manage.py runserver in the cmd is Not Found: /manifest.json and the error that is consoled out in the dev tools is main.40c1cf71.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. Please suggest me what should I do to handle this -
Read uploaded File in django function
I am uploading a file from the front end and trying to read it in the backend to do some data extraction from that. I have written the following code which is failing in all scenarios Views.py class UserInfo(View): template_name = "Recruit/recruit.html" def get(self, request): user = UserInformationFrom() return render(request, self.template_name, {"form": user}) def post(self, request): user = UserInformationFrom(request.POST, request.FILES) output = dict() HTMLExtensionList = ['.html','.htm'] if user.is_valid(): savedUser = user.save() filename = user['file'].data.name name, extension = os.path.splitext(filename) if extension.lower() in HTMLExtensionList: output = readHTML(filename=user['file'].data) savedUser.email = output['Email'] savedUser.mobile = output['Phone'] savedUser.Zipcode = output['zipCode'] savedUser.state = output['state'] savedUser.upload_by = request.user savedUser.updated = timezone.now() savedUser.save() return render(request, self.template_name, {"form": user}) else: return render(request, self.template_name, {"form": user}) DataExtract.py def readHTML(filename): with open(filename, "r", encoding='utf-8') as file: soup = BeautifulSoup(file) for data in soup(['style', 'script']): data.decompose() var = ' '.join(soup.stripped_strings) email = ExtractEmail(var) phone = findPhone(var) zipCode = extractZipCode(var) state = extractState(var) return {"Email": email, "Phone": phone, "zipCode": zipCode, "state": state} I am getting the following error expected str, bytes or os.PathLike object, not InMemoryUploadedFile I am getting errors in DataExtract where I am trying to open the file. I tried this solution still not working expected str, bytes or os.PathLike object, not … -
deploying django to heroku :page not found error
I have been making a django app, and am now trying to deploy it to heroku. However when I go on it,says page not found the resources not found on the server and i am trying it on different app error remains same Here is my settings.py (at learst the relevant parts, but please ask if you would like the rest): """ Django settings for django_deployment project. Generated by 'django-admin startproject' using Django 4.0.2. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os import django_heroku import dj_database_url from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['django-deployment85.herokuapp.com','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] 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', "whitenoise.middleware.WhiteNoiseMiddleware", ] ROOT_URLCONF = 'django_deployment.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
django custom tag to pass a certain field into a filter
I am using django-simple-history to record changes to a model, I've written a bunch of custom methods for the model to extract the latest change date from the history, one for each field I'm interested in but it's a lot of duplication and really not at all DRY. It seems to me that I should be able to simplify this using a custom tag and passing the field that I want but I can't seem to get it to work. customtags.py: from django import template register = template.Library() @register.simple_tag def get_latest_record(issue, field): record = issue.history.filter(field = 1).most_recent return record in my template: {% get_latest_record issue 'name_of_field' %} -
Django Change all other Boolean fields except one
I have a model which has a boolean field: class Library(SocialLinksModelMixin): """ Represents book shelves and places where people have / leave books. """ user = models.ForeignKey(...) is_main = models.BooleanField(default=False) User can have multiple Libraries and I would like to allow setting the main one to ease the flow in the app. What is the easiest way for switching only one Library is_main to True and all others to False (There is always only 1 Library for a user that is main) I'm thinking about querying for all libraries and updating each and every one. Maybe there is another way to do that functionality? -
Rendering items in a multipage django web application
I am trying to make two pages with items that can be added/edited/deleted from the admin panel. I have 2 pages which are Store and School Uniform. The issue is that when I am adding to the cart the items from the School Uniform page, the cart shows items from the store page. A similar thing happens when I am viewing details of the items on the School Uniform page. The detail view shows items from the store page. I think that the problem is in the id of items, but I don't know how to fix it. The full project source code: https://github.com/MARVLIN/Eshop.git The repository is called Eshop views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def school_uniform(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] product2 = SchoolUniform.objects.all() context = {'products': product2, 'cartItems': cartItems} return render(request, 'store/school_uniform.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = … -
Django - How to render a form field as a table with only some of the items that match a specific criteria?
I have this form: forms.py from django.forms.models import ModelForm from .models import Order class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' From this model: models.py from django.db import models from django_countries.fields import CountryField from django.core.validators import MaxValueValidator class Category(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) image = models.ImageField(blank=True) def __str__(self) -> str: return f"{self.name}" class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(to=Category, on_delete=models.CASCADE) description = models.TextField(blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) image = models.ImageField(blank=True) vat_percentage = models.DecimalField(max_digits=4, decimal_places=2, blank=True) @property def price_with_vat(self): if self.vat_percentage: return (self.price / 100 * self.vat_percentage) + self.price else: return self.price def __str__(self) -> str: return f"{self.name} / {self.price} EUR" class Address(models.Model): street = models.CharField(max_length=255) city = models.CharField(max_length=255) country = CountryField() zip_code = models.PositiveIntegerField(validators=[MaxValueValidator(99999999)]) def __str__(self): return f"{self.street} / {self.city}" class DeliveryAddress(models.Model): street = models.CharField(max_length=255) city = models.CharField(max_length=255) country = CountryField() zip_code = models.PositiveIntegerField(validators=[MaxValueValidator(99999999)]) def __str__(self): return f"{self.street} / {self.city}" class Order(models.Model): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) address = models.ForeignKey(Address, on_delete=models.PROTECT) delivery_address = models.ForeignKey(DeliveryAddress, on_delete=models.PROTECT) company_name = models.CharField(max_length=255) company_ico = models.PositiveIntegerField(validators=[MaxValueValidator(9999999999)]) company_dic = models.PositiveIntegerField(validators=[MaxValueValidator(999999999999)], blank=True) company_vat = models.PositiveIntegerField(validators=[MaxValueValidator(999999999999)], blank=True) products = models.ManyToManyField(Product) And this is my view: views.py def create_order(request): if request.method == 'GET': context = { 'form': OrderForm } return render(request, 'eshop/create_order.html', context=context) … -
Why is my model instance not serializable?
I have the following model class class Club(models.Model): """ A table to store all clubs participating """ name = models.CharField(max_length=30) logo = models.ImageField(upload_to='images/') goals_last_season = models.IntegerField() points_last_season = models.IntegerField() def __str__(self): return F'{self.name}' and try to serialize it with htis encoder class ExtendedEncoder(DjangoJSONEncoder): def default(self, o): if isinstance(o, ImageFieldFile): return str(o) else: return super().default(o) as follows: def get_offer_details(request): """ View to get the queried club's data :param request: :return: """ # Get the passed club name club_name = request.POST.get('club_name') # Query the club object club_obj = Club.objects.get(name=club_name) # Create dict data = { 'club_obj': club_obj } # Return object to client return JsonResponse(data, safe=False, cls=ExtendedEncoder) which raises TypeError: Object of type Club is not JSON serializable. How can I basically serialize this? -
Please stuck for two days on this custom class detail class view is not display record
Please can anyone help me out on this issue Please stuck for two days on this custom class detail class view is not display record, i think is reverting back to the logged in user data instead of the detail from the list my code below not error even printed out the variable but still blank view.py class ListOfEnrolledCandidate(View): def get(self, request, **kwargs): users = CustomUser.objects.filter(user_type=6).select_related('candidates') context = { 'users': users } return render(request, 'superadmin/candidates/list-enrolled.html', context) class CandidateProfile(View): def get(self, request, **kwargs): user = CustomUser.objects.get(id=int(kwargs['id'])) print(user) return render(request, 'superadmin/candidates/profile-detail.html',{'users':user.id}) models.py class Candidates(models.Model): admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="candidates") profile_pic = models.ImageField(default='default.jpg', upload_to='upload') middle_name = models.CharField(max_length=255) gender = models.CharField(max_length=255) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) state = models.ForeignKey(State, on_delete=models.CASCADE) local = models.ForeignKey(Local, on_delete=models.CASCADE) dob = models.CharField(max_length=100) candclass = models.CharField(max_length=100, null=True) parentno = models.CharField(max_length=11, null=True) exam_year = models.CharField(max_length=100, null=True) profile_pic = models.ImageField(default='default.jpg', upload_to='media/uploads') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() def __str__(self): return self.middle_name class CandidateSubject(models.Model): admin = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) subject1 = models.CharField(max_length=255, null=True) subject2 = models.CharField(max_length=255, null=True) subject3 = models.CharField(max_length=255, null=True) subject4 = models.CharField(max_length=255, null=True) subject5 = models.CharField(max_length=255, null=True) subject6 = models.CharField(max_length=255, null=True) subject7 = models.CharField(max_length=255, null=True) subject8 = models.CharField(max_length=255, null=True) subject9 = models.CharField(max_length=255, null=True) subject10 = models.CharField(max_length=255, null=True) created_at … -
How to add images to a Pdf file from static files using borb library and Django
I want to add an image to a pdf file, the images are in the static directory: 'static/images/logo.png' Settings file: STATIC_URL = '/static/' Part of the Code: from borb.pdf.canvas.layout.image.image import Image page_layout.add( Image( "/static/images/logo.png", width=Decimal(128), height=Decimal(128), )) Error Code: MissingSchema: Invalid URL '/static/images/Logo.png': No schema supplied. Perhaps you meant http:///static/images/Logo.png? I do not want to show it in a front end template, instead is a backend function to generate pdfs. Do i have to provide/generate any kind of url link to the Image function?? how to do it? Thanks ! -
Django: "bash: npm: command not found" error when installing Tailwind CSS
I'm trying to install TailwindCSS on my Django App using this tutorial, unfortunly I'm stuck at this part $ npm init -y && npm install tailwindcss autoprefixer clean-css-cli && npx tailwindcss init -p When I try I get back this error: bash: npm: command not found I've downloaded and installed node.js and when I check using npm -v it seems that I have the 8.3.1 version and with node -v I got v16.14.0. I've tried installing again TaiwindCSS and I still get the error bash: npm: command not found Can somebody help me understand what I'm doing wrong? Thank you all -
How to return django ibject instance to client via ajax
I'm struggling to use an async (ajax) returned Django model instance on the client side. Something doesn't make sense with parsing the object to json / dict back and forth I assume. # views.py def get_offer_details(request): """ View to get the queried club's data """ # Get the passed club name club_name = request.POST.get('club_name') # Query the club object club_obj = Club.objects.get(name=club_name) # Transform model instance to dict dict_obj = model_to_dict(club_obj) # Serialize the dict serialized_obj = json.dumps(str(dict_obj)) # Return object to client return JsonResponse({'club_obj': serialized_obj}, safe=False) # .js function get_offer_details(club_name) { $.ajax({ url : "/get-offer-details/", // the endpoint headers: {'X-CSRFToken': csrftoken}, // add csrf token type : "POST", // http method data : { club_name : club_name }, // data sent with the post request // Update client side success : function(data) { // Grab the returned object let obj = data.club_obj // Parse it into an object let parsed_obj = JSON.parse(obj) // console.log(typeof) returns "string" // Access the data of the object let prev_goals = obj.goals_last_season // console.log(prev_goals) returns undefined ... console.log(data.obj) --> {'id': 2, 'name': 'FC Bayern Munich', 'logo': <ImageFieldFile: images/fcb_logo.png>, 'goals_last_season': 79, 'points_last_season': 71} -
Django jwt auth: How to override "Invalid or expired token" Error Message
How can i override default expired token message? example: right now im getting { "error": { "message": "Given token not valid for any token type", "status": 401, "error": "Invalid or expired token", "error_code": 6, "description": "The access token used in the request is incorrect or has expired. " } } in response message How can i change it -
Django Rest Framework user auth with React
Can anybody tell me the updated way to use User Authentication for Django Rest Framework? Each tutorial seems outdated. I would like to sign up, login logout using React with fetch function. Please share your experience. -
Bootstrap Modal Box Not showing in multiple events
I am trying to use Bootstrap modal box in my blog post website. On my Index page I am showing multiple posts and for each post on a button I want to open a modal box but I am not able to make it work. can some one point out where I am making the mistake {% for i in post %} <button type="button" class="btn btn-primary" data-toggle="modal" data- target="#exampleModal{{i.post_id}}"> Launch demo modal </button> <div class="modal fade" id="exampleModal{{i.post_id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h1>Yes</h1> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data- dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endfor %} -
How do I create unique log filenames using thread local in a gunicorn wsgi app?
I have a Django app with logging configured using dictConfig. Within dictConfig I call a custom filehandler that returns an instance of FileHandler with a filename. The filename is obtained by making an instance of thread local and giving it a uuid attribute. The app is served via gunicorn. When I test the app making two calls via postman, logs are written to the same file. I thought wsgi created a unique Django process, but I think it creates a process per worker that shares memory space, which I believe is why the filename remains the same after Django sets up the logger. How do I create unique log filenames using thread local in a gunicorn wsgi app? -
query ManyToManyfield for requested user
I have two models, a user model and a sport model. These two models have a m2m relationship as a user can do multiple sports and a sport can be played by more than one user. I want to get a query set of a user's sports, so only the sports a specific user does shows up for that user. I have created a context_processors.py file so that the information is available on all pages of the site. The problem is that I don't know how to query the database to get this information. These are my models: class Sport(models.Model): name = models.CharField(max_length=100, null=False) class User(AbstractUser): ... sports = models.ManyToManyField(Sport) Right now, I get all the sports available, like this def test(request): sports = Sport.objects.all() return { 'x': sports } I just want to get the sports the requested user is assigned to in the sports variable. -
Internal server [closed]
I m having the this issues after deploying an app on DigitalOcean. I Set Up a wagatail app with Postgres, Nginx, and Gunicorn on Ubuntu 20. And after the the configurations, here is what I get when I send a message from the contact app. Internal server error Sorry, there seems to be an error. Please try again soon. I have sentry running and telling me the errors like this: 1- ConnectionRefusedError /{var} New Issue Unhandled [Errno 111] Connection refused 2 - Invalid HTTP_HOST header: '${ip}:${port}'. The domain name -
python name '_mysql' is not defined
I build a virtual environment with python 3.7.10, by installing mysql and mysqlclient It is mysql 8.0.28, mysqlclient 2.1.0. When running python manage.py migrate It comes out like this: (test) ➜ backend git:(main) python manage.py migrate Traceback (most recent call last): File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/usr/local/Caskroom/miniforge/base/envs/test/lib/python3.7/site-packages/django/db/models/base.py", line … -
Why is django adding two slashes at the end of my urls?
I'm new to django and I'm trying to develop my first website. I've searched for similar questions but I couldn't find any (or maybe I've only searched the wrong query). What I'm here to asking is why django is adding a final slash into my url? and why is it doing this just in few occasions? I'd want to explain you better what it's happening to me. This is my urls.py (a portion) urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('new/', new, name="new"), path('attachements/<str:pk>/<str:var>/', attachements, name="attachements"), path('new_2_4/<str:pk>/<str:var>/', new_2_4, name="new_2_4"), path('new_4e2/<str:pk>/<str:var>//', new_4e2, name="new_4e2"), # others ] In my template.html I've created tag which allows me to go from a page to others, for example: <ul class="nav nav-tabs"> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'attachements' att.id var%}">Allegati</a> </li> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'new_2_4' att.id var %}">4</a> </li> <li class="nav-item" style="background-color:powderblue;"> <a class="nav-link" href="{% url 'new_4e2' att.id var %}">4.2</a> </li> </ul> <div style="position:relative; left:20px;"> <a class="btn-sm btn-info" href="{% url 'new_2_4' att.id var %}">&#x2190;</a> <a class="btn-sm btn-info" href="{% url 'new_4e3' att.id var %}">&#x2192;</a> </div> When I first have designed the whole thing, my url for 'new_4e2' didn't have two final slashes: I've had to add one final manually because … -
Ajax requires Basic authentication again
I have project with django and nginx and nginx has the basic authentication Accessing top page / the basic authentication works well. server { listen 80; server_name dockerhost; charset utf-8; location /static { alias /static; } location / { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://admindjango:8011/; include /etc/nginx/uwsgi_params; } } but in template, I use ajax to local api /api/myobj/{$obj_id} $.ajax({ url:`/api/myobj/${obj_id}/` It requires the authentication again and pop up appears. I wonder /api/myobj/ is under / Why it requires authentication again?? And even I put the id/pass correctly, it is not accepted. I tried like this ,but it also in vain. $.ajax({ url:`/api/myobj/${obj_id}/`, username: "myauthid", password: "myauthpass", -
Saving and displaying multiple checkboxes to Django ModelMultipleChoiceField
I am a beginner on django 2.2 and I can't correctly send multiple choices in the database. In my field table the days are stored like this: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] My form : CHOICESDAY = (("Monday", "Monday"), ("Tuesday", "Tuesday"), ("Wednesday", "Wednesday"), ("Thursday", "Thursday"), ("Friday", "Friday"), ("Saturday", "Saturday"), ("Sunday", "Sunday") ) class FgtScheduleForm(forms.ModelForm): days = forms.MultipleChoiceField(required=True, choices=CHOICESDAY, widget=forms.CheckboxSelectMultiple( attrs={'class': 'checkbox-inline'})) class Meta: model = FgtSchedule fields = ('name','days') widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control form-form ' 'shadow-none td-margin-bottom-5'}), } fields = ('name', 'days') My model class FgtSchedule(models.Model): days = models.CharField(max_length=100, blank=True) My view : def fg_schedule_list(request): list_fg_sch = FgtSchedule.objects.all() return render(request, 'appli/policy/fg_schedule.html', {'list_fg_sch': list_fg_sch}) My template {% for fg_sch_list in list_fg_sch %} <tr> <td>{{ fg_sch_list.id }}</td> <td>{{ fg_sch_list.name }}</td> <td>{{ fg_sch_list.days|replace_days }}</td> </tr> {% endfor %} My custom tags : @register.filter def replace_days(value): CHOICESDAY = {"Monday": "Monday", "Tuesday": "Tuesday", "Wednesday": "Wednesday", "Thursday": "Thursday", "Friday": "Friday", "Saturday": "Saturday", "Sunday": "Sunday"} return CHOICESDAY[value] The problem is when I want to display later all the days I have KeyError at "['1', '2']" -
is there a way to find duplicated value that has both the same address and pickup date in two different table?
I am currently working on a delivery app. Basically, what I am trying to achieve here is to have a counter that display out any potential duplicated jobs that the customer might have accidently double entered. The criteria to be considered as a duplicated job is as such: Has to have same delivery_address and same pickup_date. This is my postgresql tables: class Order(models.Model): id_order = models.AutoField(primary_key=True) class OrderDelivery(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) delivery_address = models.TextField() class OrderPickup(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) pickup_date = models.DateField(blank=True, null=True) This is what I have came up with so far: def dashboard_duplicated_job(orders, month): # This function finds for jobs that has # (1) exact pickup_date # (2) exact delivery address # and mark it as duplicated job. # Find current month, if not take current year now = timezone.localtime(timezone.now()) month = "12" if month and int(month) == 0 else month if month == 12 or month == '12': now = timezone.localtime(timezone.now()) last_month = now.today() + relativedelta(months=-1) start_date = last_month.replace(day=1).strftime('%Y-%m-%d') year = last_month.replace(day=1).strftime('%Y') month = last_month.replace(day=1).strftime('%m') last_day = calendar.monthrange(int(year), int(month))[1] string_start = str(year) + "-" + str(month) + "-01" string_end = str(year) + "-" + str(month) + "-" + str(last_day) start_date = …