Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Optimizing Django Form/Table Reload for Improved Performance and Minimizing Page Reloads"
1-I'm encountering challenges with page reloading and performance optimization in my Django project. The primary issues involve the reload behavior of a form or table, where the entire page refreshes upon submission. i want only table elements or data will refresh or reload not the whole page will reload.. 2- the second issue is that it is taking too much time to reload or fetch or run queries can we make it faster.. this is my views.py- def Home(request): # Get the filtered data using RocCharge model from filters.py myfilter = Orderfilter(request.GET, queryset=RocCharge.objects.all().select_related('RocCharge')) # Logic for clearing all filter buttons if request.method == 'GET' and 'remove_filter' in request.GET: filter_name = request.GET['remove_filter'] myfilter.form[filter_name].initial = None elif 'remove_all_filters' in request.GET: for filter_name in myfilter.form.fields: myfilter.form[filter_name].initial = None # Showing or getting applied filters data combined_data = myfilter.qs.values( 'srn_no', 'charge_id', 'charge_holder_name', 'date_of_creation', 'date_of_modification', 'date_of_satisfaction', 'amount', 'address', 'existing_old', 'cin__state', 'cin__city', 'cin__company_name', 'cin__company_cin', 'cin__sector', 'cin__industry', ) from_date = request.GET.get('fromdate') to_date = request.GET.get('Todate') if from_date and to_date: combined_data = combined_data.filter(date_of_creation__gte=from_date, date_of_creation__lte=to_date) # download data logic/func.................................. if 'download_xlsx' in request.GET: filtered_data = myfilter.qs.values( 'charge_holder_name', 'date_of_creation', 'date_of_modification', 'date_of_satisfaction', 'amount', 'existing_old', 'cin__state', 'cin__city', 'cin__company_name', 'cin__company_cin', 'cin__sector', 'cin__industry' ) # Convert the filtered data to a DataFrame df = pd.DataFrame.from_records(filtered_data) … -
I am trying to create a virtual environment but its not working. even it exists there
Getting this error I tried at least 20 times but didn't work getting this error. activate : The term 'activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 activate + CategoryInfo : ObjectNotFound: (activate:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Suggestion [3,General]: The command activate was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\activate". See "get-help about_Command_Precedence" for more details. PS C:\djangopracticeset\main\mainenv\scripts> -
Django: Concatenate two manytomany fields in one single field and save it in the database
I have these two models: class Person(models.Model): name = models.CharField(max_length=200) class Project(models.Model): project_info = models.CharField(max_length=200) project_manager = models.ManyToManyField(Person, related_name="project_manager") project_collaborator = models.ManyToManyField(Person, related_name="project_collaborator") I want to save in the database the field "project_info" with this concatenated value: "project_manager & project_collaborator". I tried to override the save method of the Project model: def save(self, *args, **kwargs): self.project_info = self.project_manager + '&' + self.project_collaborator super().save(*args, **kwargs) but it returns me the error "unsupported operand type(s) for +: 'ManyRelatedManager' and 'str'". -
SMTP.starttls() got an unexpected keyword argument 'keyfile' with django 3.2.23 and python 3.12.1
I'm trying to configure my web app to send confirmation emails after registration. I'm using Django 3.2.23 and Python 3.12.1 and my settings are : if 'DEVELOPMENT' in os.environ: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = 'boutiqueado@example.com' else: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASS') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER'). I'm having this error message : TypeError at /accounts/signup/ SMTP.starttls() got an unexpected keyword argument 'keyfile' Request Method: POST Request URL: https://boutique-ado-mike-8ab1d2bb405e.herokuapp.com/accounts/signup/ Django Version: 3.2.23 Exception Type: TypeError Exception Value: SMTP.starttls() got an unexpected keyword argument 'keyfile' Exception Location: /app/.heroku/python/lib/python3.12/site-packages/django/core/mail/backends/smtp.py, line 67, in open Python Executable: /app/.heroku/python/bin/python Python Version: 3.12.1 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python312.zip', '/app/.heroku/python/lib/python3.12', '/app/.heroku/python/lib/python3.12/lib-dynload', '/app/.heroku/python/lib/python3.12/site-packages'] Server time: Thu, 14 Dec 2023 09:57:01 +0000 I checked the EMAIL_HOST_USER and EMAIL_HOST_PASS and both are ok. The pass provided by gmail had spaces but I removed the spaces in the pass. The app is in production and all the vars are in heroku config vars. How can I solve this. I tryed to change EMAIL_USE_TLS = True to EMAIL_USE_SSL = True and port to 465 but the error persists. help please!!! -
Not able insert into Django modeling
my input is using JSON post request { "rawdata": [ { "id": "89729999", "name": "testname", "product": "testproduct", "modified_at": "2023-12-14T03:00:00.000Z", "modified_by": "personname", "asset": { "configname": ["testconfig"], "serialnumber": ["testserialnumber"] "owner": ["owner1","owner2"] } } ] } model.py class Host(models.Model): id = models.CharField(primary_key=True, max_length=15) name = models.CharField(max_length=80) product = models.CharField(max_length=50) modified_at = models.DateTimeField() modified_by = models.CharField(max_length=50) class Hostinfo(models.Model): fk = models.ForeignKey(Host, on_delete=models.CASCADE) ## id parameter_section = models.CharField(max_length=40) parameter = models.CharField(max_length=80) parameter_index = models.IntegerField() ## index value = models.CharField(max_length=200, null=True) modified_at = models.DateTimeField() modified_by = models.CharField(max_length=50) view.py @api_view(('POST',)) def hostrequest(request): data=request.data.get('rawdata') print(data) try: for item in data: host=Host() host.cmdbid = item['cmdbid'] host.name = item['name'] host.product =item['product'] host.modified_at= item['modified_at'] host.modified_by= item['modified_by'] host.save() hostparameter = Hostinfo() for parameter_section in item: if parameter_section != "cmdbid" and parameter_section != "name" and parameter_section != "product" and parameter_section != "modified_at" and parameter_section != "modified_by": detailData = item[parameter_section] for parameter in detailData: parameters = detailData[parameter] for parameter_index in parameters: value = parameters[parameter_index] hostparameter.fk += item['cmdbid'] hostparameter.parameter_section += parameter_section['parameter_section'] hostparameter.parameter += parameter['parameter'] hostparameter.parameter_index += parameter_index['parameter_index'] hostparameter.value += value['value'] hostparameter.save() response_data={"error":False,"Message":"Updated Successfully"} return JsonResponse(response_data,safe=False,status=status.HTTP_201_CREATED) except: response_data={"error":True,"Message":"Failed to Update Data"} return JsonResponse(response_data,safe=False) i executed view script without any issue but i'm only able insert value into host. But not able insert into Hostinfo. Anyone could … -
How can i configure Django-Cors-Header properly
I deployed my django app on fly.io. When accessing api endpoints with swagger, I get this error in the console; " The page at 'https://bookinventory.fly.dev/' was loaded over HTTPS, but requested an insecure resource 'http://bookinventory.fly.dev/api/view/1'. This request has been blocked; the content must be served over HTTPS. Cors has been installed with settings from the docs. I have set; CORS_ALLOW_ALL_ORIGINS = True CSRF_TRUSTED_ORIGINS = [ 'https://bookinventory.fly.dev', 'http://bookinventory.fly.dev'] And the middleware and installed apps has all ben configured for cors -
API login issues
I created API and trying to login user. While 127.0.0.1:8000/api/register works perfectly find but authentication in /api/login error is getting. In settings.py I set auth_user_model = 'account.AppUser' Still I am getting this error: POST /api/login/ HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "non_field_errors": [ "User not found" ] } #account/models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ from django.db import models JOB_TYPE = ( ('M', "Male"), ('F', "Female"), ) ROLE = ( ('employer', "Employer"), ('employee', "Employee"), ) '''class User(AbstractUser): username = None email = models.EmailField(unique=True, blank=False, error_messages={ 'unique': "A user with that email already exists.", }) role = models.CharField(choices=ROLE, max_length=10) gender = models.CharField(choices=JOB_TYPE, max_length=1) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email def get_full_name(self): return self.first_name+ ' ' + self.last_name objects = CustomUserManager() ''' class CustomUserManager(BaseUserManager): use_in_migrations = True """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password=None): """ Create and save a User with the given email and password. """ if not email: raise ValueError('The Email must be set') if not password: raise ValueError('The Password must be set') email = self.normalize_email(email) user … -
Send the values of several columns of the table Django rest framework
i want Send the values of several columns of the table ("id", "meter_id", "State", "date", "VII1", "VII2", "VII3", "VII_avg") here is my code: class VAndI(APIView): def get(self, request): queryset = PowerMeter.objects.all().order_by('-id')[:5].values("id", "meter_id", "State", "date", "VII1", "VII2", "VII3", "VII_avg") serializer = VAndISerializer(instance=queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) but got this ERROR: 'int' object has no attribute 'pk' here is my serializer: class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) class VAndISerializer(DynamicFieldsModelSerializer): class Meta: model = PowerMeter fields = ["id", "meter_id", "State", "date", "VII1", "VII2", "VII3", "VII_avg"] Please note that with this model and serializer, I get the data of all the columns, but in this case, I only want the information of the specified columns. class VAndI(APIView): def get(self, request): queryset = PowerMeter.objects.all().order_by('-id')[:5].values("id", "meter_id", "State", "date", "VII1", "VII2", "VII3", "VII_avg") serializer = VAndISerializer(instance=queryset, many=True) return Response(serializer.data, … -
How to disable all stateful thing in Django?
I need to disable all django things that use default database. Admin, session, messages etc. won't work, but it is acceptable. I want to make my api server fully stateless. P.S. Just turning off all the middlewares and apps does not work. P.S.S. I know I can use FastApi or smt, but i want django(drf) I tried remove all the middlewares and apps, but when i try to go my pages i got an error INSTALLED_APPS = [ # 'django.contrib.admin', # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.messages', # 'django.contrib.staticfiles', "restapi.apps.RestapiConfig", "rest_framework", "corsheaders", ] MIDDLEWARE = [ # 'django.middleware.security.SecurityMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', # 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'django.contrib.messages.middleware.MessageMiddleware', # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Error: RuntimeError at /api/savedfilters/ Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Request Method: GET Request URL: http://127.0.0.1:8000/api/savedfilters/ Django Version: 4.2.6 Exception Type: RuntimeError Exception Value: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Exception Location: C:\Users\Sergey\AppData\Local\pypoetry\Cache\virtualenvs\ndbackend-_IiuFZN4-py3.10\lib\site-packages\django\db\models\base.py, line 134, in __new__ Raised during: restapi.views.SavedFilterView Python Executable: C:\Users\Sergey\AppData\Local\pypoetry\Cache\virtualenvs\ndbackend-_IiuFZN4-py3.10\Scripts\python.exe Python Version: 3.10.0 -
Warning: Root no database_url environment variable set and so no databases set up
I am a student taking up on full-stack development. I am trying to deploy my Django app with sqlite3, to Heroku. as it's for my course exercise, i am not changing sqlite3 to postgre. My code shows error when i add below in settings.py """ Django settings for recipe_project project. Generated by 'django-admin startproject' using Django 4.2.7. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ import os from pathlib import Path # 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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY','django-insecure-ml49cp(e)=yakpevh4xz)3w)6xuq6kv7g&3^xf^)gr-n3&p#%9') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # recipe_project-related apps 'recipe', 'user', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'recipe_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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', ], }, }, ] WSGI_APPLICATION = 'recipe_project.wsgi.application' … -
Converting Boolean value from DB to Bootstrap switch input - Django
I have a boolean field in the database - emails_allowed. This is reflected in the user profile page as a bootstrap 5 switch input To represent the current value in the database I am using the template language in the following manner - <input class="form-check-input" style="margin-left: -1.5em;" type="checkbox" id="email-allowed" {{ profile.email_allowed|yesno:"checked,unchecked" }}> I was expected the template language to merely output checked or unchecked as a string. Instead it is creating a HTML attribute called checked or unchecked as shown below - <input class="form-check-input" style="margin-left: -1.5em;" type="checkbox" id="email-allowed" checked=""> As a result, I am unable to change the state of the switch as it is permanently either checked or unchecked. Has anyone come across this issue? Any suggestions on how to solve this is greatly appreciated. Thanks in advance -
getting issues when making multipart/form-data request in jmeter
getting issues when making multipart/form-data request in jmeter I am getting status code 201. but when downloading it showing unsupported formate, --AaB03x content-disposition: form-data; name="file"; filename="strawberryamp_kiwi.jpg" Content-Type: image/jpeg Content-Transfer-Encoding: binary D:\appointy\strawberryamp_kiwi.jpg --AaB03x content-disposition: form-data; name="file_type" IMAGE --AaB03x content-disposition: form-data; name="is_public" true --AaB03x content-disposition: form-data; name="owner" "48a74388-6f29-45d2-b2fc-b6b27d64f4e0" --AaB03x-- on postman everything is working fine. but not on jmeter expecting proper downloading after sending the file -
I want to know the hashed version of the password that is generated when using the user.set_password(pasword) method in Django and print that password
I want to know the hashed version of the password that is generated when using the user.set_password(password) method in Django and how to print that password? I'm trying to understand how Django's user.set_password(password) method works. Specifically, I'm interested in the generated hashed password, which is a secure representation of the plain text password. Can anyone explain how this method stores the password securely and how the hashed password can be used for authentication? code I am using: password = sellerForm.data['password'] user = User.objects.create(username=email,email=email,first_name=first_name,last_name=last_name,is_superuser=0,is_staff=0,is_active=1) user.set_password(password) user.save() See the actual hashed value of the password printed to the console or output. Understand how Django stores passwords securely using this method. Learn how the hashed password is used for authentication purposes. -
Update view with django-formtools
I implemented django-formtools SessionWizardView with a navbar, so I can jump between steps if I want to update existing instances. My problem is, if I want to edit an instance I have to submit all forms, so they are valid and render_done is called. -
Extract Individual URL Request Counts
I have a Django app running with NGINX as a reverse proxy. My NGINX configuration looks like this: server { listen 8080 default_server; listen [::]:8080 default_server; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; } location /metrics { stub_status on; } } I'm using the NGINX Prometheus Exporter to monitor NGINX metrics, and I would like to extract the number of requests for individual URLs. For instance, if I have two URLs, /job1 and /job2, I want to see the following metrics: number_of_requests{path:/job1} 20; number_of_requests{path:/job2} 30; Is there a way to achieve this? Thanks in advance for your help! -
Django admin doesn't load Static files but folder is there in Azure cloud
I deployed a Django project in an Azure web App which doesn't load the styles and static files in admin interface. According to this posts Django doesn't serve static files in production (when Debug is false), it suggests to configure the web server to the static files (Apache or Nginx). The thing is, how to show the django admin static files in an Azure web App? Thanks. -
Django Logout is not deleting cookie from browser and casing error while try to log in for second time
Here is code for login and logout view. When try to log in for first time cookie is set but on logout it doesn't update cookie or delete it from browser causing error in login attempt. @csrf_exempt def post(self, request): try: email = request.data.get('email') password = request.data.get('password') user = authenticate(request, username=email, password=password) if user is not None: request.session.set_expiry(86400*30) # 30 days login(request, user) user_obj = Customer.objects.get(email=email, password=password) return Response({'user_id': user_obj.id}, status=status.HTTP_200_OK) else: return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) except Exception as e: return Response("Internal Server Error",status=status.HTTP_500_INTERNAL_SERVER_ERROR) class LogoutView(APIView): @csrf_exempt def post(self, request): try: logout(request) # delete cookie response = JsonResponse({'message': 'Logout successful'}, status=status.HTTP_200_OK) response.delete_cookie('sessionid') response.delete_cookie('csrftoken') return response except Exception as e: print('error logout ==>',e) return Response("Internal Server Error",status=status.HTTP_500_INTERNAL_SERVER_ERROR)``` -
how do I turn {{ }} into a link? [closed]
how can I turn this post title into a link? {{post.title}} I tried this but it does not turn the post title itself into a link it makes a new link with the title <a href="{% url 'detail' post.id %}">{{post.title}}</a> it looks like this the title does not turn into a link Thanks in advance -
How to give a user an authentication token with DRF to use in APIs based only off their username found in headers (no password)
To reach this token generating API on the web the user will have to first authenticate with Oauth2 with their company username/password. This username is now in the header as USERINFO-cn and I can access it with user = request.META['USERINFO-cn'] I want to take the username and assign that user a unique token. I've tried following the example in the django-rest-framework documentation on generating tokens with a customized version of obtain_auth_token. This code gives an error since Token.objects.get_or_create(user=user) is obviously expecting more than just a username. from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response class CustomAuthToken(ObtainAuthToken): def get(self, request, *args, **kwargs): user = request.META['USERINFO-cn'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user': user }) I know this method may be confusing but basically I want internal users at my company to be able to use other APIs without exposing their password (just a token) but I will at least be able to determine which users are calling APIs based off the token. -
render deploy error return: Not Found: /static/ (folder)
I am working on a web page. I have done two deployments in Render. In one deployment I can't see the images, not load images but yes load css and bootstrap. And in the second deployment it does not detect the static folder, so the site works showing the images but I cannot see css or bootstrap working. Not Found: /static/proyectowebapp/vendor/bootstrap/js/bootstrap.bundle.min.js 127.0.0.1 - - [13/Dec/2023:22:28:21 +0000] "GET /static/proyectowebapp/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 3385 "https://service-new-2mtd.onrender.com/blog/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" Not Found: /static/proyectowebapp/css/gestion.css 127.0.0.1 - - [13/Dec/2023:22:28:21 +0000] "GET /static/proyectowebapp/css/gestion.css HTTP/1.1" 404 3301 "https://service-new-2mtd.onrender.com/blog/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" What am I doing wrong? I want to deploy my django project on the render page -
Django filter from the model field
I want to make a filter on the site by author for example, I made a language filter like this: models.py CATEGORIES = ( (1, 'Russian'), (2, 'English') ) class Book(models.Model): title = models.CharField(max_length=300) lang_category = models.IntegerField(choices=CATEGORIES, default=1, db_index=True) views.py def index(request, tag_slug=None): books = Book.objects.filter(is_active=True) form = BookFilterForm(request.GET) filtered_queryset = BookFilter(request.GET, queryset=books) if form.is_valid(): if form.cleaned_data['lang_category']: books = books.filter(lang_category__icontains=form.cleaned_data['lang_category']) forms.py class BookFilterForm(forms.Form): LANG_CHOICES = [ ('', 'All languages''), (1, 'Russian'), (2, 'English') ] lang_category = forms.ChoiceField(required=False, choices=LANG_CHOICES, widget=forms.Select(attrs={'class': 'form-select'}), label='Select a language') this works for me, but there is another field that I want to filter by: models.py class Book(models.Model): title = models.CharField(max_length=300) lang_category = models.IntegerField(choices=CATEGORIES, default=1, db_index=True) **author_book = models.CharField(max_length=300)** tell me how you can filter by this type of field I tried this and of course it didn't work: forms.py author_book = forms.ChoiceField(choices=Book.author_book, required=False, widget=forms.Select(attrs={'class': 'form-select'}), label='Author') -
Unable to Run Python HTTP Server on Port 8001 - Need Help in Creating a Minimal, Reproducible Example
Question: I'm encountering an issue while trying to run a Python HTTP server on port 8001 using the command python -m http.server 8001. The server starts, but I'm unable to access it. I've ruled out common problems like port availability and firewall settings. Here's what I've tried: Ensured that port 8001 is not in use by another process. Checked firewall settings to allow traffic on port 8001. Double-checked network configuration. Despite these checks, the issue persists. I'd like to seek help on Stack Overflow, and I want to follow the guidelines for creating a minimal, reproducible example. Can someone guide me on how to structure my question effectively? I want to provide a clear and concise example that others can easily understand and use to help me troubleshoot this problem. Thanks in advance! -
Submit button has no action in Django
I have 3 models in my project and no form is showing any action when the submit button is pressed after putting all the inputs of the form. forms.py class BlogForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'slug', 'thumbnail', 'body', 'status', 'is_subsriber', 'meta', 'author'] models.py class BlogPost(models.Model): author = models.ForeignKey(Author, on_delete = models.CASCADE) title = models.CharField(max_length = 999, unique = True) slug = models.SlugField(max_length = 999, unique = True) thumbnail = ProcessedImageField(upload_to='article', format='JPEG', options={'quality': 60}) body = CKEditor5Field(config_name='extends') meta = models.TextField() status = models.CharField(max_length = 10, choices = blogstatus, default = "DF") is_subsriber = models.BooleanField(default = False) created_on = models.DateTimeField(auto_now_add = True) published_on = models.DateField(auto_now = True) modified_on = models.DateField(auto_now = True) views.py def article_form(request): if request.method == "POST": form = BlogForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("home") else: form = BlogForm() return render(request, 'article/post-form.html', {"form":form}) index.html <form class="form" method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Publish</button> </form> This is just one model and its form. I've tried using action in the html form but it still doesn't work. -
Add like count to a social network
I am almost done with my project, I completed every step and now I am stuck at the very least, I am not able to show the like count per post in my project. views.py def index(request): posts = Post.objects.all().order_by("date").reverse() paginator = Paginator(posts, 10) number = request.GET.get('page') currentPosts = paginator.get_page(number) likeList = [] try: for like in likes: if like.userLiking.id == request.user.id: likeList.append(like.postLiked.id) except: likeList = [] return render(request, "network/index.html", { "currentPosts": currentPosts }) index.js function like(id, likeList) { if (likeList.indexOf(id) >= 0) { fetch(`/remove/${id}`) .then(response => response.json()) .then(result => { console.log(result), window.location.reload() }) } else { fetch(`/add/${id}`) .then(response => response.json()) .then(result => { console.log(result), window.location.reload() }) } } index.html <div> <ul style="list-style: none"> {% for post in currentPosts %} <li><a href="{% url 'profile' post.user.id %}"> From: {{ post.user }}</a></li> <li><h5 id="description{{ post.id }}">{{ post.description }}</h5></li> <li>{{ post.date }}</li> {% if user.is_authenticated and user == post.user %} <button id="editButton{{ post.id }}" onclick="edit({{ post.id }})">Edit</button><br> <div id="text{{ post.id }}"></div> <div id="save{{ post.id }}"></div> {% endif %} {% if user.is_authenticated %} {% if post.id not in likeList %} <button class="likebtn" id="{{ post.id }}" onclick="like({{ post.id }}, {{ likeList }})">Like</button><br> {% else %} <button class="unlikebtn" id="{{ post.id }}" onclick="like({{ post.id }}, {{ likeList … -
error when return serializer data in Django rest framework
when i try send data with this code: class MeterData1(APIView): def get(self, request, formate=None): queryset = PowerMeter.objects.all(id=10) serializer = PowerMeterSerializer(data=queryset,many=True) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I encounter this error: { "non_field_errors": [ "Invalid data. Expected a dictionary, but got QuerySet." ] } and this is my serializer : class PowerMeterSerializer(serializers.ModelSerializer): class Meta: model = PowerMeter fields = '__all__' and model: class PowerMeter(models.Model): meter_id = models.CharField(max_length=127) State = models.ForeignKey(State, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True, blank=True) VII1 = models.PositiveIntegerField(default=0, blank=True) VII2 = models.PositiveIntegerField(default=0, blank=True) VII3 = models.PositiveIntegerField(default=0, blank=True) VII_avg = models.PositiveIntegerField(default=0, blank=True) Vln1 = models.PositiveIntegerField(default=0, blank=True) Vln2 = models.PositiveIntegerField(default=0, blank=True) Vln3 = models.PositiveIntegerField(default=0, blank=True) Vln_avg = models.PositiveIntegerField(default=0, blank=True) I1 = models.PositiveIntegerField(default=0, blank=True) I2 = models.PositiveIntegerField(default=0, blank=True) I3 = models.PositiveIntegerField(default=0, blank=True) I_avg = models.PositiveIntegerField(default=0, blank=True) P1 = models.PositiveIntegerField(default=0, blank=True) P2 = models.PositiveIntegerField(default=0, blank=True) P3 = models.PositiveIntegerField(default=0, blank=True) P_total = models.PositiveIntegerField(default=0, blank=True) Q1 = models.PositiveIntegerField(default=0, blank=True) Q2 = models.PositiveIntegerField(default=0, blank=True) Q3 = models.PositiveIntegerField(default=0, blank=True) Q_total = models.PositiveIntegerField(default=0, blank=True) S1 = models.PositiveIntegerField(default=0, blank=True) S2 = models.PositiveIntegerField(default=0, blank=True) S3 = models.PositiveIntegerField(default=0, blank=True) S_total = models.PositiveIntegerField(default=0, blank=True) PF1 = models.PositiveIntegerField(default=0, blank=True) PF2 = models.PositiveIntegerField(default=0, blank=True) PF3 = models.PositiveIntegerField(default=0, blank=True) PF_totalMax_Demand_import = models.PositiveIntegerField(default=0, blank=True) Max_Demand_export = models.PositiveIntegerField(default=0, blank=True) Current_Demand = models.PositiveIntegerField(default=0, blank=True) Frequency = models.PositiveIntegerField(default=0, …