Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make postgresql row fields "read only", if all fields of a row is filled up
How to make postgresql row fields "read only", if all fields of a row is filled up. I am using Django. -
Django Migration Error 'TypeError: sequence item 1: expected a bytes-like object, str found' on mysql-connector-python cursor_cent.py file
I'm using mysql-connector to handle mysql requests in a Django project. Problem is I'm setting up a simple project with "django-admin startproject project ." and when I try to do a simple manage.py migrate, this is my output. $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: aqui <mysql.connector.cursor_cext._ParamSubstitutor object at 0x7f408ae1ec10> b'SELECT engine FROM information_schema.tables WHERE table_name = %s' 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 "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 91, in migrate self.recorder.ensure_schema() File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 68, in ensure_schema editor.create_model(self.Migration) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 348, in create_model self.deferred_sql.extend(self._model_indexes_sql(model)) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 1087, in _model_indexes_sql output.extend(self._field_indexes_sql(model, field)) File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/base/schema.py", line 1106, in _field_indexes_sql if self._field_should_be_indexed(model, field): File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/mysql/schema.py", line 111, in _field_should_be_indexed storage = self.connection.introspection.get_storage_engine( File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/mysql/connector/django/introspection.py", line 270, in get_storage_engine cursor.execute( File "/home/thejhoule/anon/anonproj/end/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) … -
Aligning form labels input-group-prepend with bootstrap
I'm working on a python/django website with bootstrap, but i'm running into something i can't seem to solve on my own. Been a while since i've worked with python/django/bootstrap, so i might be missing something? <form action="" method="post" autocomplete="off"> {% csrf_token %} {{ form.non_field_errors }} <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend "> <span class="input-group-text" id="basic-addon1">Player Name</span> </div> <input type="text" class="form-control" id="player_name" name='player_name' placeholder="Player Name"> </div> <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend "> <span class="input-group-text " id="basic-addon1">Recruiter</span> </div> {{ form.recruiter }} </div> <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Notes</span> </div> <input type="text" class="form-control" id="notes" name="notes"> </div> <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Accepted</span> </div> <select class="form-select form-select-lg" aria-label=".form-select-lg" id='accepted' name='accepted'> <option value="Not Yet" selected>Not Yet</option> <option value="No">No</option> <option value="Yes">Yes</option> </select> </div> <div class="input-group mb-3 col-lg-4"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Vote is up</span> </div> <select class="form-select form-select-sm" aria-label=".form-select-sm" id='vote_is_up' name='vote_is_up'> <option value="No" selected>No</option> <option value="Yes">Yes</option> </select> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="archived" hidden> <label class="form-check-label" for="flexCheckDefault" hidden> Archived </label> </div> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% endif %} <button type="submit" class="btn btn-primary">Add</button> … -
How to restrict user in Django to login through only one device, window or tab?
I am looking to develop a functionality to enable the user to login to only one place , if he tries to login from another device or tab then he will get logout from the previos tab or device, i didnt find any good solutios to implement, any help is appreciated -
find previous sunday date based on today date in Django
Let us consider today date as 09/11/2021 And previous sunday date is 31/10/2021 today = datetime.date.today() Now find previous sunday date -
Django MongoDB Model field with unique values or null
I am using Djongo v1.3.6 to connect Django to MongoDB. Now I would like to have an optional field for a unique value - in my case a phone number. I thought it is possible to have null as a placeholder for accounts that do not have a phone number. However, MongoDB seems to be treating null as a unique value as well. Thus, it is not letting me insert new objects into the database once one object has phone_number: null I tried to declare the index for phone_number as sparse but it does not seem to take any effect. I searched the Internet for some time now but could not find anything useful for my case. class UserProfile(models.Model): user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE) phone_number = models.CharField(validators=[PHONE_VALIDATOR], max_length=17, unique=True, null=True, blank=True) ... meta = { 'indexes': [ {'fields': ['phone_number'], 'sparse' : True, 'unique' : True}, ], } Any help is very appreciated. -
Internal server error 500 when uploading a CSV file using AJAX
I have a very simple web app for uploading CSV files to my server. For that purpose, I'm using AJAX and JQUERY under DJANGO: function Upload_CSV(){ var csrftoken = getCookie('csrftoken'); var formData = new FormData(document.getElementById("formUploadCSV")); var add_answer = confirm("Confirm uploading and processing of csv File?" ); if (add_answer) { $.ajax({ url: "/cvs/DealsMachine/upload_csv/", type: "POST", data: formData, async: false, cache: false, contentType: false, enctype: 'multipart/form-data', processData: false, success: function (data) { $('#message').html("<p class='text-center text-success font-weight-bold'>Success</p>"); window.alert("Data populated, please check the lists table!"); }, error: function(data) { $("#message").html("<p class='text-center text-danger font-weight-bold'>Failed</p>"); } }); } } However, every time I try to use the function, I'm receiving POST 500 (Internal server error). I was able to capture the following on the browser console: Any idea about how to handle this error? I deployed the app on another server and works fine. So maybe is something about server configuration. (I'm using Linux servers) Thanks! -
Field is required even though it's been explicitely set to not required in serializer
I'm running into some trouble with a route creating/updating a model, DRF asks for a field I've set to not required, and it's been working with other serializers but not a speficic one. The request (here the costing nested object is what interests us) : { "building_block_id":"bd750fa0-d41d-492d-adc1-9aa7c50db232", "building_block_type_ids":"6fb5b907-9597-45fd-bb77-e93a2456cca3", "approbation_user":"", "approved":false, "name":"BB2", "web_doc_link":"", "author":"", "cms":"", "part_number":"", "manufacturer":"", "description":"T", "available_stock":null, "include_bench_output_connector":true, "base_repository":"", "form_factor_id":null, "direction_bench_side":null, "cost_references":[ { "cost":2, "cost_date":"2021-11-03", "cost_quantity":2, "fab_cycle_time_days":2 } ], "coupling":[ { "developped":false, "tested":false, "validated":false, "delivered":false, "valid_link":"", "implem_link":"", "software_version_id":"62f4c9f8-1156-4b41-af1a-22041b824d06" } ], "comments":[ ], "features":[ ], "provides":[ ], "requires":[ ] } Error returned by Django : { "coupling": [ { "building_block_id": [ "This field is required." ] } ] } Serializer class : class BuildingBlockSerializer(serializers.ModelSerializer): cost_references = NestedCostReferenceSerializer(many=True, required=False) coupling = NestedCouplingSerializer(many=True, required=False) comments = NestedBuildingBlockCommentsSerializer(many=True, required=False) features = NestedFeaturesBuildingBlockSerializer(many=True, required=False) provides = NestedProvidesSerializer(many=True, required=False) requires = NestedRequiresSerializer(many=True, required=False) main_picture_link = Base64ImageField(required=False) front_picture_link = Base64ImageField(required=False) back_picture_link = Base64ImageField(required=False) # Related names for reverse relationship cost_reference_rel_name = 'cost_references' coupling_rel_name = 'coupling' comment_rel_name = 'comments' feature_rel_name = 'features' provide_rel_name = 'provides' require_rel_name = 'requires' class Meta: model = building_blocks.BuildingBlock fields = ['building_block_id', 'building_block_type_ids', 'approbation_user', 'approved', 'name', 'main_picture_link', 'front_picture_link', 'back_picture_link', 'web_doc_link', 'author', 'cms', 'part_number', 'manufacturer', 'description', 'available_stock', 'include_bench_output_connector', 'base_repository', 'form_factor_id', 'direction_bench_side', 'cost_references', 'coupling', 'comments', … -
Cant use findAll() function
can any body tell me why is error html_content = get_html_content(test) from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'html.parser') productDetail = [] product = soup.findAll("div",{"class":"s-result-item"}) for pd in product: product = pd.find("div",class_="s-impression-counter") product_name = product.find('span',class_="a-text-normal").text productDetail.append(product_name) print(productDetail) it appears 'NoneType' object has no attribute 'find' i know the problem is in the product variable, but if i not allow to use findAll(), what should i use ? -
save data to Django models on different types of messages I receive on Mqtt
My goal is to save data to my Django models on different types of messages I receive on Mqtt. For that I assume I need to import the model I want to save. But when I do I get "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." My mqtt connection setup: mqtt.py import paho.mqtt.client as mqtt from print.views import * def on_connect(client, userdata, rc, properties=None): client.subscribe("foo/printers/#") print("Connection returned result: " + mqtt.connack_string(rc)) def on_message(client, userdata, msg): handle_msg(msg.topic, msg.payload) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set(username="foo",password="bar") client.connect("mqtt.foo.de", 1883, 60) My __init__.py: from . import mqtt mqtt.client.loop_start() My Messagehandler view: from models import Machine def handle_msg(topic, message): printer = topic.split("/")[2] print(Machine.objects.get(Name=printer)) When I put the import inside the function it simply doesnt work -
Apache Django Error - Loading Module From lib64 But Expected To Load From Different Directory
I have configured apache, python virtual environment, and Django. I'm trying to host the Django in apache. I verified the Django working fine by running the command "./manage.py runserver 192.168.0.107". But this is not working in Apache, in apache, if I load the page I'm getting 500 Internal Server errors. In the Apache HTTP log, I got the below error message. [Mon Nov 08 18:21:51.248632 2021] [wsgi:error] [pid 1812] [remote 192.168.0.105:50224] django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17) In Python, I verified the SQLite version and it says 3.36.0 and not 3.7.17, refer to the details below. Python 3.7.12 (default, Nov 8 2021, 09:02:58) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from sqlite3 import dbapi2 as Database>>> >>> from sqlite3 import dbapi2 as Database >>> Database.sqlite_version_info (3, 36, 0) I tried to find the version that apache actually using, I used the grep command and I found it was using SQLite 3.7.17 from lib64 [root@localhost ~]# grep -rnw /usr -e '3.7.17' /usr/lib64/pkgconfig/sqlite3.pc:10:Version: 3.7.17 /usr/include/sqlite3.h:110:#define SQLITE_VERSION "3.7.17" REQUIREMENT I need to clean or uninstall package 3.7.17 and tell Apache or WSGI to use 3.36.0 Below is the configuration … -
How to update multiple objects in django
I'd like to update more than one objects at same time, when the register date achieve more than 6 days: The Idea is update all issue_status from 'On Going' to 'Pending' for each objects Is it necessary iterate it? Below is my current code and error: models.py class MaintenanceIssue(models.Model): issue_status = models.CharField(max_length=30, choices=[('pending', 'Pending'), ('on going', 'On going'), ('done', 'Done')]) register_dt = models.DateTimeField(blank=True, null=True) @property def pending_issue(self): issue_time_diff = (datetime.now() - self.register_dt).days return issue_time_diff views.py: on_going_issues = MaintenanceIssue.objects.get(issue_status='On Going') if on_going_issues.pending_issue > 6: on_going_issues.issue_status = 'Pending' on_going_issues.save() get() returned more than one MaintenanceIssue -- it returned 61! -
twilio sms status callback - not in json
I made a django app that integrates with Twilio SMS and I am trying to set-up a way to get the status of an sms I send. I have been following twilio guide on how to track delivery status on python so when I send a text I send it with the following parameters (where sms_obj is an instance in my db to keep track of the text I am sending). def send_sms(sms_obj, to): client = Client(account_sid, auth_token) message = client.messages \ .create( body=sms_obj.body, from_= phone_number, to=to, status_callback='https://www.ateam.productions/comunications/twilio/sms/status/{sms_id}'.format(sms_id=sms_obj.id) ) return So basically I should receive a callback with delivery statuses on this url https://www.ateam.productions/comunications/twilio/sms/status/{sms_id}, (which I do) However, the data I get from Twilio aren't in a nice Json structure but rather a long string like the one below. Before I start coding some weird regex to process such string, I was wondering if anyone had advices on how to handle the process. SmsSid=SM3bceec02449e4a75a3c308e2befa6136&SmsStatus=sent&MessageStatus=sent&To=%2B19174003826&MessageSid=SM3bceec02449e4a75a3c308e2befa6136&AccountSid=////////&From=%2B19179244405&ApiVersion=2010-04-01 -
Template Does Not Exist at / cms_wizard /create/ INHERIT
The issue > https://i.stack.imgur.com/0mbDr.png Here is one solution I tried: "os.path.join(SETTINGS_PATH, 'templates'), "(I substituted SETTINGS_PATH with BASE_DIR, and the setting.py terminated without any errors but still the problem isn't solved. how am I supposed to inherit the template, it has to be in a folder which I should make? also, the directory of cms_wizard/create isn't making sense as shown in the image above how do I fix it. Here is my setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'sekizai.context_processors.sekizai', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'cms.context_processors.cms_settings', 'django.template.context_processors.i18n', ], }, }, ] -
Django makemigrations models conflict apps extensions
I'm trying to extend 2 apps in django. While I'm trying to apply manage.py makemigrations I'm recieving the following error: File "Desktop\ipam\ipam_extension\openwisp_ipam_extension\models.py", line 3, in <module> from openwisp_ipam.base.models import AbstractIpAddress, AbstractSubnet File "Desktop\ipam\venv\lib\site-packages\openwisp_ipam\base\models .py", line 10, in <module> from openwisp_users.models import Organization File "Desktop\ipam\venv\lib\site-packages\openwisp_users\models.py" , line 18, in <module> class User(AbstractUser): File "Desktop\ipam\venv\lib\site-packages\django\db\models\base.py" , line 113, in __new__ raise RuntimeError( RuntimeError: Model class openwisp_users.models.User doesn't declare an explicit app_label and isn't in an application in INSTA LLED_APPS. My 2 apps are: openwisp_users_extension extends openwisp_users openwisp_ipam_extension extends openwisp_ipam The problem is probebly that in openwisp_ipam_extension.models I have this line: from openwisp_ipam.base.models import AbstractIpAddress, AbstractSubnet Which internally using openwisp_users extended app. I assume this conflict shouldn't happend because I saw it is possible to extend both apps together -
django oauth2 Session value state missing error
there is my social auth setting and it works correctly in local-host but on server it returns session value state missing error. i have tested similar questions in stack overflow but the answers didn't solved my problem. SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = '' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = '' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home/' SOCIAL_AUTH_LOGIN_URL = '/' SOCIAL_AUTH_REDIRECT_IS_HTTPS = True LOGIN_URL = '/auth/login/google-oauth2/' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SOCIAL_AUTH_FIELDS_STORED_IN_SESSION = ['state'] SESSION_COOKIE_SECURE = False AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.linkedin.LinkedinOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) white_list = ['http://localhost:8000/accounts/profile'] DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}', 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': white_list, 'ACTIVATION_URL': '#/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SOCIAL_AUTH_TOKEN_STRATEGY': 'djoser.social.token.jwt.TokenStrategy', 'SERIALIZERS': {}, } SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) -
Order by nested objects date
I am building a chat application and have the following models representing the chat room, chat message and the counter of unread messages class ChatRoom(BaseModel): name = models.CharField(max_length=255, default='', blank=True) participants = models.ManyToManyField('accounts.User', related_name='chat_rooms') class ChatMessage(BaseModel): text = models.TextField(default='', blank=True) owner = models.ForeignKey('accounts.User', on_delete=models.CASCADE) room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name='messages') class ChatRoomUnreadMessagesCounter(BaseModel): room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name='unread_counters') owner = models.ForeignKey('accounts.User', on_delete=models.CASCADE) messages_count = models.IntegerField(default=0) class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_deleted = models.BooleanField(default=False) class Meta: abstract = True I would like to make an API view that would return a list of ChatRoom objects that are ordered in the following manner: ChatRoom objects that have unread messages ordered by messages count -> ChatRoom objects that have messages in them by the latest message created_at last in first out -> ChatRoom objects that are sorted alphabetically. How would I construct my queryset properly? Here's an expected result output | Room Name | Unread Messages | Last Message | | Rean | 2 | 09.11.2021T12:00:00 | | Ash | 1 | 09.11.2021T12:00:24 | | Altina | 0 | 09.11.2021T12:15:00 | | Juna | 0 | 09.11.2021T12:14:00 | | Kurt | 0 | 09.11.2021T12:13:00 | | Musse | 0 | 09.11.2021T12:12:00 | … -
Django send multiple responses
Disclaimer: New to Django, don't know all the advanced stuff here so may be quoting my question in a misleading way. I have set up a Django web server that does some numerical calculation with some network data on the server-side and returns the data to the client. Now, the tasks requested by users have multiple results and they are generated sequentially. For now what I'm doing (1) User send a task request from frontend---> (2) calculation is done in the backend sequentially and all the result is generated ---> (3) django sends all the result in a single response to the frontend to update the result. Now the 2nd step that is the calculation part takes a lot of time about 1-2 seconds which spoils the user experience on the client-side. As multiple results are generated sequentially, I can show the result one by one to the client as they are generated. But I can't understand how can I send multiple responses against a single client request. I guess this is not possible with HTTP? Can anyone help me how do I tackle this problem? Is it possible to that? -
Django searching multiple models and removing duplicates
I am trying to build a search function for my blog that searches through the two models Articles and Spots. The two models are connected via the pivot table ArticleSpots. My blog is structured so that there are multiple spots in each article. When a query is searched I want the query to be searched within both models but only display clickable articles. I have a html page for each article but not for each spots, so all the spots that resulted from the search have to be shown as the article which contains the spot. Hope that makes sense! This is the code that I came up with but the problem is that I get a lot of duplicates in the variable results. There are duplicates within each articles_from_spots and articles_from_query, and there are also overlaps between them. Is this the right way to accomplish this ? How can I remove the duplicates from the results? Any help would be appreciated! views.py def search(request): query = request.GET.get("q") articles_from_query = Articles.objects.filter( Q(title__icontains=query) | Q(summary__icontains=query) ) spots_from_query = Spots.objects.filter( Q(title__icontains=query) | Q(summary__icontains=query) | Q(content__icontains=query) ) articles_from_spots = [] for x in spots_from_query: article = Articles.objects.filter(articlespots__spot=x) articles_from_spots.extend(article) results = chain(articles_from_spots, articles_from_query) context … -
Django: custom storage system with incremental number
I'm trying to creare a custom storage file system in python to have the duplicate files that are uploaded to be different by a number that increment. The code is kinda working, my only problem is that instead having this kind of results: nameofthefile_1.txt nameofthefile_2.txt nameofthefile_3.txt I get this nameofthefile_1.txt nameofthefile_1_2.txt nameofthefile_1_2_2.txt This is my code class CustomStorage(FileSystemStorage): def get_available_name(self, filename, max_length=None): number_1 = filename.split('_')[19] plus_one = int(number_1.split('.')[0]) if self.exists(filename): plus_one += 1 dir_name, file_name = os.path.split(filename) file_root, file_ext = os.path.splitext(file_name) filename = os.path.join(dir_name, '{}_{}{}'.format(file_root, plus_one, file_ext)) return filename def user_directory_path(instance, filename): extension = filename.split('.')[-1] filename = "file_%s_1.%s" % (instance.identification, extension) return 'folder/{0}/{1}'.format(instance.user, filename) -
Adding a panel black behind a form
I currently have a form in my app that looks like this: However I would like to add a white panel behind the form, the panel must still show the background behind it When I use the <div class="panel panel-default" style="color: white "> it does not add this Does anyone know how I can add this with HTML / CSS Please see the below code for assistance: {% extends "main/base.html"%} {% block content %} <div class="opacity-50"> <body id="bg" style="background-size: cover; background-repeat: no-repeat;background-image: url('https://images.unsplash.com/photo-1518334792104-db78a16ac8b8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80')";> </body> </div> <div class="panel panel-default" style="color: white "> <from> <div style="text-align: center"> <h1>Sign Up with Shiftly</h1> <p>Please complete the form below carefully, ensure you provide the correct information and documents to avoid your application being delayed.</p> </div> <h2 style="text-align: left; padding-left: 250px">PERSONAL INFORMATION</h2> <br> <div style="text-align: Left; padding-left: 255px"> <div class="row mb-2" style="width: 100%"> <div class="col-6 col-sm-2"> Title {{ form.title }}</div> <div class="col-6 col-sm-3"> Initials {{ form.initials }} </div> <div class="col-6 col-sm-3"> First Name(s) {{ form.firstname }} </div> <div class="col-6 col-sm-3"> Surname {{ form.surname }} </div> </div> <div class="row mb-2" style="width: 100%"> <div class="col-6 col-sm-3"> Preferred Name {{ form.prefferedname }}</div> <div class="col-6 col-sm-2"> Gender {{ form.gender }} </div> <div class="col-6 col-sm-3"> Date Of Birth{{ form.dob }} </div> … -
How can gunicorn handle hundreds of thousands of requests per second for django?
From the docs - How many workers, DO NOT scale the number of workers to the number of clients you expect to have. Gunicorn should only need 4-12 worker processes to handle hundreds or thousands of requests per second. Generally we recommend (2 x $num_cores) + 1 as the number of workers to start off with. From threads, The number of worker threads for handling requests. Run each worker with the specified number of threads. A positive integer generally in the 2-4 x $(NUM_CORES) range. You’ll want to vary this a bit to find the best for your particular application’s workload. Now the question is what no of threads and workers can serve hundreds or thousands of requests per second? Let's say I have a dual-core machine and I set 5 workers and 8 threads. And I can serve 40 concurrent requests? If I am going to serve hundreds or thousands of requests, I'll need a hundred cores? this line is very hard to understand: Gunicorn should only need 4-12 worker processes to handle hundreds or thousands of requests per second. -
Filter products using Category Model in Django
I'm building an ecommerce website and want to filter products using categories but I don't know how to render the products. And add the categories in the navigation bar from where people can navigate to different categories. Here's my views.py file: from django.shortcuts import render from django.views import View from .models import Product, Category class ProductView(View): def get(self, request, *args, **kwargs): products = Product.objects.filter(is_active = True) context = { 'products': products, } return render(request, 'Product/products.html', context) class ProductDetailView(View): def get(self, request, slug): product = Product.objects.get(slug = slug) context = { 'product': product } return render(request, 'Product/productdetail.html', context) class CategoryView(View): def get(self, request): category = Category.objects.all() products = Product.objects.filter(category__slug = slug) context = { 'category': category, 'products':products, } return render(request, 'Product/category.html', context) And this is my models.py from django.db import models from Seller.models import Seller class Category(models.Model): category = models.CharField(max_length = 255) slug = models.SlugField(max_length = 255) def __str__(self): return self.category class Product(models.Model): product = models.ForeignKey(Seller, on_delete = models.CASCADE) title = models.CharField(max_length = 255) image = models.ImageField(upload_to = 'images', null = True, blank = True) file = models.FileField(upload_to = 'files', null = True, blank = True) actual_price = models.PositiveIntegerField(default = '0') selling_price = models.PositiveIntegerField(default = '0') slug = models.SlugField(max_length = 255, … -
How to keep a property value in django.values()?
I have my model as: .... created_at = models.DateTimeField(auto_now_add=True, db_column="order_date", null=True, blank=True) @property def created_date(self): return self.created_at.strftime('%B %d %Y') I want to get created_Date in my views.py data = Subs.objects.values('somevalues','created_date') It throws an error. How to access created_date so that i can use it here. -
Django model allow only once in many
Please excuse the title but I'm not sure howto put this into words. I have a model "card" and a model "computer": class card(models.Model): name=models.CharField( verbose_name = 'Name', max_length=50, null=True, blank=True, ) serial=models.CharField( verbose_name = 'Serial', max_length=50, null=True, blank=True, ) class computer(models.Model): name=models.CharField( verbose_name = 'Name', max_length=50, null=True, blank=True, ) slot1 = models.OneToOneField( 'card', related_name='cardslot1', on_delete=models.SET_NULL, null=True, blank=True, verbose_name = 'Slot 1', ) slot2 = models.OneToOneField( 'card', related_name='cardslot2', on_delete=models.SET_NULL, null=True, blank=True, verbose_name = 'Slot 2', ) (Of course that this computer model is invalid) The cards are unique and should only be allowed to be used in one slot - of any computer. What's the best way to achieve this? I was thinking about a in-between table, something like card n-1 cardcomputer n-1 computer but I'm hoping there's a better way I'm not seeing right now. Thanks