Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use global variable in Django instead of session variable?
I have a Django project that uses a pretty complex object which I would like to pass around in views. Now, normally one would use the session variables for that: request.session['variable'] = complex_object I am aware that this is the normal way to do this. Alas, my very complex object is not JSON serializable so I cannot save it as a session variable. One way to solve this would be to write a serializer for the object. But since the object is really horribly complex and nested, this is not even tedious: it's impossible. So I was searching for an easier workaround. I started working with global variables. This is bad practice, I know, but I need a solution. Global variables work very well in development. But as soon as I deploy the project, they start becoming very unreliable. Sometimes they work, sometimes they don't. So this can't be the way either. To not make this question too text heavy, some pseudo code to show you my global variables in principle: global p def a(request): global p p = 5 def b(request): global p print(p) As I said, doing this in development works well. In production, not so much. Any … -
how to use `commit=False` in django views for getting foreign key values?
views fun:- def save_all_form_at_once(request): if request.method == 'POST': form1 = StudentForm( request.POST, prefix="form1") form2 = GradeForm( request.POST, prefix="form2") form3 = SemesterForm( request.POST, prefix="form3") form4 = CourseForm( request.POST, prefix="form4") if all([form1.is_valid() , form2.is_valid() , form3.is_valid() , form4.is_valid()]): form1.save() dont know how to get following values # new_course = form4.save(commit=False) # new_course.student_id = form1.get("enroll_no") # new_course.save() # new_sem = form3.save(commit=False) # new_sem.student_id = form1.get("enroll_no") # new_sem.course_id = new_course.get("id") # new_sem.save() # new_grade = form2.save(commit=False) # new_grade.Sem_Info_id = new_sem.get("id") # new_grade.Student_Name_id = form1.get("enroll_no") # new_grade.Subject_Info_id = new_course.get("id") # new_grade.save() else: form1 = StudentForm(prefix="form1") form2 = GradeForm(prefix="form2") form3 = SemesterForm(prefix="form3") form4 = CourseForm(prefix="form4") return render(request, 'add.html', {'form1' : form1, 'form2' : form2, 'form3' : form3, 'form4' : form4 } ) models.py file as you can see I didn't put null=Flase in any of FK because I need them in my DB. how can I get all those FK values and save into my DB I need all FK values. and have no idea how to do it! if I'm doing in the wrong way please correct me! -
Django FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\ivan\\Desktop\\Python\\static'
I'm trying to install django debug toolbar to track ORM queries to the database. Can't use python manage.py collectstatic and getting the error Here's the settings files settings.py INSTALLED_APPS = [ #... 'django.contrib.staticfiles', #.. 'debug_toolbar', ] MIDDLEWARE = [ #... 'debug_toolbar.middleware.DebugToolbarMiddleware', ] # ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(os.path.join(BASE_DIR, "db.sqlite3")), } } # .... STATIC_URL='/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'static').replace("\\", "/"), ] -
Django-reversion foreign-key data "follow" question - get related model instance from history when object was created
Say I have models: @reversion.register() class EmailTemplate(models.Model): html_content = models.TextField() context_variables = models.JSONField() @reversion.register(follow="template") class EmailMessage(models.Model): template = models.ForeignKey(EmailTemplate) custom_data = models.JSONField() Case 1: EmailTemplate data: html_content = """ Hello {{ first_name }} """ context_variables = {'first_name': 'Enter name' } EmailMessage data: template = ForeignKey(EmailTemplate with id: 1)) custom_data = {'first_name': 'Robert } I parse this to make additional form fields when creating new email message from template. It lets me declare fields for this email template and form within the EmailTemplate. I create EmailTemplate in admin, so I can see all history versions. The problem is when I select an email from my sent emails list to send again the email with this specified template version (it may be from the past) as the template could be modified later. I know I can create a new template, but there will be many and I won't bother you with the reasons behind my desicion of using reversion. I would also like to avoid attaching large html content to my EmailMessage instance saved to the db. There will be more functionalities like view the web version of this email, unsubscribe etc. I'd rather just be able to render the template (via … -
Django deserialize with one field but serialize with other field
I have two models. Bar is related to Foo via foreign key. In my Bar serializer, I have FooSerializer so it can serializer from its model: class BarSerializer(serializers.ModelSerializer): foo = FooSerializer(source='*') ... class Meta: model = Bar then my Foo Serializer looks like: class FooSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() link = serializers.SerializerMethodField() class Meta: model = Foo fields = ('name', 'link') def to_internal_value(self, data): # Save depending on name foo = Foo.objects.get(name=data) return {'foo': foo} def get_link(self, object): print('req', object.id) if object.id and request: return request.build_absolute_uri( '/app/foo/{}'.format(object.id)) return None I want to able to post in Bar with Foo's name field, for example: { "bar_name": "Nikko", "foo": "The Foo", } but the response I want is: { "bar_name": "Nikko", "foo": { "name": "The Foo", "link": "https://localhost:8000/apps/foo/1", } } -
How two diffrent docker container api communicate with each other requests?
In one container there Django app running which expose to host port 8000 and another container flask app is running which expose to the host port 8001. So there is a condition where the flask app API end needs to communicate with the Django app API end. Code req = requests.get('http://192.168.43.66:8000/api/some') Error requests.exceptions.ConnectionError: HTTPConnectionPool(host='192.168.43.66', port=8000): Max retries exceeded with url: /api/user (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fc6f96942e0>: Failed to establish a new connection: [Errno 110] Connection timed out')) But if I change the request URL to some other API end which not running on the container it gets the response. And each Django API end is working fine if I want to access it through some other external source like postman or browser. -
NameError: name 'DeliveryOrder' is not defined
Here I am trying to call deliveryorder as ForeignKey into the PurchaseOrder table. Once I run makemigrations it shows the above error. Moreover, I can not write the PurchaseOrder definition after the DeliveryOrder because the DeliveryOrder table also holding PurchaseOrder as ForeignKey. Purchase Order class PurchaseOrder(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) deliveryorder = models.ForeignKey(DeliveryOrder) po_quantity = models.PositiveIntegerField(default= 0) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) def __str__(self): return self.part.partname Delivery Order class DeliveryOrder(models.Model): purchaseorder = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE) do_quantity = models.PositiveIntegerField(default= 0) created_date = models.DateField(auto_now_add=True) def __str__(self): return self.do_quantity Can suggest to me how to overcome this issue? -
How to stream IOT signals from Celery/Django?
I have an IoT device that generates 10 datapoints/sec (16 numbers in one datapoint). I want to stream that data into a web app and display it as a real-time graph. I'm using Django as backend, Celery/Redis for background tasks, and Channels for socket connections. Celery task @shared_task def start_eeg_stream(room_group_name, room_name): channel_layer = get_channel_layer() redis_uri = config('REDIS_URL') host, password = redis_uri.split('@')[1].split(':')[0], redis_uri.split('@')[0].split(':')[2] r = redis.Redis(host=host, password=password) pub_sub = r.pubsub() pub_sub.subscribe(f'EEG:{room_name}') r.set(room_name, 1) for message in pub_sub.listen(): if message and message['type'] == 'message': # do something with the message async_to_sync(channel_layer.group_send)( room_group_name, { 'type': 'socket_message', 'payload': {"type": "EEG_POINT", "value": str(message['data'])} } ) if not int(r.get(room_name)): print('stopping eeg stream..') break Django consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .tasks import start_eeg_stream, stop_eeg_stream class LiveDataConsumer(WebsocketConsumer): def __init__(self) -> None: super().__init__() self.consumer = None def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'GROUP_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() self.send(text_data=json.dumps({'value': 'Connected', 'type': "CONN_SUCCESS"})) def disconnect(self, close_code): # Leave room group stop_eeg_stream(self.room_name) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): data_json = json.loads(text_data) # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'socket_message', 'payload': data_json } ) # Receive message from room … -
How to make many to one field in Django?
I want to make simple Django project based on book - author - publication Here book has an author but author has multiple books. Second I want relationship between book and publications, like publication has multiple books but book has one publication (if book published) or book has no publication (if book is not published) how can I make model for it ? Where to use foreign key in this? -
Shared library between multiple Django projects?
If I have 2 Django apps, how could I share a common library between both? I was thinking about a third library project, that I shortcut to in the other 2 projects locally, & on production replace the shortcut with the whole Library folder. would something like this work? and if so, how would I switch out the shortcut for the actual folder on release? -
How can I schedule a task in my djnago amazon product tracking project?
I am working on a web-app project with Django. It is an Amazon product price tracker. I want the app to automatically scrape products in the product table to check if the price of the product has reduced or not. I want to deploy the application once it is finished so it should work there too. I looked for answered online but it seems that cronjobs and celery do not work for windows so is there any other ways I can achieve my goals. I have created a function that needs to be executed once every day. This is the function I want to execute every 24 hours. def track(): products = Product.objects.all() for product in products: new_data = getproduct(product.link) update_data(product, new_data) I have tried the schedule library: import schedule import time from .models import Product from .utils import getproduct schedule.every().day.at("12:00").do(track) here getproduct is the method which scrapes the product data and product is the model -
Django Rest Framework deployed under subdirectory proxy
I'm trying to deploy a small API using a subdirectory on the server. Usually if I do the following config it works fine: location /iframe/api/ { proxy_pass http://127.0.0.1:8001; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; client_max_body_size 0; } The funny thing is that for static files it seems to work, because I get back proper styling for the rest framework, but for every single urlpattern it also transfers the iframe/api which isn't ideal and basically not a single API route is matched. I tried to add proxy_redirect off but still no avail. Any idea why isn't this working as expected? How should I deploy a rest framework API under a sub-directory? -
Cannot resolve keyword 'use_as_keyword' into field
Django==3.2 class SemanticsLevelThreeGeneral(general.ArchivedMixin, semantics.model_mixins.UniquePhraseMixin, semantics.model_mixins.PhraseStrMixin, semantics.model_mixins.SemanticsLevelTwoMixin, general.FlagMixin, general.CommentMixin, models.Model): """ Just general semantics. 1. For reports. 2. Used in <meta name="keywords">. """ use_as_keyword = models.BooleanField(null=False, default=False, validators=[semantics.validators.validate_use_as_keyword,]) class Meta: verbose_name = gettext("Level 3 general") verbose_name_plural = verbose_name Absolutely new database. I deleted all the migrations and made them anew. Everything opens fine in the admin site. Migration went fine. The database: ads6=# select * from semantics_semanticslevelthreegeneral; id | comment | archived | flag | phrase | use_as_keyword | semantics_level_two_id ----+---------+----------+------+--------+----------------+------------------------ (0 rows) Problem When I try to save an instance of this model in the admin site, it blows up. Environment: Request Method: POST Request URL: http://localhost:8000/admin/semantics/semanticslevelthreegeneral/2/change/ Django Version: 3.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'omnibus', 'images.apps.ImagesConfig', 'clients', 'toponyms', 'generals', 'home', 'scaffolds', 'staticassets.apps.StaticassetsConfig', 'semantics', 'commerce', 'tmplts.apps.TmpltsConfig', 'dashboard', 'files', 'marketing'] Installed Middleware: ['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'] Traceback (most recent call last): File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) … -
In Django Generate only s3 client generate_presigned_post with content type for mp4 file upload
After uploading the video(.mp4) file S3 metadata sets its Content-Type : binary/octet-stream when makes my browser force to download the file instead of playing In order to make it play in browser i need to change that content-type programmatically to "video/mp4" in django -
Django admin suddenly starts throwing crbug/1173575
I am building a backend that I administrate using the django-admin view. I have a prod version that runs on a server using nginx, which works as expected (using Gunicorn). Starting yesterday, developping locally has become impossible because when I try to access Django's dev server (started using python manage.py runserver) I get the error "The site can't be reached" (crbug/1173575, non-JS module files deprecated.) as in this post. This never happened before, and because I am not directly using Angular, I can't use the solution described in the post. I did a pip freeze both locally and on the prod server, and the output is the same, which means I did not install a parasite package. It seems to me that the django-admin website is using some deprecated js modules that is now no longer accepted by browsers. It is worth mentionning that I tried to access the dev server using both Mozilla Firefox 78.10.0 and Google Chrome 90.0.4430.93. -
how to past list to template
I am trying to pass this eligable list to my template so that I can display it in my website but when I run the website it says that local variable 'eligable' referenced before assignment. I dont understand because this is the only time I used the word eligable in my code. code: def specificDate(response): empName = employeeName.objects.all if 'checkEmployee' in response.POST: n = response.POST.get("nameEmployee") specDate = response.POST.get("date") if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists(): emp = employeeName.objects.get(employee=n) t = Name.objects.get(name=emp, date=specDate) overT = Name.objects.filter(name=emp, overtime=True) eligable = [] for item in overT: eligable.append(item.date) print('Hello') checkIn = t.timeIn.strftime("%H:%M:%S") checkOut = t.timeOut.strftime("%H:%M:%S") datee = datetime.strptime(specDate,'%Y-%m-%d') print("Here:: ",t.date) print("Month:: ",datee.month) messages.info(response, checkIn + ' - ' + checkOut) return redirect('/specificDate') else: messages.info(response, 'Name does not exist') else: pass return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable}) -
trying to refresh page in django from view not working
I have developed a funcktion that deletes several entries in my django project. They are bases on marked checkbox values. When all done, I want to refresh my template page so that all premarked checkboxes diseapear. But when trying redirect and render, nothing really happens. I want to refresh the page as if I clicked refresh on the page. How do I do that? views.py def deleteMulti(request): g=request.GET checked=g.getlist('marked[]') dbase=g.get('dbase') print('delete: ',checked) print('dbase: ',dbase) #res=[Concert.objects.get(pk=l) for l in checked] if dbase=='concert': deleted=[Concert.objects.filter(id=l).delete() for l in checked] res=Concert.objects.all() print('delete') response=redirect('events') return response urls.py: path('events',Events.as_view(),name='events'), -
DRF: serializer validation without a model
Is the validate_fieldname method not called when not using a ModelSerializer? I am trying to validate my input: class SomeSerializer(serializers.Serializer): serial = serializers.CharField() class Meta: fields = ["serial",] def validate_serial(self, value): if value ... return value I want to use a validator method on the input of serial, but I do not have a related model I could use. -
Not able to send email to sendgrid python
my send_mail code from rest_framework.views import APIView from middleware.response import success, bad_request from user.serializer.dao import SendEmailDao from core.models import EmailLeadLogs from util.email import send_mail class SendEmailView(APIView): def post(self, request): attributes = SendEmailDao(data=request.data) if not attributes.is_valid(): return bad_request(attributes.errors) email_lead_logs = EmailLeadLogs(**attributes.data["meta"]) email_lead_logs.subject = attributes.data["subject"] email_lead_logs.save() send_mail(attributes.data["email"].split(","), attributes.data["subject"], attributes.data["message"]) return success({}, "email send successfully", True) This is the error i am getting, I am trying to use it from drf error -
How should I resolve this error - cannot able call function in a view in django
Please see image I am not able add userid in a queue -
Admin page not loading in Django
I have a new app, which works fine, i can load all my new pages and navigate without any problem. But when i try to access the admin dashboard, i have an error 500. I am new to Django (from Railsd) and would appreciate some help, as i do not see any error log. My setup is as follow: Settings.Py INSTALLED_APPS = [ 'djangoformsetjs', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_hosts', 'rest_framework', 'djoser', 'app' # Enable the inner app ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) core/url.py urlpatterns = [ path('api/app', include('app.urls')), path('admin/', admin.site.urls), path("", include("authentication.urls")), # add this path("", include("app.urls")) # add this ] I was told to check the setup of the admin using : django-admin check, But i get the following error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. This is a bit overwhelming given that i was super comfortable in my previous language. Can you guys help me understand please ? -
How would you design a API Gateway, service registry and Service Discover with Django or Python?
can anyone recommend to me some tools/libraries that I can use to design/implement API Gateway, Service Registery and Service Discovery with Django and Python. Till now I have found Consul, Eureka and a package called Sharkraidar(https://pypi.org/project/sharkradar/), I just need some help to decide the correct tools and the correct approach to implement them. -
ISR not working in django server but in next dev server
hello i recently ran into an error, when i try to do ISR in django python server it fails but when i do in next dev server it works.. on dev server when i update content in django admin panel it changes in dev server , but when in production mode we use django server and it would not work there , whats the solution.. index.js import Head from 'next/head' import Image from 'next/image' import Posts from '../comps/Posts' import styles from '../styles/Home.module.css' export default function Home({data}) { console.log(data) return ( <div> {data.map(e=>{ return( <div> <h1 id='data_h1'>{e.username}</h1> </div> ) })} </div> ) } export async function getStaticProps() { const res = await fetch('http://127.0.0.1:8000/userprofile_data/'); const data = await res.json(); return {props: {data}, revalidate: 1 }; } -
Why does my django url pattern not accept paths starting with "api/payments/"?
I have an app with a payment module, when I use the path "api/payments/" for this module, requests from the front-end do not hit the api, however, when i change the module url path to something else e.g. 'api/collections/' all methods in the module work fine. What could the issue be with that specific url path? -
How to send different message on same group for different users in django channels
I am trying to build a real-time ticket reservation app so I want to display the real time seat booking status to users. For example; I have user1 and user2 connected to a group reservation-1 Now when the user1 selects the ticket in group reservation-1 the seat status will be converted to selected and the message should be broadcasted to all the users connected to the same group with the status of unavailable for that particular seat. But for user1 it should be the status of selected. My code implementation for JavaScript: const socket = new WebSocket('ws://${window.location.host}/ws/reservation-1'); // This is an event when user select the seat socket.send(JSON.stringify({ "event": "SELECT", "seat": "seat_id" })); // This is an event when user deselect the seat socket.send(JSON.stringify({ "event": "DESELECT", "seat": "seat_id" })); socket.onmessage = function(e) { const data = JSON.parse(e.data); // code logic to update the seat based on return values of seat status. } My Django server-side consumer code using django-channels: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ReservationConsumer(WebsocketConsumer): def connect(self): self.chat_group_name = 'reservation-1' async_to_sync(self.channel_layer.group_add)( self.reservation_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.reservation_group_name, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) user = self.scope['user'] event = data['event'] …