Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test not created testing database and not work
everyone I created TestCase, but when I put the command "python manage.py test", this test don't work. Can you help me, please? from django.test import TestCase from accounts.models import UserProfile class AccountsTestCase(TestCase): def setUp(self): print('test_setUp') UserProfile.objects.create(email='test@test.com', password='user111333') def get_user(self): user = UserProfile.objects.get(email='test@test.com') -
How to transfer from datatable data to python variable
Good day, guys! does anyone know how I can pass a data from my table to a python variable? Here's my snippet <table class="table table-hover table-dark"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Filename</th> <th scope="col">Date Uploaded</th> </tr> </thead> <tbody> {% for row in files %} <tr> <td>{{ row.0 }}</td> <td>{{ row.1 }}</td> <td>{{ row.3 }}</td> </tr> {% endfor %} For Example, I clicked a table row 2 then it supposedly get the row.1 value then it will transfer to my variable (get_name_from_table) in python. Here's my code in python get_name_from_table = "" return send_file(BytesIO(data_v), attachment_filename= get_name, as_attachment=True) ``` My main activity is to have a download file button, it's so hard for me to find a dynamic download button. :( -
Import "django..." could not be resolved from source Pylance (reportMissingModuleSource)
I created a new virtual environment in my folder "Django 2021", by typing "python -m venv env" in the cmd which was in the same directory as the folder "Django 2021", then I "pip install django" in the already active env, after that I used the command "django-admin startproject devsearch" (also in the venv). Now I had the "env" and "devsearch" subfolders of "Django 2021", then I dragged my "env" folder into my "devsearch" folder. After that I opened my VS Code (IDE) and selected my "devsearch" folder inside "Django 2021" as my workspace. Opened a new terminal (and also activated my venv) and ran the server (python manage.py runserver), everything still worked perfectly. However, after that, I tried coding something (can't remember) but I couldn't test it because django wasn't imported. I hovered my mouse over the problem and it displayed: "Import "django..." could not be resolved from source Pylance (reportMissingModuleSource)". Here is a bit of visual representation: enter image description here (Folders) enter image description here (VS Code) -
Getting MultiValueDictKeyError while checking if a field is empty
I have a regsitration form where a user chooses a plan. I am trying to check that if the field is empty a message should be displayed. The field name is plan. The code is below if password1==password2: if CustomUser.objects.filter(email=email).exists(): messages.info(request, 'User with same email already exists') return redirect('register') elif plan is None: messages.info(request, 'Please select a plan') return redirect('register') else: user=CustomUser.objects.create_user(full_name=full_name.upper(),age=age, phone_no=phone_no, address=address, plan=plan, email=email.lower(), password=password1) user.is_active = False user.save() usr_otp = random.randint(100000, 999999) UserOtp.objects.create(user = user, otp = usr_otp) mess = f"Hello, {user.full_name},\n Please enter the otp to validate your email and activate your account. \nYour OTP is {usr_otp} .\n Thanks!" return render(request, 'register.html', {'otp': True, 'user': user}) # return redirect('login') I have tried multiple ways to check whether the plan field is empty or not such as elif plan == ' ' elif not plan elif plan is None elif request.POST['plan'] == ' ' for all these I am getting only one error MultiValueDictKeyError at /account/register 'plan' Request Method: POST Request URL: http://127.0.0.1:8000/account/register Django Version: 3.2.8 Exception Type: MultiValueDictKeyError Exception Value: 'plan' Exception Location: C:\Users\rickb\Envs\virenv\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__ Python Executable: C:\Users\rickb\Envs\virenv\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\rickb\\Envs\\virenv\\jgs', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\rickb\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\rickb\\Envs\\virenv', 'C:\\Users\\rickb\\Envs\\virenv\\lib\\site-packages'] Server time: Mon, … -
import a file from a directory outside Django project
So I am making a UI to manage an ultrasound sensor GPiOs. I have a directory full of sensors' code and then I have a Django project with a django app. I am trying to import a ultrasound.py into views.py to use the main function that gets the distance. The problem is that when I do from Sensores.ultrasonidos import main I get a ModuleNotFoundError: No module named 'Sensores' error. I've seen that I have to add an __init__ file inside the directory. But doesn't work for me. Help is much appreciated. my views.py: from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import UltrasonicSensor from Sensores.ultrasonidos import main class IndexView(ListView): template_name = 'index.html' context_object_name = 'sensors' def get_queryset(self): return UltrasonicSensor.objects.order_by('-id')[:5] class SensorDetailView(DetailView): template_name = 'sensor_detail.html' context_object_name = 'sensor' my ultrasound.py: import time from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger def main(): # Grove - Ultrasonic Ranger connected to port D16 sensor = GroveUltrasonicRanger(16) counter = 10 while (counter < 10): distance = sensor.get_distance() distance = (float(distance) / 100) print('{:.4f} m'.format(distance)) if distance < 1: print('Cerca') elif 1 <= distance <= 1.9: print('Medio') else: print('Lejos') time.sleep(1) counter = counter + 1 if __name__ == '__main__': main() -
Select objects from django model based on user input
I have a large django model with about 800 objects and I want to create a view in which the user can select a certain number of those objects to pass to another view for further processing. The fact that there are so many objects of the model makes listing all the objects very unpractical, as the user would have to scroll through 800 objects. In order to address this problem, I want to place an as-you-type search-bar in the top of the view so that the user can type the name of the objects and select them by clicking them. When the objects are selected, they should appear under the search-bar as tags that the user can remove by clicking an "x" next to each one. When the user has made all the required selections, then they should be able to click a button and jump to the next view where those selected objects are accessible. The model I am using can be simplified to: class Song(): song_name = models.CharField(max_length=256) song_author = models.CharField(max_length=256, blank=True) song_content = models.TextField() def __str__(self): return self.song_name class Meta: ordering = ['song_order'] song_order = models.PositiveIntegerField(editable=False, db_index=True) So far I have been able to make a … -
Writing JavaScript function in Django models
I would like to get long, lat variables from my models.py, which looks something like this: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Marker(models.Model): latitude = models.FloatField( validators=[MinValueValidator(-90), MaxValueValidator(90)], ) longitude = models.FloatField( validators=[MinValueValidator(-180), MaxValueValidator(180)], ) And add fetch them to the line myLatLng in JavaScript function initMap() { const myLatLng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: myLatLng, }); new google.maps.Marker({ position: myLatLng, map, title: "Hello World!", }); } the sample code is here: https://developers.google.com/maps/documentation/javascript/examples/marker-simple So I would like to create a marker from my admin page and display it on the map -
TemplateDoesNotExist at / Home.html Exception Type: TemplateDoesNotExist
My Customers urls.py ''' from django import urls from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('', views.Home ,name= 'Home'), path('Hall/', views.Hall ,name= 'Hall'), path('Food_item/', views.Food_item ,name= 'food'), path('About_us/', views.About_us ,name= 'about'), ] ''' My Web_project urls.py ''' from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('customer.urls')), ] ''' Settings.py Templates ''' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', ], }, }, ] Customers View.py ''' from django.http.response import JsonResponse from django.shortcuts import render def Home(request): return render(request, "Home.html", {"title":" Home"}) def Hall(request): return render(request, "Hall.html", {"title": "Hall"}) def Food_item(request): return render(request, "Food_item.html", {"title": "Food_item"}) def About_us(request): return render(request, "About_us.html", {"title": "About_us"}) ''' My cd is web_project>customer>templates>customer>Home.html The error it showing ''' Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Nawaf Bhatti\Desktop\New\web_project\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\rest_framework\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site- packages\django\contrib\admin\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site- packages\django\contrib\auth\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\web_project\customer\templates\Home.html (Source does not exist) ''' -
How to serve premium content base on user subscription in django
Hello guys i hope the way i ask this questions meets the standard way of stackoverflow. I have a projects i'm working on. On this project you need to subscribe a plan (monthly, 3 months or 6 months) to gain access to premium blog post contents and if you are not subscribed but registered, you will only get access to regular blog post contents. I've been able to integrate payment api and also the payment is working, i've also been able to save the payment details on a table in my database. What i need now is how do i filter the user based on their subscription status to serve them the premium or regular contents.Below is my Models and Views. # In models.py class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) username = models.CharField(max_length=200, unique=True, blank=True) email = models.EmailField(max_length=200, unique=True, blank=False) first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) phone_no = models.CharField(max_length=11,validators=[MaxLengthValidator(11)]) profile_picture = models.ImageField(upload_to="images/profile_image",default="default_user_image.jpeg", blank=True, null=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] def __str__(self): return self.username def get_absolute_url(self): return reverse("admin-update-user", kwargs={"pk": self.pk}) class … -
Angular to Django: Unable to upload a file - file is blank
I am creating a File Upload feature in my application where the user has to upload an excel file along with a date (using a date picker). The user then clicks upload and this calls a view in Django which runs a python class that uploads the data onto an oracle database using SQLAlchemy. I have hit an issue where I don't know how to successfully pass through a file in my service call. In the example below, I have assigned the file to the variable fileToUpload but when this is called in the upload service and assigned in a dictionary, the value of that becomes empty. Please see code below: views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.data['data'], request.data['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST) file-upload.service.ts DJANGO_SERVER: string = "http://127.0.0.1:8000"; constructor(private http:HttpClient) { } public upload(data: any, selectedDate:any) { let postData = { data, selectedDate }; return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, postData); } upload.component.ts onChange(event: any) { this.filetoUpload = event.target.files[0]; } inputEvent(event:any) { this.monthEndDate = event.value; } onUpload() { this.loading = !this.loading; this.fileUploadService.upload(this.filetoUpload, this.monthEndDate).subscribe( (event: any) => { if (typeof (event) === … -
How to create a for loop based lightbox gallery with django
(Newbie Django dev here, with no Javascript knowledge) I'm building a Django website designed to display one page for each notice in the db. Some images can be attached to the notices: sometimes none, sometimes a few, up to maximum a dozen. I'd like to display these images on top of the detail.html page, following the example shown here: https://www.w3schools.com/howto/howto_js_lightbox.asp I understood that I need to adapt the code to use a for loop. I did my best to adapt it but I'm stuck with a non working gallery. Here is my code right now, adapted from the tutorial: detail.html <div id="illustrations" class="galerie"> {% for image in object.illustration_objet_archi.all %} <div class="row"> <div class="column"> <img src="{{ image.image_thumbnail.url }}" onclick="openModal();currentSlide({{ forloop.counter }})" class="hover-shadow"> </div> </div> <!-- The Modal/Lightbox --> <div id="myModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content"> <div class="mySlides"> <div class="numbertext"> {{ forloop.counter }} / {{ image.image.count }} </div> <img src="{{ image.image.url }}" style="width:100%"> </div> <!-- Next/previous controls --> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <!-- Caption text --> <div class="caption-container"> <p id="caption">{{ image.legende }}</p> </div> <!-- Thumbnail image controls --> <div class="column"> <img class="demo" src="{{ image.image.url }}" onclick="currentSlide({{ forloop.counter }})"> </div> </div> </div> {% endfor %} </div> style.css (the body … -
Not Found error after logging in with google using django-allauth
I am using django-allauth package and google provider for authentication in my django project. Everything worked fine in development however when I launched my project on the server, I got an error. When I press the "Log in with Google" button in my sign in page, I get redirected to the page where google asks me to choose my Google account to continue with. Then after this step, where I get redirected to my site, I'm encountered with a Not Found error. I tried a bunch of stuff found online but they didn't work. here is my Google credentials authorized redirect URIs. In my settings.py file I configured allauth as below: # Django-allauth configs AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_SIGNUP_REDIRECT_URL = 'accounts:create_profile_url' ACCOUNT_EMAIL_VERIFICATION = 'none' LOGIN_REDIRECT_URL = 'dashboard_url' ACCOUNT_FORMS = { 'login': 'accounts.forms.CustomLoginForm', 'signup': 'accounts.forms.CustomSignupForm', 'change_password': 'accounts.forms.CustomChangePasswordForm', } ACCOUNT_DEFAULT_HTTP_PROTOCOL='https' and I've added 'allauth.urls' in my urlpatterns too urlpatterns = [ ... path('accounts/', include('allauth.urls')), ... ] I … -
Django - filter queryset until Sum is reached
Let's imagine a model called Roll. It stores the outcome of rolling a six-sided die (D6): class Roll(models.Model): outcome = models.PositiveSmallIntegerField('Roll', null=False, blank=False, default=1) There are many rolls, for example: print(list(Roll.objects.all().values_list('outcome', flat=True))) >>> [1, 5, 6, 3, 5, 4, 4, 3, 2] Now, how should I go about to get the latest N rows whose Sum('outcome') reaches an arbitrary amount, without looping in some way or another, until that amount is reached? If we imagine the rolls: pk | outcome | (accumulated sum) 1 | 3 | 3 2 | 2 | 5 3 | 6 | 11 4 | 1 | 12 5 | 5 | 17 6 | 4 | 21 7 | 3 | 24 8 | 4 | 29 9 | 5 | 34 10 | 1 | 35 and the arbitrary amount 20, then the query should pick the pk 6 as the accumulated sum has now reached the amount needed. Could something similar to the below work?: amount = 100 Roll.objects.annotate( accumulated_sum=Subquery( Roll.objects.filter( pk__lt=OuterRef('pk') ).values('pk').order_by('pk').annotate( sum=Sum('outcome', distinct=True) ).values( 'sum' )[:1] ) ).filter( sum_before__gte=amount ) -
Django: get attributes values
I want to get all attributes values, but unfortunately , I got only one which is getting from self.name My models.py class Container(models.Model): number = models.CharField(max_length=13) # Example: MSKU 907032-3 iso_type = models.ForeignKey(Container_type, on_delete=models.CASCADE, null=True) weight = models.PositiveSmallIntegerField(null=True) terminal = models.ForeignKey(Terminal, on_delete=models.CASCADE, null=True) arive_time_to_terminal = models.DateTimeField() port = models.ForeignKey(Port, on_delete=models.CASCADE, null=True) CY = models.DateTimeField() ETD = models.DateTimeField() status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True) order_added = models.DateTimeField() # Change ALL null=False exception STATUS, time = DateTimeField def __str__(self): return self.number Views.py def terminal(request,id): terminal = Terminal.objects.get(name=id) container = Container.objects.all() #terminal_id=1 return render(request, 'main/terminal.html', {'title': 'Terminal', 'terminal': terminal, 'number':container }) and template is: {{ weight }} {{ terminal }} {{ arive_time_to_terminal }} {{ Container.port }} {{ CY }} {{ ETD }} Many Thanks -
Docker Django + Nginx use hostnames
I've createda a docker-compose configuration with one container for Django and another one for Ngnix, but accessing Nginx as client result in: HTTP_HOST header: 'container_name.network_name:port'. The domain name provided is not valid according to RFC 1034/1035. location / { proxy_pass http://container_name.network_name:port; This means that the Nginx proxy reach the remote address of the django container but even if I add only for test purpose ALLOWED_HOST=['*'] to django it still goes to this error. Is there a way to use the container_name.network_name syntax? -
django - how to sum values of the same key?
I want to sum the value of the count key if the values of year_taken have duplicates, how can I do that? so the output would look like this {'year_taken': '2019-2020', 'count': 1}, {'year_taken': '2021-2022', 'count': 3} -
How do I selectively mark books read by a user in the frontend if I have a common dataset of books and a dataset of the particular books read?
I have a "Books" model in django which stores information like the name, author etc (irrelevant here, just mentioning for some context). I display all that information using a Paginator and each user has the option of marking the books he/she has read. To mark them, what I can think of doing is creating another model called "BookStatus" where I insert new entries every time a user reads a book. However, I'm unable to figure out how to actually display that the user has read some particular book next to the book's name while displaying it in the frontend. What would be the easiest way to accomplish this? In short, I have a database of books which are common to all users. For each user I want to store the books he/she has read and while displaying those common books I want to be able to mark them as read/unread on the frontend. -
Django profile model
I am beginner on django and trying to create a profile model that interrelate "User" built-in model via One-To-One relation field, it results impossible to span the user model properties by profile model instance and vise versa. Can someone help me. models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): users=models.OneToOneField(User, on_delete=models.CASCADE) image=models.ImageField(default='profilepic.jpg',upload_to='profile_pictures') location=models.CharField(max_length=100) def __str__(self): return self.users.username profileTemplate.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Profile</title> </head> <body> <h2>{{user.username}}</h2> <img src='{{user.Profile.image}}'> </body> </html> -
Unable to server static files Django S3
I'm trying to put static files to S3, and here's what I have so far in settings.py: # AWS S3 Static Files Configuration AWS_ACCESS_KEY_ID = config('AWS_S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_S3_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_S3_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' AWS_DEFAULT_ACL = None STATICFILES_DIRS = [ 'pakcage404/static', ] STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'ca-central-1' AWS_S3_USE_SSL = False AWS_S3_ENDPOINT_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.ca-central-1.amazonaws.com" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.ca-central-1.amazonaws.com/{AWS_STORAGE_BUCKET_NAME}" But when I try to access one of the static files I have uploaded, I was given this error message on the browser: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>some request ID</RequestId> <HostId>some ID</HostId> </Error> -
How to annotate related table in django?
I have two entities Task and Technology. Technology table has a FK to Task and each task has 9 technologies. enabled category frequency c1 c2 c3 note True 3G 2100 11/03/2010 foo False 4G 700 02/04/2012 bam False 4G 1800 spam True 4G 2100 bim True 4G 2600 bum True 5G 700 tan False 5G 3700 tan True 5G 26000 tan For each tasks I need to annotate a cell of this technology matrix. This means annotate something like: candidates_technologies__3G_2100_enabled candidates_technologies__3G_2100_c1 candidates_technologies__3G_2100_c2 candidates_technologies__3G_2100_c3 candidates_technologies__3G_2100_note candidates_technologies__4G_700_enabled candidates_technologies__4G_700_c1 candidates_technologies__4G_700_c2 candidates_technologies__4G_700_c3 candidates_technologies__4G_700_note candidates_technologies__4G_1800_enabled candidates_technologies__4G_1800_c1 candidates_technologies__4G_1800_c2 candidates_technologies__4G_1800_c3 candidates_technologies__4G_1800_note ... Where candidates_technologies is the related name. Currently this is my solution, but is killing the performance. from django.db.models import Q, F, Value, Case, When, DateField, BooleanField, CharField bool_cols, text_cols = ["enabled"], ["onair_note"] date_cols = [t for t in TECHNOLOGY_COLUMNS if t not in text_cols or t not in bool_cols] columns = date_cols + bool_cols + date_cols def _get_output_field(col): if col in bool_cols: return False, BooleanField() elif col in text_cols: return "", CharField() else: return None, DateField() tech_annotations, whens = {}, [] for category, frequency in TECHNOLOGY_FREQUENCY_LIST: for column in columns: out = _get_output_field(column) key = '_'.join([category, frequency, column]) value = ExpressionWrapper( Case( When( Q(**{'candidates_technologies__category': category}) … -
Change background color in a select option dropdown
I'm rendering a form using django. One of the fields in the form is a select with options. Rendering form field: {{ form.work }} The select options after rendering are: <select name="work" class="form-control" required="" id="id_work"> <option value="" selected="">---------</option> <option value="chair">The chair</option> <option value="table">The table</option> </select> How can i change the background color for each of the values? So when i press the dropdown arrow to see all values with different colors. I used css with no success. select option[value="chair"] { background-color: red !important; } select option:nth-child(2) { background: red; } As a note, the form consists of different fields with select options. I use bootstrap 4. Thank you -
I am getting 'BasePermissionMetaclass' object is not iterable when trying to access the api
I am trying to access the api i made but i keep getting this 'BasePermissionMetaclass' object is not iterable error views.py class BlogPostListView(ListAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostDetailView(RetrieveAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostFeaturedView(ListAPIView): queryset = BlogPost.objects.all().filter(featured = True) serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostCategoryView(APIView): serializer_class = BlogPostSerializer permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = BlogPost.objects.order_by('-date_created').filter(category__iexact = category) serializer = BlogPostSerializer(queryset, many=True) return Response(serializer.data) In settings.py i have : REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } I havetried everything i can think of but not been able to fix it -
How to update stock through purchase and sale in Django?
I am working on a Django Billing Webapp/Invoicing Webapp. I'm having a problem updating stocks through Purchase and Sales. I want the medicine quantity to increase when there is a purchase and decrease when there is a sale. But after a lot of tries, I cannot achieve it. Please help me to integrate this feature into my Django WebApp. Here are the contents of the files: Models.py from django.db import models from django.utils import timezone from django.shortcuts import render, get_object_or_404 #------------------------Medicine models---------------------------------- gst = ( (0, '0%'), (5, '5%'), (12, '12%'), (18, '18%'), ) # Create your models here. class Medicines(models.Model): Med_HSN = models.IntegerField(default=0) Med_name = models.CharField(max_length=20) Med_Quantity = models.IntegerField(default=0) Med_Manufacturer = models.CharField(blank=True,max_length=50) Med_Expiry = models.CharField(default=1,max_length=10) Med_Batch_no = models.CharField(blank=True,max_length=15) Med_MRP = models.FloatField(blank=False) Med_Rate = models.FloatField(blank=False) Med_GST = models.IntegerField(default=0,choices=gst) date_created = models.DateField(default=timezone.now) def caluclate_value(self): value = self.Med_MRP * (self.Med_GST/100) total_value = self.Med_MRP + value return total_value def get_cost(self): return self.caluclate_value() * self.Med_Quantity def __str__(self): return self.Med_name + " : " + str(self.caluclate_value()) # def caluclate_stock(self): # med_quantity = self(request=self.request).Med_Quantity # get_med_1_quantity = Purchase.med_quantity_1 # value = med_quantity + get_med_1_quantity # print(value) # return value #----------------------------------End Medicines Models-------------------------------------- #---------------------------------Sales Models-------------------------------- from django.core.checks import messages from django.db import models from Customer.models import Customer … -
Expire/Invalidate Session from all browsers except current
I have a django application that is using cookie-based sessions. I have a use-case where, after user changes the password, I update the session using update_session_auth_hash(request, request.user). The problem is when I have logged in from 2 different browsers and I update the password from one browser, it automatically updates the session in other browser. What I want is that, when I change the password in one browser, it should update the session on that browser only and remove/invalidate session from all other browsers. -
Django rest Framework error messages. Does not work
I am new to Django and I am working on a small project, I want an error message to be shown if the user let the field empty. the code that I wrote is not working. Can anyone help me ? def validate_name(school: School): if school.name is None: raise APIException(detail='Name is mandatory.') class SchoolService(object): @staticmethod def validate_create(school: School): validate_name(school)