Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image is not uploading to the specific destination
I tried several ways to upload images to a specific destination. Showing no error but the image is not uploading to the destination. views.py from django.views.generic.edit import CreateView from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['name', 'weblink', 'image'] success_url = reverse_lazy('posts') template_name = 'base/post.html' def form_valid(self, form): # form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user return super().form_valid(form) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): name = models.CharField(max_length=200) weblink = models.CharField(max_length=200) image = models.ImageField(default='default.png', upload_to='uploads/%Y/%m/%d/') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'Added {self.name} Profile' urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ..... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I added also the media root and URL in the settings file. I didn't any clue but unable to upload the file to the specific location. -
How can I make django model in this situation?
I make a stock market project using django. So I want to make 2 database table. table stocklist (ticker, name) table stockPrice (code, date, price, open, high, close etc...) I want to make second table name is stock ticker. so I though this is many to one relation. And I made django model.py class StockList(models.Model): ticker= models.CharField(max_length=10,primary_key=True) company = models.CharField(max_length=50) last_update = models.DateTimeField() class stockPrice(models.Model): ticker = models.ForeignKey('stockList', on_delete=models.CASCADE) date = models.DateTimeField() open = models.FloatField() high =models.FloatField() low = models.FloatField() close = models.FloatField() diff = models.FloatField() volume = models.FloatField() But it isn't work. How I make django model? And is it many to one relation? Thank you. -
Check if current user email ends with
I want to check if the current logged in user email ends with a certain string. I tried to do request.user.email__endswith ... but that doesn't work. I know you can do User.objects.filter(email__endswith) But how do I do that in the view with the current user? -
Django: How to handle 'dynamic' ModelChoiceField forms?
I'm working on a form with 2 fields from 2 different models linked together. See below : class FirstModel(models.Model): name = models.CharField(max_length=32) class SecondModel(models.Model): name = models.CharField(max_length=32) first_model = models.ForeignKey(FirstModel, on_delete=models.CASCADE) I want the user to select a FirstModel with a first widget. And a SecondModel using a second widget only filled with SecondModel that match the FirstModel that the user selected. My idea: using two ModelChoiceField with all the data in it and filter in the browser using javascript, but I can't find any way to do it. What am I doing wrong ? -
from .exceptions import InvalidKeyError ModuleNotFoundError: No module named 'jwt.exceptions'
I am trying to send an email verification link to a registered user but i keep getting this error, i dont know why but anytime i send a post request to this endpoint i keep getting this error Internal Server Error: /auth/register Traceback (most recent call last): File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/SRC/users/views.py", line 28, in post print(token) File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/tokens.py", line 80, in __str__ from .state import token_backend File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/state.py", line 3, in <module> from .backends import TokenBackend File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/rest_framework_simplejwt/backends.py", line 3, in <module> from jwt import InvalidAlgorithmError, InvalidTokenError, algorithms File "/mnt/c/Users/Somtochukwu/Desktop/cultural-exchange/proj/lib/python3.8/site-packages/jwt/algorithms.py", line 5, in <module> from .exceptions import InvalidKeyError ModuleNotFoundError: No module named 'jwt.exceptions' Here is my views.py class RegisterView(GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() user_data = serializer.data user = … -
Upper index does not seem to work with iexact Django field lookup
I have some references (strings) that I want to use to filter a query with a case-insensitive exact match. To do so, I used iexact Django field lookup. Model.objects.filter(column1__iexact=reference) Since I have a very large number of rows on that table, I wanted to create an index to speed up the query. Django uses the UPPER function to perform the iexact lookup. So I created the following migration (DB is Postgresql): class Migration(migrations.Migration): dependencies = [ ('app', 'previous_migr'), ] operations = [ migrations.RunSQL( sql=r'CREATE INDEX "index_name_idx" ON "table" (UPPER("column1") );', reverse_sql=r'DROP INDEX "index_name_idx";' ), ] Unfotunately, this index does not seem to be used while querying. Why do I think this ? Here are the request times with : iexact ~= 17s exact < 1s Here is the generated (truncated) SQL query : SELECT "table"."id" FROM "table" WHERE ( "table"."is_removed" = false AND (UPPER("table"."column1"::text) = UPPER('blablabla') OR UPPER("ordering_order"."column2"::text) = UPPER('blablabla'))) ORDER BY "table"."id" ASC ) Is there something wrong with my migration ? Any other option to do this query with good performance ? -
Can I use redis as a backend proxy server for storing WebSocket connection instances of a Chat Application
I am building a chat application using Django Channels and REST framework as the backend and a React frontend. I want to make sure each chat room has a single websocket connection. How can Redis serve as a Proxy server and help achieve this goal. -
how i can add update user data using django-allauth
how i can add update user data using django-allauth , i want allow users to change first name and 2nd name after signup so how to do that ? my code | models.py : class Profile(models.Model): first_name = models.CharField(max_length=125) last_name = models.CharField(max_length=125) user_pic = models.ImageField(upload_to='images/',null=True, blank=True) def __str__(self): return self.first_name forms.py : # update user data Form class ProfileForm(forms.ModelForm): first_name = forms.CharField(required=False,label='First Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter First Name '}) ) last_name = forms.CharField(required=False,label='Last Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter Second Name '}) ) user_pic = forms.ImageField(required=True,label='Your photo') class Meta: model = User fields = ('first_name', 'last_name','user_pic') def save(self, commit=True): user = super(ProfileForm, self).save(commit=False) if commit: user.save() return user views.py : # Edit Profile View @login_required(login_url='accounts/login/') class ProfileView(UpdateView): model = User form_class = ProfileForm success_url = reverse_lazy('profile') template_name = 'account/profile.html' def get_object(self, queryset=None): return self.request.user html page : <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" style="background-color:#7952b3" value="update"> </form> when i open page in browser it don't show the form field but the update button appear -
django.contrib.auth.models.AnonymousUser object at 0x000001F13FE409A0 "Mpesa.Paid_user" must be a "User" instance
I would like to save to the database the currently logged-in user but it keeps throwing out the error above, any insight would be appreciated. below are some snippets. views.py our_model = Mpesa.objects.create( Paid_user = request.user, MpesaReceiptNumber = mpesa_receipt_number, PhoneNumber = phone_number, Amount = amount, TransactionDate = aware_transaction_datetime, ) our_model.save() models.py class Mpesa(models.Model): Paid_user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE) MpesaReceiptNumber = models.CharField(max_length=15, blank=True, null=True) PhoneNumber = models.CharField(max_length=13, blank=True, null=True) Amount = models.IntegerField(blank=True, null=True) TransactionDate = models.DateTimeField(blank=True, null=True) Completed = models.BooleanField(default=False) -
i want to save my check box value of my form to my Django database
I am using form in my Django Web app and The form consist of checkboxes but when the the check boxes are marked true and the form is submitted the check box chenges are not marked in the databaseenter image description here here is my models.py my Help model is not sending the check box values to Database # Create your models here. class Contact(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) phone = models.CharField(max_length=12) desc = models.TextField() date = models.DateField() def __str__(self): return self.name class Help(models.Model): name = models.CharField(max_length=122) address = models.TextField() phone = models.CharField(max_length=12) bed = models.BooleanField("bed",default=False) oxygen = models.BooleanField("oxygen",default=False) plasma = models.BooleanField("plasma",default=False) date = models.DateField() def __str__(self): return self.name HERE IS MY views.py from django.shortcuts import render import requests from datetime import datetime from webapp.models import Contact from webapp.models import Help from django.contrib import messages # Create your views here. def index(request): return render(request,'index.html') def contact(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') desc = request.POST.get('desc') contact =Contact(name=name,email=email,phone=phone,desc=desc,date=datetime.today()) contact.save() messages.success(request,'Your message has been sent') return render(request,'contact.html') def help(request): if request.method == "POST": name = request.POST.get('name') address = request.POST.get('address') phone = request.POST.get('phone') plasma = request.POST.get('plasma') oxygen = request.POST.get('oxygen') bed = request.POST.get('bed') if plasma … -
How do I connect a Django app to Postgresql inside Docker?
I'm trying to run a django app from Docker container but I'm facing issues when connecting to a Postgresql -database. This is my docker-compose.yml: version: "3.8" services: app: build: . environment: PYTHONUNBUFFERED: 1 DATABASE_URL: postgres://$DATABASE_USER:$DATABASE_PASSWORD@$DATABASE_HOST:$DATABASE_PORT/$DATABASE_NAME env_file: .env volumes: - .:/data ports: - 8000:8000 image: test:django container_name: tes_container command: python manage.py runserver 0.0.0.0:8000 depends_on: - db db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data env_file: .env environment: - POSTGRES_DB=$DATABASE_NAME - POSTGRES_USER=$DATABASE_USER - POSTGRES_PASSWORD=$DATABASE_PASSWORD container_name: postgres_db This is my .env: DEBUG=on SECRET_KEY=mysecret # Database settings DATABASE_NAME=postgres DATABASE_USER=postgres DATABASE_PASSWORD=postgres DATABASE_HOST=localhost DATABASE_PORT=5432 Every time I run docker-compose run --rm app python manage.py migrate I get this error: psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: .... django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) … -
How can I solve this : JSONDecodeError at /update_item Expecting value: line 1 column 1 (char 0)
This is my views.py How can i solve this.Anyone please help!!! JSONDecodeError at /update_item Expecting value: line 1 column 1 (char 0) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) url = 'http://httpbin.org/status/200' r = requests.get(url) if 'json' in r.headers.get('Content-Type'): js = r.json() else: print('Response content is not in JSON format.') js = 'spam' and this is my cart.js I hope anybody will help me If you want to check my whole project code I am ready to show var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = 'update_item' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) … -
Django CORS requests creating 403 Forbidden Error only on server
I have an application which uses Django for the backend and react for the frontend so I setup django-cors-headers. When I tested the application locally with the settings I added, I had no issues. But I deployed to my server, I kept getting 403 error on API requests (except GET requests). Below is my settings.py file (only the relevant settings): import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<my-secret-key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['<my-server-ip>'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend', 'services', 'rest_framework', 'dj_rest_auth', 'rest_framework.authtoken', 'user', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) } CORS_ALLOWED_ORIGINS = [ "http://<my-server-ip>:8000", "http://localhost:8000", "http://127.0.0.1:8000", "http://0.0.0.0" ] CSRF_TRUSTED_ORIGINS = [ "http://<my-server-ip>:8000", "http://localhost:8000", "http://127.0.0.1:8000", "http://0.0.0.0" ] CORS_ALLOW_CREDENTIALS = True I make the API requests from React using axios … -
Django Serializer how to hide/show related fields
I have three 4 Model Quiz, Question, Multichoice, and Answers When using serializer to display a Quiz Data, the data is displayed as follows [ { "id": 333, "title": "Practice Exam : Class 12 Physics (Current Electricity) ", "description": "", "url": "b75038cf-e309-45da-9a91-02a4ff1ea231", "category": 52, "random_order": true, "pass_mark": 0, "draft": false, "durationtest": "10:00", "get_questions": [ { "id": 6155, "content": "<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">The equivalent resistance between P and Q in the given figure is approximately:&nbsp;</span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(A) 10&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(B) 5&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(C) 6&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(D) 20&Omega; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;B</span></span></p>\r\n<gdiv></gdiv>", "category": 52, "sub_category": 178, "getanswers": [ { "id": 17065, "content": "A", "correct": false, "question_id": 6155, "question": 6155 }, { "id": 17066, "content": "B", "correct": true, "question_id": 6155, "question": 6155 }, { "id": 17067, "content": "C", "correct": false, "question_id": 6155, "question": 6155 }, { "id": 17068, "content": "D", "correct": … -
Django workaround to use window function call in an aggregate function?
I'm trying to calculate customer order frequency. First use a window function to get the previous order date then annotate the days since the last order. from django.db.models import Avg, F, Window from django.db.models.functions import ExtractDay, Lag, TruncDate orders = ( Order.objects .annotate( prev_order_date=Window( expression=Lag('paid_at', 1), partition_by=[F('customer_email')], order_by=F('paid_at').asc(), ), days_since_last=ExtractDay( TruncDate('paid_at') - TruncDate('prev_order_date') ), ) ) Then group by customer_email before calculating the average frequency. customer_data = ( orders.values('customer') .annotate(avg_frequency=Avg('days_since_last')) ) Unfortunately this throws an error. Does anyone know of a workaround or know of an alternate way to calculate the average frequency? psycopg2.errors.GroupingError: aggregate function calls cannot contain window function calls -
Django request.session empty between views using JWT
I'm having trouble with using request.session in Django (using JWT for authentification) to keep some user's parameters. I am well aware I have to specify INSTALLED_APPS = [ 'django.contrib.sessions', MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', but I think there is something I don't get and I think it is related to the fact I am using JWT. I can store some data in request.session when doing an API call (view) but it won't exist anymore on another one. @api_view(["POST"]) def updateFilters(request): # récupère les filtres dans la session filtres = request.data for key, value in filtres.items(): request.session[key] = value #it's ok here return Response("Filters updated") @api_view(['POST']) def testAPI(request): #empty here !!!!! print(request.session.items()) return Response("Test") Could someone explain what is wrong and maybe propose a solution ? Thank you for your help -
Django - pagination based on search criteria
I am having issues getting results when clicking on page 2 and above - most likely due to url issues. I have a list of names and if I search on e.g. "John" I want them to be separated by pages if number of names > e.g. 10. My Views are as follows: (searching works fine) def name_search(request): if 'q' in request.GET: q=request.GET.get('q', '') pvt_list = pvt_data.objects.filter(full_name__icontains=q) #Pagination p = Paginator(pvt_list, 10) # Show 10 contacts per page. page_num = request.GET.get('page', 1) try: page = p.page(page_num) except PageNotAnInteger: page = p.page(1) except EmptyPage: page = p.page(1) context = {'items' : page} return render(request, 'home/name_search.html', context) else: return render(request, 'home/name_search.html') My urls.py file is urlpatterns = [ ... path('name_search', views.name_search, name='name_search'), ... ] My html file is {% for pvt in items %} {{ pvt.full_name }} {% endfor %} <div class="pagination"> <span class="step-links"> {% if items.has_previous %} <a href="?page={{ items.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ items.number }} of {{ items.paginator.num_pages }}. </span> {% if items.has_next %} <a href="?page={{ items.next_page_number }}">next</a> {% endif %} </span> </div> When I search, I get the following link 'http://127.0.0.1:8000/name_search?q=John' with the first 10 names correct. When I click on next button I get … -
Query data that belongs to a certain user and compare to similar data from another user
I am a month into working with django and this is giving me trouble.I have a table Invoice that stores invoices .The contents for one invoice are structured as below.The invoices have an appointment field that has a field doctor that stores details of the doctor belonging to the appointment.The invoice also has a doctor_amount which belongs to the doctor in the appointment.I need to get all the doctor_amounts that belong to one doctor and sum them.I then need to find the doctor who has the most amount.I have tried a lot and do not know which attempt is even close so I can put here.So I will just leave it open so I can get independent insight. I will really appreciate the help. { id:1, status: "cleared", appointment:{ id: 3, doctor:{ id: 10, name: "kev", } amount: 10000, doctor_amt: 9000, } } views.py class TopDoctorView(APIView): def get(self, request, format=None): all_invoices = Invoice.objects.all() serializers = InvoiceSerializer(all_invoices, many=True) try: result = {} invoices = serializers.data result = res return Response(result, status=status.HTTP_200_OK) except Exception as e: error = getattr(e, "message", repr(e)) result["errors"] = error result["status"] = "error" return Response(result, status=status.HTTP_400_BAD_REQUEST) -
ESP8266 not connecting to django server
I've created a local server on my pc with django and im trying to send a GET request from my esp8266 01 module which just gives a message and a POST request which send data that is stored in a JSON file. The server works fine with postman but doesnt connect with a esp. The http request gives error code -1 This is code only for GET ESP Code: #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> ESP8266WiFiMulti WiFiMulti; void setup() { Serial.begin(115200); // Serial.setDebugOutput(true); Serial.println(); Serial.println(); Serial.println(); for (uint8_t t = 4; t > 0; t--) { Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush(); delay(1000); } WiFi.mode(WIFI_STA); WiFiMulti.addAP("username", "password"); } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { WiFiClient client; HTTPClient http; Serial.print("[HTTP] begin...\n"); if (http.begin(client, "http://127.0.0.1:8000/polls/")) { Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error if (httpCode > 0) { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { String payload = http.getString(); Serial.println(payload); } } else { … -
Django login required error ERR_TOO_MANY_REDIRECTS
My django application worked fine before using LoginRequiredMiddleware, after I used LoginRequiredMiddleware i have got this error. This page isn’t working 127.0.0.1 redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'login_required.middleware.LoginRequiredMiddleware', # 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REPORT_BUILDER_ASYNC_REPORT = True WSGI_APPLICATION = 'mymachine.wsgi.application' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'index' LOGOUT_REDIRECT_URL = 'login' LOGIN_URL = 'login' CSRF_COOKIE_HTTPONLY = False url.py urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('', IndexView.as_view(), name='index'), ] view.py class LoginView(CreateView): """ Login """ template_name = "registration/login.html" defaults = dict() def __init__(self, **kwargs): super(LoginView, self).__init__(**kwargs) def on_create(self, request, *args, **kwargs): return render(request, self.template_name, self.defaults) def init_component(self, request): logout(request) self.defaults['name_space'] = reverse('auth') self.defaults['form'] = LoginForm def get(self, request, *args, **kwargs): self.init_component(request) return self.on_create(request, *args, **kwargs) def post(self, request, *args, **kwargs): form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user: login(request, user) request.session["company_id"] = 1 return redirect(settings.LOGIN_REDIRECT_URL) elif user is None: context = {'name_space': reverse('auth'), 'form': LoginForm, 'message': _("username or password is incorrect"), 'add': 'try Again'} return render(request, 'registration/login.html', context) This is the url that appears in chrome. http://127.0.0.1:4050/login/?next=/login/ I have tried must of the answers in the … -
Django: how to refresh html content on new database entry
I am developing a MQTT Dashboard app with django. I have a mqtt thread running in background, periodically polling for data from remote device and saving it as a database (MariaDB) row. I also have a view that displays this row in simple table. Now, what I want to do is to refresh this view (without page reload) when new data appears and my question is how to do that. I thought of two different approaches: Use JS's setInterval triggering ajax call to periodically refresh content. Problem here is that I'm not really proficient with JavaScript nor jQuery so I would love to get simple example how to do that Somehow refresh data from within on_message function which is called when mqtt gets new data. Problem here is that I have no clue if it is even possible I would appreciate any explanation of above or even more some description of different, more proper way to do that. Here is my code: part of template with content i want to refresh: <div class="row mb-4 justify-content-center text-center"> <h1 class="text-uppercase text-white font-weight-bold">{% translate "Parameters" %}</h1> <table id="device-parameters-table"> <thead> <tr> <th scope="col">{% translate "Parameter" %}</th> <th scope="col">{% translate "Value" %}</th> <th scope="col">{% translate … -
In my form there is an image upload section. If user not upload any file, then it gives MultiValueDictKeyError. How to get rid of it?
I am working on a project for a Django web-based application. In this project, there is a section in which I take info from the user through an HTML form. I added a section "image upload " but it gives a MultiValueDictKeyError error when the user does not upload any file. I tried this but not working for me. This is error section : error image This is my addpost.html section. It consists of a form through which, I am taking info. <form action="{% url 'addpost' %}" method='POST' enctype="multipart/form-data" novalidate> {% include 'includes/messages.html' %} {% csrf_token %} {% if user.is_authenticated %} <input type="hidden" name="user_id" value="{{user.id}}"> {% else %} <input type="hidden" name="user_id" value="0"> {% endif %} <div class="row "> <div class="tex-center"> <div class="row"> <div class="col-md-6 text-left"> <div class="form-group name"> <input type="text" name="author" class="form-control" placeholder="Author" {% if user.is_authenticated %} value="{{user.first_name}}" {% endif %} readonly> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="title" class="form-control" placeholder="title" required> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="location" class="form-control" placeholder="location" required> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="short_desc" class="form-control" placeholder="Write short description" required> </div> </div> <div class="col-md-12"> <div class="form-group message"> <textarea class="form-control" name="full_desc" placeholder="Write full description"></textarea> </div> </div> <input type="file" … -
Django static folder works on a local server but doesn`t work on the remote server
Django static folder works on a local server but doesn`t work on the remote server. What could be the reason? -
Django Prefecth - call root elements field in filter
Here is my code, I am retrieving a Feed and all related data using the query. I am also checking if the user who is retrieving the feed is also a friend of the user who posted the feed. For friend relationships, I am using the Friends model. viewer_id and feed_id will be given by the system. I want to replace ?????? with a field from Feed model (like user_id who posted the Feed) feed = Feed.objects.select_related( 'user_info', 'images' ).prefetch_related( 'tags', Prefetch( "friends_set", queryset=Friends.objects.filter(user=viewer_id, follows=??????), to_attr="friends" ), ).get(id=feed_id) -
Django: how to add a step among the auth login code
I'm building out my first Django Project, and I'm always grateful that authentication steps are provided in modern frameworks, but I'm having trouble seeing how/where to customize the login process to do an additional step behind the scenes. I followed a tutorial to use the Django authentication, and everything is working great. I made a registration/login.html page that includes 'next' for where to take the users. I include the Django urls for authentication in mysite/urls.py: urlpatterns = [ path('familytree/', include('familytree.urls')), path('admin/', admin.site.urls, name='admin'), path('accounts/', include('django.contrib.auth.urls')), ] In settings.py, I specify that I want users to go to the dashboard page after logging in: LOGIN_REDIRECT_URL = 'dashboard' LOGOUT_REDIRECT_URL = 'landing' The question: I'd like to add one other step: after a user successfully authenticates, I'd like to make a record in a new logins table, and then let them continue on to the dashboard. Where's the right place to add this step? At first I was thinking I could change the LOGIN_REDIRECT_URL to some other step (and then have that proceed to dashboard), but what I want isn't really a url.... not sure if middleware would be more appropriate? OR is there some way to sort of extend the login code …