Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python requests makes a lot of post requests, what should I do?
The project is written in Django. There is a function in views.py that should make a POST request to the API of one site. But for some reason the script does not work correctly, the update is very slow, and a ConnectionError is thrown. But the POST request is sent several times, and eventually creates several records in the database on the site. There don't seem to be any cycles. What's wrong? views.py: @login_required(login_url='login-main') def send_program_to_orchard(request, orchard_pk, pk, user_pk): services.send_program_to_orchard(orchard_pk, pk) return redirect(request.path) services.py: def make_json(program_id): program = Program.objects.get(id=program_id) program_substances = ProgramSubstance.objects.filter(program=program) response = { 'program_number': program.number, 'program_substances': [] } for each in program_substances: response['program_substances'].append({'date': each.date.isoformat(), 'substance': each.substance, 'dose': float(each.dose), 'measurement': each.measurement, 'comment': each.comment}) return json.dumps(response) def send_program_to_orchard(orchard_pk, program_pk): orchard = Orchard.objects.get(id=orchard_pk) headers = {'Authorization': f'Token {orchard.API_token}'} data = {'data': make_json(program_pk)} requests.post(orchard.program_API, headers=headers, data=data) -
logger.info() is not showing message in log file in Django project
I am learning django logging . log files are generating but I am not showing the required message i want to show in log file. here is my code the code in views.py file: ``from asyncio.log import logger from django.shortcuts import render from django.http import HttpResponse Create your views here. import logging, traceback logger = logging.getLogger('django') def home(request): logger.info('Some Message') return render(request, 'home.html')`` the code in setting is here: `` import os LOGGING ={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file'], 'level':'DEBUG' } }, 'handlers':{ 'file':{ 'level':'INFO', 'class':'logging.FileHandler', 'filename':'./logs/debug3.log', 'formatter':'simple' } }, 'formatters':{ 'simple':{ 'format':'{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style':'{', } } } `` -
Postman works in form data but not in raw or on my server for that matter
So the first piece of code is the backend end point and second is the front end. It does not send the token to an email address on the server or using Postman raw data. But it does send a token using form-data. Any ideas I'm new to this. thanks class RegisterView(View): def post(self, request, *args, **kwargs): data = request.POST.get('email') check_if_email_exists = [] for email in Registration.objects.all().values_list('email', flat=True): check_if_email_exists.append(email) if data in check_if_email_exists: return JsonResponse('Email already provided', safe=False, status=200) else: new_user = Registration.objects.create(email=data) new_user.save() content = {'code': new_user.code} send_mail( "Thanks for Registering", f'Here is your signup Token:{content}', 'djangod192@gmail.com', [data], fail_silently=False, ) return JsonResponse(content, status=201) const SignUpStep1 = () => { const navigate = useNavigate(); const [email,setEmail] = useState(""); const dispatch = useDispatch(); const url = "https://motion.propulsion-learn.ch/app/api/auth/registration/"; const updateEmail = (event) => { setEmail(event.target.value); } const sendVerificationCode = (event) => { event.preventDefault(); if (email.length > 0) { const data = { email: email }; const fetchConfig = { method: 'POST', headers: new Headers({ "Content-Type": "application/json", }), body: JSON.stringify(data), }; fetch(url,fetchConfig) .then((response) => { return response.json(); }) const action = { type:"setEmail", payload:email }; dispatch(action) navigate("/SignUpStep2") }else{ alert("please enter email address"); } } -
How to save mapped values based on Foreign key (amount can vary)
I am programming a product listing tool and I need to map product attributes from my own products to for example Amazon's product attributes. Which attributes are required is defined through the product category. So I have my own Article which is mapped to the given Amazon product category and based on the category i need to create depending fields (choosable set of fields). Have a look add my models: from django.db import models from Article.models import Article class AmazonCategory(models.Model): category = models.CharField(max_length=255,unique=True) attribute = models.ManyToManyField(to='AmazonAttribute',through='AmazonCategoryToAmazonAttribute') class AmazonAttribute(models.Model): attribute = models.CharField(max_length=255) class AmazonAttributeValue(models.Model): attribute = models.ForeignKey(AmazonAttribute,on_delete=models.CASCADE) value = models.CharField(max_length=255) class AmazonCategoryToAmazonAttribute(models.Model): category = models.ForeignKey(AmazonCategory,on_delete=models.CASCADE) attribute = models.ForeignKey(AmazonAttribute,on_delete=models.CASCADE) required = models.BooleanField() class AmazonArticle(models.Model): article = models.ForeignKey(Article,on_delete=models.CASCADE) category = models.ForeignKey(AmazonCategory,on_delete=models.CASCADE) I will give a detailed example. I have a Product on my personal system called "Brush" and it is in the category "Art" which I have personally assigned. Now I created the categories and values for categories tables for Amazon (they are given AmazonCategory) already and I can map my article with the Amazon category "Toys | Toys and Babys | Toy". I have also stored the information in my database that the category "Toys | Toys and Babys | Toy" require … -
Datatables| Django, sorting, paging and searching with DRF
I have a Datatable that's working perfectly, and I wanted Server-side process to be true and not client-side. But when I enable server-side the sorting, paging and search became faulty. TestCase: https://codepen.io/TheNerdy97/pen/gOvNeeo?html-preprocessor=pug I'm using this module https://github.com/izimobil/django-rest-framework-datatables For seamless integration between Django REST framework and Datatables. I did as the doc said but it still won't work as expected. models.py from unittest.util import _MAX_LENGTH from django.db import models #from django.utils.translation import gettext as __ # Create your models here. class Fresh(models.Model): code = models.CharField(("code"), max_length=255) orbs = models.IntegerField(("orbs")) orbs_display = models.CharField(('orbs_display'), max_length=255) price = models.IntegerField(("price")) price_display = models.CharField(('price_display'), max_length=255) images = models.CharField(("images"), max_length=10000000) date = models.CharField(("date"), max_length=255) class Meta: ordering = ['code', 'orbs', 'price'] def __str__(self): return self.code views.py from django.shortcuts import render from accounts.models import Fresh, Orbs from rest_framework import viewsets from accounts.serializers import FreshSerializer from django.core import serializers # Create your views here. def index (request): return render(request, 'index.html') class FreshViewSet(viewsets.ModelViewSet): queryset = Fresh.objects.all().order_by('price') serializer_class = FreshSerializer urls.py import accounts from . import views from django.urls import path, include, re_path from rest_framework import routers from main import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'fresh', views.FreshViewSet) router.register(r'orbs', views.OrbsViewSet) urlpatterns = [ path('', views.index, name='index'), path('fresh', views.fresh, name='fresh'), … -
django-picklefield changes structure after upgrade
I'm migrating a Django app from 1.11.16 to 4.0.5 and django-picklefield will be migrated also from 2.0 to 3.1 . A django object has the following line: from picklefield.fields import PickledObjectField class A(models.Model): ... log_list = PickledObjectField(default=list) . Using the old code (1.11.16) and the new code (4.0.5) results a totally different result for the query: #old Obj.objects.get(id=4737).log_list [{u'date': datetime.datetime(2022, 6, 27, 12, 54, 50, 746392), u'message': u'Fetching trademark search started', u'typ': u'info'}, {u'date': datetime.datetime(2022, 6, 27, 12, 54, 53, 423384), u'message': u'Fetching trademark search finished', u'typ': u'info'}] #type == list #new Obj.objects.get(id=4737).log_list gAJdcQEofXECKFgEAAAAZGF0ZXEDY2RhdGV0aW1lCmRhdGV0aW1.... #so it results exactly what is stored in the db. #type == str With picklefield version 3.1 is there anything else I need to do / change to have the behaviour than with version == 2.0 ? What should I do with the new setup to get the list instead of the str? -
Page not found (404) Django after deleting object
After i delete an object of my table, with a delete button, I get the an 404 Page not found error. Here is my code: views.py: def deleteAction(request, i): y = get_object_or_404(Literatur, pk=i) y.delete() return HttpResponseRedirect(reverse('literatur:index')) urls.py urlpatterns=[ path('deleteAction/<int:i>/', views.deleteAction, name="deleteAction"), ] models.py class Literatur(models.Model): name = models.CharField(max_length=100) jahr = models.IntegerField() autor = models.CharField(max_length=100) auflage = models.IntegerField(default=1) verlag = models.CharField(max_length=100) ort = models.CharField(max_length=100) isbn = models.IntegerField() def __str__(self): return f"{self.name} {self.jahr} {self.autor} {self.auflage} {self.verlag} {self.ort} {self.isbn}" -
Django Rest Framework static file blocked by CORS
Can someone help me, because I can't do anything with CORS. I have DRF server with corsheaders installed. The settings are INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ('Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials', 'Authorization', 'Content-Type', 'Cache-Control', 'X-Requested-With', 'x-csrftoken') What am I trying to achieve is to get an image from server to crop it in React. So I get the name of the image in the server response, I show it on the page with no ploblem, but when I'm trying to get it like this: let img = new Image(); img.crossOrigin = 'Anonymous'; img.src = "http://127.0.0.1:8000/static/images/" + props.image.picname; setImage(img); I'm getting an error that access to the image is blocked. I've tried to run server as python manage.py runserver --nostatic and modify urls.py with those lines: if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() But it didn't help. How should I manage this since I have no request to the image, I just open it. Why showing the image on the page is ok to CORS and trying to get it by JS from the same page is such a big problem? -
django sitemap for static react routes (error : NoReverseMatch at /sitemap.xml/)
i want to implement sitemap for static react routes and I get this error: Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name. I added a list of my react routes REACT-ROUTES in settings.py and append them to urlpatterns in the root urls.py file settings : INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'rest_framework', . . ] SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'ess')], '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', ], }, }, ] REACT_ROUTES = [ 'contact', 'politique-de-confidentialite', 'mentions-legales', 'cookies', . . ] STATIC_URL = '/static/' STATIC_ROOT = basepath + '/app/static' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ess', 'static')] urls : from django.conf import settings from django.contrib.sitemaps.views import sitemap from .sitemaps import StaticViewSitemap react_routes = getattr(settings, 'REACT_ROUTES', []) sitemaps = { 'static': StaticViewSitemap } urlpatterns = [ path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), re_path(r'^$', TemplateView.as_view(template_name='index.html')), ] for route in react_routes: urlpatterns += [ re_path('{}'.format(route), TemplateView.as_view(template_name='index.html')) ] sitemaps.py : from django.contrib.sitemaps import Sitemap from django.urls import reverse class StaticViewSitemap(Sitemap): def items(self): return ['contact'] def location(self, item): return reverse(item) I don't know what I am missing, please help -
Im trying to implement a delete button using django and vue js
Im trying to implement a delete button using django and vue js but im running into an error 500 and i cant seem to understand why ? i know it means my call isn't working go from here <button class="button is-success" @click="deleteTest()"> Yes, Delete</button> to here deleteTest() { axios.post('/app/api/testzone_delete/' + this.TestCategory_id + '/') .then((response) => { console.log(response) this.showDialog = false }) .catch((function (error) { console.log(error ) })) } } }) </script> then like its django it goes through url.py path('api/testzone_delete/<int:individualtestzone_id>/', api_delete_test, name='api_delete_test'), and finally in the api.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import TestCategory from django.contrib import messages @csrf_exempt def api_delete_test(request, individualtestzones_id): individualtestzone = request.user.TestCategories.all().get(pk=individualtestzones_id) individualtestzone.delete() return JsonResponse({'success': True}) im pretty new to django and can't seem to see why it does not work -
DRF Model Permission denying access to authenticated user
I'm getting a permission denial error but, if I'm understanding things correctly, the permissions should already have been assigned. class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [DjangoModelPermissions] class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [DjangoModelPermissions] I've tried some different permission classes so far, but except for just bypassing it entirely with AllowAny nothing seems to have worked. -
Choose Front-end and Backend for multipurpose website( Social Network + ecommerce (like facebook has Market)
I have been reviewing the suggestion of using Django for backend(api) and using Reactjs for front-end. These can help the platform run smoothly, fast and secured.However, I would like to know your suggestion of choosing technologies for building that platform (social network and ecommerce at same domain) -
How do i become a forex web application developer [closed]
i am web developer with intermediate knowledge in Python, Django , javascript, Html and css. i will like to start building web applications for forex trading but i dont't have any idea on how to start and i haven't seen any tutorials on it. Any idea will be appreciated thanks. -
Not able to apply redis lock on celery workers
I am trying to replace django memcache’ to redis lock and getting Connection reset error` -
How to filter comparing two informations from the same Django model
I have a MedicalCertificate model like this: class MedicalCertificate(models.Model): needs_leave = models.BooleanField() date = models.DatetimeField() days_off = models.IntegerField() And I need to filter the active medical certificates, which are: date + days_off >= datetime.now() I tried to use F(), but not success. Ex.: from django.db.models import F certificates = { 'needs_leave': True, 'days_off__gte': datetime.datetime.now() - F('externalsystemmedicalcertificates__date') } queryset = MedicalCertificate.objects.filter(**certificates) Any idea how to proceed? -
Python3 import error smart_unicode django
This is my first time ever trying to run a py script I have a script to auto import to android studio some translations. I installed python 3.10.5 and pip and trying to run a script. I have this import from django.utils.encoding import smart_str, smart_unicode When i try to run it, I get the error ImportError: cannot import name 'smart_unicode' from 'django.utils.encoding' (C:\Users\a816353\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\encoding.py) I have tried some suggestions but I cant figure out what to do. -
How to perfom CRUD Operation in Flutter & Postgres
I want to perfom CRUD Operation Postgres but with a flutter app, so that my Django app can share data with Flutter. -
Python Django convert timestamp from UTC to local timezone
Im am working with Django + DRF, to develop a REST API. I have configured the django settings to work with the timezone support on: USE_I18N = True USE_L10N = True USE_TZ = True As previously mentioned, my database is receiving and storing data in UTC. My problem is that for some users (each user has their configuration) I must return responses in their time zone (usually in UTC-3 or UTC-2). I was reading several posts and tried several combinations of: astimezone and normalize without succes. I attach my attempts: timezone_arg = pytz.timezone('America/Buenos_Aires') print(ts_a, ts_b) ts_a = ts_a.astimezone(timezone_arg) ts_b = ts_b.astimezone(timezone_arg) print(ts_a, ts_b) utc = pytz.timezone('UTC') ts_a = timezone_arg.normalize(ts_a.astimezone(utc)) ts_b = timezone_arg.normalize(ts_b.astimezone(utc)) print(ts_a, ts_b) I am getting the following: 2022-06-17 05:39:09 2022-06-17 05:46:49 2022-06-17 05:39:09-03:00 2022-06-17 05:46:49-03:00 2022-06-17 05:39:09-03:00 2022-06-17 05:46:49-03:00 I understand that django is interpreting that what I am telling it is that the timestamps are already in UTC-3... and it is normalizing them to UTC. But what I want is to cast from UTC to UTC-3. My input/output should be: 2022-06-17 05:39:09 2022-06-17 05:46:49 2022-06-17 02:39:09 2022-06-17 02:46:49 Since I don't only work with the time zone of Argentina (UTC-3), I can't compute a timedelta of 3 … -
Plotly in Django should I use Dash?
I am a reasonably experienced amateur python coder. With this site's help I have fought my way through, celery, channels, websockets, NGINX, docker etc etc to produce a website which controls my astronomy dome and some house automation. Part of the astronomy setup is a 3rd party weather station which collects data (temperature, wind speed, humidity, brightness, rain etc) and distributes a json file every 15 secs. I have successfully coded pyhton / Django / Plotly to collect the data and produce one graph (temperature). I have successful embedded this graph in a webpage. The next step is to add a drop down box as a choice mechanism for what data (e.g. temperature or bightness) to show in the graph. I think I can do this with websocket calls. Should I use Dash instead ? I have found plotly relatively easy to use and I am attracted to the idea of using the bootstrap plugin to manage bootstrap in python code as opposed to in an html page. but Problem: installing Django-Plotly-Dash v2.0 downgrades django (v4.0.5 to 3.2.13), daphne (v3.0.2 to 2.5.0) and channels (v3.0.4 to 2.4.0). I'm not sure if that is going to 'break' anything but since everything … -
Store extra data like refresh_token when signing up via access_token
I am trying to signup using access token for google. My frontend is next.js with next-auth.js fetching the access_token, refresh_token, etc. I am using python social auth with Django to persist the user information. I use the access_token provided by next-auth to signup the user in Django. How do I make sure that the other response fields like refresh_token, and expires are saved in the Django DB? I can pass the required fields from next-auth to an API in Django but not sure what the expected format is. https://python-social-auth.readthedocs.io/en/latest/use_cases.html#signup-by-oauth-access-token @psa('social:complete') def register_by_access_token(request, backend): # This view expects an access_token GET parameter, if it's needed, # request.backend and request.strategy will be loaded with the current # backend and strategy. token = request.GET.get('access_token') user = request.backend.do_auth(token) if user: return HttpResponse(json.dumps(get_tokens_for_user(user))) else: return HttpResponse('Unauthorized', status=401) def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) update_last_login(None, user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } -
Pass Django list as argument to Javascript
I have a list passed through the context into the html page of a Django project which I want to read inside of a .js which contains chartjs code. The problem is that .js is reading as string and not as a list/array. views.py def index(request): context = { "data": [1, 2, 3, 4, 5]} return render(request, 'index.html', context) Then, in the html page I have to pass the {{ data|safe }} to a javascript like so: <script src='{% static "js/chart.js/linechart.js" %}' var label = "fakelabel"; var index = {{ data|safe }}; ></script> Inside the .js I'm reading the 'index' input as: document.currentScript.getAttribute("index") How can I fix this? ('label' is read correctly as str indeed). -
Pylance, functions not defined
I have a simple code with 3 functions. the first one get some values from the 2 others to check some conditions, but I get an error from Pylance saying the functions sub1 and sub2 are not defined. any clues? @staticmethod def main_test() var1 = sub1() if not var1: return ('test1 not even') var2 = sub2() if not var2: return ('test2 not even') return True @staticmethod def sub1(): test = random.randint(1, 10) if (test % 2)==0: return True return ( str(test) + 'is Odd') @staticmethod def sub2(): test = random.randint(1, 10) if (test % 2)==0: return True return ( str(test) + 'is Odd') -
Template variables doesn't updates after redirect in Django?
I am building simple django app where I want to do some parsing when user click button on the frontend. I have template variable {{ parsing }} which I am using inside index.html to disable button for parsing when user click on it <div class="btn-group mr-2" role="group" aria-label="Parsing group"> <button class="btn btn-dark btn-lg" id="parseButton" {% if parsing %} disabled {% endif %}> <i class="fa fa-terminal gradient-text"></i> <span class="gradient-text">| Parse</span> </button> </div> Next what I do is JQuery method which sends ajax request to my backend to initialize variables for parsing and method from views.py returns redirect to the same page (index.html). $('#parseButton').click(function () { $.ajax({ type: 'POST', url: 'initialize_parsing/', headers: {"X-CSRFToken": $.cookie("csrftoken")}, data: {} }); Then my views.py: def initialize_before_parsing(request): if request.method == 'POST': frontendTracker = FrontendTracker() frontendTracker.progress = 0 frontendTracker.parsing = True return redirect("index") class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): frontendTracker = FrontendTracker() context = super(IndexView, self).get_context_data(**kwargs) context["showAnnotation"] = frontendTracker.showAnnotationButton context["parsing"] = frontendTracker.parsing context["progress"] = frontendTracker.progress return context and urls.py urlpatterns = [ path('', IndexView.as_view(), name="index"), path("initialize_parsing/", initialize_before_parsing, name="initialize_before_parsing"), ] Finally what is bother me is that when I send that ajax request and everything works fine when my page being redirected {{progres}} template variable isn't changed … -
Python NameError: name '_mysql' is not defined
I am trying to have a working ubuntu server with Python, Django and MySQL. But when I switch from SQLite to MySQL and trying to reach my server I get the following error "NameError: name '_mysql' is not defined". It does work if I run the project in virtual environment mode with the command "python manage.py runserver". The database is also correctly created with the command "python manage.py migrate". This does not work when I try to reach my URL. I think there is an issue with my virtual host file, but I am unable to see it. Any help would be appreciated! Virtual host file: <VirtualHost *:80> ServerName mysite.com ServerAlias www.mysite.com WSGIDaemonProcess myprocess python-path=/var/www/myproject/myname:/var/www/myproject/myname/venv/lib/python3.7/site-packages WSGIProcessGroup myprocess WSGIScriptAlias / /var/www/myproject/myname/myproject/wsgi.py <Location / > Order deny,allow Deny from all # ek Allow from ${IP_USER1} Allow from ${IP_USER2} </Location> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> The error log: mod_wsgi (pid=55852): Failed to exec Python script file '/var/www/myproject/wsgi.py'. mod_wsgi (pid=55852): Exception occurred processing WSGI script '/var/www/myproject/myname/myproject/wsgi.py'. Traceback (most recent call last): File "/var/www/myproject/myname/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: cannot import name '_mysql' from partially initialized module 'MySQLdb' (most likely due to a circular import) (/var/www/myproject/myname/venv/lib/python3.7/site-packages/MySQLdb/__init__.py) During handling of the … -
How to get the Current User IP in Python / Django
I am trying to capture the IP Address and the System Name of the current Login user during the login Process. I Use following code for the same: import socket system = socket.gethostname() IPAddr = socket.gethostbyname(system) It works fine in Local Server but when I push to Server it takes the server name and server IP instead of user IP.