Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NOT NULL constraint failed when sending a post request with Django Rest Framework
I have a problem with my API. When I'm sending a Post request to create a new Message I got the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: chat_message.channel_id The models: class Channel(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(Account) created_date = models.DateTimeField(auto_now_add = True) class Message(models.Model): user = models.ForeignKey(Account, on_delete = models.CASCADE) channel = models.ForeignKey(Channel, on_delete = models.CASCADE) content = models.TextField(blank=False) created_date = models.DateTimeField(auto_now_add = True) The serializers: class ChannelSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, read_only=True) class Meta: model = Channel fields = '__all__' class MessageSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) channel = ChannelSerializer(read_only=True) class Meta: model = Message fields = '__all__' class UserSerializer(serializers.ModelSerializer): """ Serializers For The User Object""" class Meta: model = Account fields = ["email","password","username","id"] extra_kwargs = {'password': {'write_only': True, 'min_length': 8 }} def create(self, validated_data): """ Create the user with encrypted password""" return Account.objects.create_user(**validated_data) def update(self, instance, validated_data): """Update The user""" user = super().update(instance,validated_data) return user And the views: class ChannelView(viewsets.ModelViewSet): """View for the channels""" serializer_class = ChannelSerializer queryset = Channel.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): """Retrieve channels linked to the authenticated user""" return self.queryset.filter(users = self.request.user) def perform_create(self, serializer): """ Create a new channel with users set in the request as users""" serializer.save(users = self.request.data.get('users')) class MessageView(viewsets.ModelViewSet): """View for … -
Serializing a ManyToMany field
I have two models in my django app, one user model and one keyterm model. When registering a new user, the user can specify one or multiple keyterms. And a keyterm can be affiliated to one or many users. The problem I am encountering is when registering a user with an existant/new keyterm. I think the issue is surfacing when I'm retrieving the data from the post request. Here is my code for : the user model, and the keyterm model Both the serializers class Keyterm(models.Model): keyterm = models.CharField(max_length=255, primary_key=True) class User(AbstractUser): name = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username = None keyterms = models.ManyToManyField('Keyterm', ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class KeytermSerializer(serializers.ModelSerializer): class Meta: model = Keyterm fields = '__all__' class UserSerializer(serializers.ModelSerializer): keyterms = KeytermSerializer(many=True) class Meta: model = User fields = ['id', 'name', 'email', 'password', 'keyterms'] extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): password = validated_data.pop('password', None) keyterm_data = validated_data.pop('keyterms', []) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() for keyterm in keyterm_data: name = keyterm['keyterm'] try: k = Keyterm.objects.get(keyterm=name) except Keyterm.DoesNotExist: k = Keyterm.objects.create(keyterm=name) instance.keyterms.add(k) return instance Here is the request I used to test: { "name": "User3", … -
Access django session and user asynch/in different (unix) process
I'd like to integrate a streamlit application - streamlit is based on tornado - into django via an <iframe>, while ensuring that streamlit requests only go through if there is an authenticated user in django running on the same domain - e.g. via nginx or both running on different ports. However, I'm experiencing issues with asynch-ness. I've set DJANGO_ALLOW_ASYNC_UNSAFE as a quick fix, but obviously don't get warm from database corruption due to concurrent access. So far I'm protecting myself from that by adding read-only access to the database, but can image particular django classes, e.g. the SessionStore, also aren't thread safe (although probably process safe?). Is there a safe way to do 'read-only' authentication via django in other wsgi(-ish) applications, like tornado? This is the tornado script, running next to it any django application with user authentication of whatever sort (default, saml2, etc). The django_authentication_middleware extracts the appropriate session id from the cookies and passes this the django's get_user function to then verify authentication. DJANGO_SETTINGS_MODULE should be set as for the django application. To get the error, disable DJANGO_ALLOW_ASYNC_UNSAFE. import os os.environ['DJANGO_ALLOW_ASYNC_UNSAFE'] = 'true' import asyncio from importlib import import_module from typing import Optional, Awaitable import django django.setup() from … -
Admin User model
My admin user model does not update new record when I register using UserCreationForm. Access the github code in the views I have imported Usercreationform has shown below and I did all the views coding. I do not know where I went wrong. I also rendered the form correctly into the template. But the annoying part comes after filling the form. It doesn't update in the admin panel once I accessed it // THE VIEWS from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm def home(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'main/index.html', context) // THE TEMPLATES <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" value="register"> </form> </body> </html> -
Django formset of formsets, generates duplicate ids
Enough days were wasted already on trying to figure out how to work with formset_factory given the awful documentation. It generally works fine with multiple formsets combined in the same view as long as they do not overlap. Issues arise when a formset is composed of other formsets: forms.py from django import forms class FormA(forms.Form): field_a = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'Field A', 'class': 'form-control'} ), label='', ) class FormB(forms.Form): field_b = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'Field B', 'class': 'form-control'} ), label='', ) views.py from django.forms import formset_factory from django.shortcuts import redirect, render from myapp.forms import FormA, FormB def index(request): context = {} if request.method == 'POST': context['formset_a'] = formset_factory(FormA)(request.POST, prefix='A') context['formset_b'] = formset_factory(FormB)(request.POST, prefix='B') return redirect('new') context['formset_a'] = formset_factory(FormA, extra=2)(prefix='A') context['formset_b'] = formset_factory(FormB)(prefix='B') return render(request, 'index.html', context) index.html {% load static %} {% load bootstrap5 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My title</title> <link rel="stylesheet" href={% static 'css/bootstrap.min.css' %}> </head> <body> <form method="post"> {% csrf_token %} {{ formset_a.management_form }} {% for fa in formset_a %} {{ fa.field_a }} {% csrf_token %} {{ formset_b.management_form }} {% for fb in formset_b %} {{ fb.field_b }} {% endfor %} {% endfor %} <button class="btn btn-success" type="submit">Create</button> </form> </body> </html> urls.py … -
Nginx gives 502 bad gateway but only for a few http requests
I made a portfolio website using django and hosted it on a digitalocean droplet with Postgres, Nginx, and Gunicorn. After testing it I noticed that a few of the subpages of the portfolio projects gives back the 502 response after 1 second of loading but interestingly enough it's not all of them. The pages that fail tend to have more images but I tried excluding the images the views.py sends to the template, however the ones with the 502 response failed out again. (for context the images are provided by local server side and not by an online storage service) The issue seems to be resolved when I reload those pages manually. Here is the views.py: def project_view(request:HttpRequest, name:str) -> HttpResponse: project = Project.objects.filter(name=name).first() images = ProjectImages.objects.filter(project=project) # for every image in images this downscales that image and compresses it with PIL for projectimage in images: generate_projectimage(projectimage) # this downscales the thumbnail image of the project generate_downscaled_thumbnail(project) return render(request, "project.html", { 'project': project, 'images' : images, }) The template that receives it: <div class="carousel"> <div class="carousel-cell"> <img src="data:image/jpeg;base64,{{ project.downscale }}" data-src="/media/{{ project.thumbnail }}"> </div> {% for projectimage in images %} <div class="carousel-cell"> <img src="data:image/jpeg;base64,{{ projectimage.downscale }}" alt="" data-src="/media/{{ projectimage.image }}"> … -
Get data from get request. Django
After authorization in some social network, it (social network) transmits the value of the code in the GET request and redirects the user to the profile page, I try to extract data from the GET request, but in response I get None. views.py @login_required def vk_auth(request): params = { 'client_id': '51568560', 'client_secret': 'bE8JDZO9qHTOaVb4XdcT', 'redirect_uri': 'http://127.0.0.1:8000/profile', 'display': 'page', 'response_type': 'code', } return redirect('https://oauth.vk.com/authorize?' + parse.urlencode(params)) @login_required def vk_link(request): code = request.GET.get('code') return HttpResponse(code) There is a GET request in the debug toolbar in the reguest, and there is also a code variable with the desired value, but I still can't get this data How can I get this code? -
How to import packages that are outside a django project
I have the following folder structure my project, the backend directory is a django project, when I run python manage.py runserver from the backend, I get an import error whenever I import functions from TwitterChatBot package, what's the problem and the solution? ├── backend │ ├── backend │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── chatbot │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── db.sqlite3 │ └── manage.py ├── conftest.py ├── dockerfile ├── document_scraping │ └── scrape.py ├── index │ ├── build_index.py │ └── index.jsonl ├── nginx.conf ├── prompts │ ├── passage_summarization.txt │ └── question_answering.txt ├── README.md ├── requirements.txt ├── start-server.sh └── TwitterChatBot ├── chat.py ├── gpt_3_manager.py ├── index.py ├── __init__.py ├── main.py ├── prompt.py ├── tests │ ├── chat_test.py │ ├── gpt_3_manager_test.py │ ├── index_test.py │ ├── prompt_test.py │ └── utils_test.py └── utils.py -
Django ImproperlyConfigured("The SECRET_KEY setting must not be empty.") error
I currently got a Django project and have been tasked to run it locally. Currently it is very large and so the settings e.t.c can get confusing. I'm trying to run manage.py runserver and it keeps giving me secret key not configured error. (Although my secret key is configured in settings like it ususally is) I read a previous post that this could be due to circular dependencies so i went through the settings code and found something that COULD possibly be an issue but I'm not completely sure. ### CELERY #### CELERY_IMPORTS = [ 'X.Y.tasks', 'mailchimp_synchronisation.tasks' ] When I open these files from their respective folders the first import I see is: from django.conf import settings I'm not sure if this is what's causing the error because: It seems like just information and not actually running this piece of code My settings file is saved inside a folder called settings and is saved as base.py instead of just settings.py I've tried adding the secret key to my docker compose, adding the settings file as well in the environment but it always seems to give the same error -
APScheduler not running in Django
APScheduler is not running in Django. I want to use the APScheduler library in a Djnago frame to get LINE notifications when a todo list deadline comes up, but I am not getting LINE notifications. Is there something wrong with the APScheduler settings? testapscheduler.py from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime, timedelta import pytz import requests import json from .models import Todo def notify_todo(): # 現在の日時を取得 now = datetime.now(pytz.timezone('Asia/Tokyo')) # 締め切りが30分以内のTODOリストを取得 todos = Todo.objects.filter( deadline__gt=now - timedelta(minutes=30), deadline__lt=now + timedelta(minutes=30), ttime__isnull=False, ttime__gt=now.time() ) for todo in todos: #LINE NotifyのAPIトークンを取得 api_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 通知メッセージの作成 message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}" # LINE Notifyに通知を送信 headers = {'Authorization': f'Bearer {api_token}'} payload = {'message': message} requests.post('https://notify-api.line.me/api/notify', headers=headers, data=payload) #BackgroundSchedulerの設定 def start(): scheduler = BackgroundScheduler(timezone='Asia/Tokyo') scheduler.add_job(notify_todo, 'interval', seconds=1)#1秒ごとに実行 scheduler.start() apps.py from django.apps import AppConfig class TodoConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'todo' def ready(self): from .testapscheduler import start start() models.py from django.db import models class Todo(models.Model): title = models.CharField("タスク名", max_length=30) description = models.TextField("詳細", blank=True) deadline = models.DateField("締切") ttime = models.TimeField("") def __str__(self): return self.title -
start Django project in vs code
Im trying to learn Django. I started a youtube tutorial managed to do some basic stuff etc. After closing the vs code, the server closed too. Now when I try to start the project using python manage.py runserver or python manage.py startapp, i get the error "zsh: command not found: python" im trying to do all that in vs code terminal -
Company - Worker Algorithm in Django
I want to ask a question about my algorithm. The operation should be like this; There is one or more companies, this is the top cluster. There are work fields affiliated with these companies. When the company receives a project, it gives it to the work fields, and at the same time, this project has a total price. It divides work packages into work fields and allocates a budget to each work field from the total price of the project. Each work field belonging to the company has its own work package to be completed, and there is a price for this package. When any work package is completed, I want to reduce both the price of the work completed from the work field budget and the total price of the project. But I was undecided on how to connect the payment. Can you help me? Here is the ERD Model link: https://ibb.co/ch0F3Bg I made a mistake on the worker part, ignore it. 🙂 More than one worker can work in a work field, I will fix it while connecting the diagram 🙂 I have given all the details above. -
How do I get the values out of a string object
I am sending some values to a Django back end and I would like to get the values from the object. This is the part that gets the data on the front end and sends it to the back end: function addCartToDB(cart) { let formdata = new FormData(); formdata.append("user", loggedUser); formdata.append("carttotal", cart.carttotal); for (var item of cart.items) { let data = { id: item.id, qty: item.qty, }; formdata.append("products", data); } axios .post("api/v1/cart/c/", formdata) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } This is the view that is supposed to process the request: class CreateCart(generics.CreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = CartSerializer def post(self, request): entries = request.data.getlist("products") for entry in entries: breakpoint() Since there is just one product in the cart the entry object looks like this: [object Object] and the data that is supposed to be in there is the product id and the product quantity which will be strings. How do I get the values of out the object please? -
Nuxt 3 dynamic route not found
I have a problem with nuxt 3 frontend application: I use nuxt 3 as my frontend and django as my backend and api service. When I run npm run build (it executes nuxt generate) command in local, to get files ready to be send to production, the files like /blog/9, /blog/6, /blog/4 etc. are generated into /.output/public dir. These numbers are posts ids, and posts are fetching from backend using axios, and they are generated because they already exists on backend and are automaticly fetching by nuxt when command is ran. The thing is, when i enter the domain like https://example.com/blog/9 via button or link on website, that includes the id param, that has been previously generated via npm run build command, it's all good, even with blog posts that have been generated after deploying nuxt files the production server, like https://example.com/blog/12 or https://example.com/blog/27. But when I enter the url https://example.com/blog/12 manually, not via the link or buttom on the website, it returns me a default 404 error provided by the server, as the post wasn't found. I want it to automaticly get id param from url and execute the fetch method by axios. Axios method from Post.vue component: import … -
Enable CSRF TOKEN in Django html coded using element-ui
I am trying to add CSRF TOKEN (to ensure CSRF protection) to my html script in Django for the POST requests so that it will not be classified as an unsafe request. However I am unsure of where I should place it. When I place it within {% verbatim %}, it comes off as a text as shown on in the image. Really desperate and really appreciate any advice. {%extends "doctor.html" %} {% block emr %}active{% endblock %} {% block mainbody %} {% verbatim %} {% csrf_token %} <div id="app2" class="container"> <el-row :gutter="20" style="width: 90%; height: 120%;"> <el-col :span="12"> <div class="info-wrapper"> <div class="header">Add new medication delivery jobs</div> <el-form ref="deliveryInfoForm" :model="deliveryInfo" :rules="deliveryRules" label-width="110px" label-position="left"> <el-form-item label="Order ID" prop="order_id"> <el-select v-model="deliveryInfo.order_id" placeholder="Select an Order ID" style="width: 100%; margin-left: 0px;" > <el-option v-for="item in order_id" :key="item.id" :label="item.order_id" :value="item.order_id"> <span style="float: left">{{ item.order_id }}</span> </el-option> </el-select> </el-form-item> <el-form-item label="Box Number" prop="box_number"> <el-select v-model="deliveryInfo.box_number" placeholder="Default: Box 1" style="width: 100%; margin-left: 0px;" > <el-option v-for="item in box_options" :key="item.value" :label="item.label" :value="item.value"> <span style="float: left">{{ item.label }}</span> </el-option> </el-select> </el-form-item> <el-form-item> <el-button style="width: 100%;" type="primary" @click="onSubmit">Confirm</el-button> </el-form-item> </el-form> </div> </el-col> <el-col :span="12"> <div class="info-wrapper"> <div class="header"><center>Medications Delivery Status</center></div> <el-table :data="list" stripe style="width: 100%" :cell-style="{ textAlign: 'left' }" :header-cell-style="{textAlign: … -
Is there a way to make chatsocket.send send the data to all of the instances at the same time?
In a typical consumers class, we would have the following: class SomeConsumer(AsyncWebsocketConsumer): async def connect(self): ... async def disconnect(self, close_code): ... async def receive(self, text_data): ... async def chat_message(self, event): await self.send(text_data=json.dumps({"event": event})) In this example, self.send is called once for each instance of SomeConsumer. However, I don't think all of the chat_message methods get called concurrently, at the same time for each instance, since I notice a delay in the display of the javascript data when I have multiple windows open. Ideally, I would like the data to display at the exact same time across X number of windows. Is there a way to make this work? I tried to create tasks and then await them once number_of_chat_message_calls = number_of_instances, like this: async def chat_message(self, event): SomeConsumer.count+=1 SomeConsumer.tasks.append(asyncio.create_task(self.send(text_data=json.dumps({"event": event})))) if SomeConsumer.count == SomeConsumer.consumers: done, pending = await asyncio.wait(SomeConsumer.tasks) SomeConsumer.tasks.clear() SomeConsumer.count = 0 but it still doesn't display the data synchronously. Is there any way to achieve this? -
How to improve reliability of Django-Q Schedule Tasks
My project currently has about 300 scheduled tasks. Some of these run every hour on the hour and some run once a day (at midnight). The tasks make API calls to third party API's. This is the current set up of my Q_CLUSTER Q_CLUSTER = { 'name': 'DataScheduler', 'workers': 3, 'timeout': 15, 'retry': 300, 'queue_limit': 10000, 'bulk': 10, 'max_attempts': 1, 'orm': 'default' } Of the 300 tasks, about 120 of them fail (different ones every time). If I manually trigger these to run they pass so there isn't anything wrong with the actual request. I believe the q cluster can't process all of the tasks when they are triggered at the same time. I think this can be improved by tweaking the Q_CLUSTER settings but I'm unsure how best to do this. I've tried running through the documentation https://django-q.readthedocs.io/en/latest/configure.html But I'm unsure how to improve the success rates of the scheduled tasks. I've struggled to find any other articles or documentation to explain how best to utilise these settings. My question is - how can I improve these settings to ensure the tasks pass? With time I will have more scheduled tasks so looking to address now before it gets … -
Django generating a query in the group
I have models like this: class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) class Project(models.Model): name = models.CharField(max_length=128) class EmployeeProject(models.Model): project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name='employee_projects', ) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) role = models.ForeignKey(ProjectRole, on_delete=models.CASCADE) skill_level = models.ForeignKey(SkillLevel, on_delete=models.CASCADE) hourly_rate = models.DecimalField(decimal_places=2, max_digits=9) class TaskRole(LogOnSaveMixin, DiffModel): task = models.ForeignKey( Task, on_delete=models.CASCADE, related_name='roles', ) estimated_hours = models.FloatField(null=True, blank=True) And I have a queryset like this: qs = Task.objects.all() user = self.request.user host_roles = EmployeeProject.objects.filter( employee=user.employee, ) qs = qs.annotate( total_estimated_hours=Sum('roles__estimated_hours'), ) open_tasks_qs = qs.filter( Q(project__in=host_roles.values('project_id')), ).filter( ( Q(total_estimated_hours__isnull=False) ), ) qs = open_tasks_qs | qs.filter(author=user).distinct() qs = qs.values('id') qs = qs.distinct() return qs The problem is that this query yields an error, saying that more than one row returned by a subquery used as an expression The corresponding sql looks like this: SELECT DISTINCT "tasks_task"."id" FROM "tasks_task" LEFT OUTER JOIN "tasks_taskrole" ON ( "tasks_task"."id" = "tasks_taskrole"."task_id" ) GROUP BY "tasks_task"."id", ( SELECT U0."project_id" FROM "tasks_employeeproject" U0 WHERE U0."employee_id" = 1 ) HAVING ( ( "tasks_task"."project_id" IN ( SELECT U0."project_id" FROM "tasks_employeeproject" U0 WHERE U0."employee_id" = 1 ) AND SUM( "tasks_taskrole"."estimated_hours" ) IS NOT NULL ) OR "tasks_task"."author_id" = 1 ) ORDER BY "tasks_task"."id" DESC There are two questions: How … -
How to send data from other Django app to other server
How to send data from other Django app to other server using HTML file (client side), with cors I’ve tried disabling cors -
How to handle POST net::ERR_CONNECTION_REFUSED error in Axios Vue.js django
I am using axios to send the data for the backend but it keeps break, what should i do? in .then(response => { this.$router.push('/Log-in') return response }) i returned the "response" because the console is saying "error 'response' is defined but never used" vue.js file import axios from 'axios' if (!this.errors.length) { const formData = { username: this.username, password: this.password, email: this.email } axios .post('/api/v1/users', formData) .then(response => { this.$router.push('/Log-in') return response }) .catch(error => { if (error.response) { for (const property in error.response.data) { this.errors.push(`${property}: ${error.response.data[property]}`) } console.log(JSON.stringify(error.response.data)); } else if (error.massege) { this.errors.push('Something went wrong, Please try again!') console.log(JSON.stringify(error)); } }) } setting.py django CORS_ALLOWED_ORIGINS = [ 'http://localhost:8000', 'http://127.0.0.1:8000/' ] -
I want to get the specific reviews from a different model Django
I am making a review section for my record company, but I have a hard time figuring out how I can get the specific reviews for the specific album, I pass in an id to a template called "Albumin" to get the exact album, but how do I get the reviews? models: class albums(models.Model): title = models.CharField(max_length=100) description = models.TextField() release_date = models.CharField(max_length=10) artist = models.CharField(max_length=100) genre = models.CharField(choices=GENRE_CHOICES, max_length=20) image = models.ImageField(default='default2.jpg', upload_to='album_pics') slug = models.SlugField() def __str__(self): return self.title class ReviewRating(models.Model): album = models.ForeignKey(albums, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject or f"ReviewRating #{self.pk}" views: def albuminfo(request, id): album = albums.objects.get(id = id) reviews = ReviewRating.objects.all() return render(request, "home/AlbumInfo.html", {'album' : album, 'reviews' : reviews}) def submit_review(request, album_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ReviewRating.objects.get(user__id=request.user.id, album__id=album_id) form = ReviewForm(request.POST, instance=reviews) form.save() messages.success(request,'Your review has been updated') return redirect(url) except ReviewRating.DoesNotExist: form = ReviewForm(request.POST) if form.is_valid(): data = ReviewRating() data.subject = form.cleaned_data['subject'] data.review = form.cleaned_data['review'] data.rating = form.cleaned_data['rating'] data.ip = request.META.get('REMOTE_ADDR') data.album_id = album_id data.user_id = request.user.id data.save() messages.success(request, 'Your review has … -
Safe to use django ORM from gevent greenlets or threads under WSGI?
I think the answer is “yes” but is there some official documentation I can point to? I try to inspect what is happening under the hood but have trouble convincing myself -- see this code snippet, which compares thread locals and DB connection objects between gevent greenlets and gevent threads: import time from django import db import gevent from gevent.pool import Pool from gevent.threadpool import ThreadPool def my_view(request): pool = Pool(4) start = time.time() for _ in range(4): def foo(x): time.sleep(x) print(db.connections['default']) print(threading.local()) pool.spawn(foo, 1) pool.join() delay = time.time() - start print('Running "time.sleep(1)" 4 times with 4 greenlets. %.3fs' % delay) threadpool = ThreadPool(4) start = time.time() for _ in range(4): def bar(x): time.sleep(x) print(db.connections['default']) print(threading.local()) threadpool.spawn(bar, 1) threadpool.join() delay = time.time() - start print('Running "time.sleep(1)" 4 times with 4 threads. %.3fs' % delay) I guess the django ORM is thread-safe, but I also want to make sure that each thread is getting its own DB connection. This appears to be the case from the output: <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92aef538b0> <gevent._gevent_clocal.local object at 0x7f92809a2be0> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92810fefd0> <gevent._gevent_clocal.local object at 0x7f92809a2c40> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f92810f1af0> <gevent._gevent_clocal.local object at 0x7f92809a2ca0> <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f9281068190> <gevent._gevent_clocal.local object at 0x7f92809a2d00> Running "time.sleep(1)" … -
Django interface buttons no longer work after connecting to IP 0.0.0.0:8000
I am trying to access Django website from a secondary device using python manage.py runserver 0.0.0.0:8000 The primary device that my laptop is connected to the same network as my secondary device, and I have turned off all firewalls. Also, I have configured the Allowed Host in settings.py file in Django by adding the IP address of the common connected data (192.168.61.130). However, when I access the website, the buttons on the website does not direct me to any page that I have linked in urls.py file. ALLOWED_HOSTS = ['192.168.61.130', '127.0.0.1', 'localhost'] From the example below, I have pressed the log in button and the POST request does show on the terminal. However, it does not direct me to the next page when I connect to the IP: 0.0.0.0:8000. The website works completely fine when I run on local host. Not sure why this is so and really need help on this. Hope to get any advice. -
Redis Broker getting OOM as "*.reply.celery.pidbox" keys count increased
Recently I have pushed around 10-15k tasks into celery by iterating in a for loop. Attaching below code for reference. for index, htl_urls_chunk in enumerate(iteration_grouper(htl_urls, n=10, chunk_type=list)): update_cache_for_hotel_detail_page_chunk.apply_async(kwargs={'htl_urls_chunk': htl_urls_chunk}) the length of htl_urls is around: 10-15k. Total tasks pushed ~ 1500 at given point of time. This lead to creation of below keys in redis: 01f6ebdb-361b-32ec-afe9-2eb7c8511288.reply.celery.pidbox 6292044c-a816-349a-a159-682536ea9bfa.reply.celery.pidbox Each key is of 150MB and total 29 keys created (4.24GB) This lead to OOM issue of my redis cluster. Can anyone suggest why this is happening ? I have tried to explored why these keys are being created in my redis cluster, but not able to reach any conclusion so far. -
Using MySQL CONVERT_TZ in django ORM
I am using the CONVERT_TZ MySQL function to convert datetime saved into the database into other timezone while running query. But I want to do the same thing with Django ORM due to performance issues with the next steps. Below is the code I am doing. boarding_stations = StationPoints.objects.filter(bus_id__in=bus_ids, station_id=sourceStation).annotate(coverted_timezone=Func(F('reachedTime'), '-08:00', '+05:30', function='CONVERT_TZ')) The above code returns FieldError as it says Cannot resolve keyword '-08:00' into the field. What's the correct way to use this MySQL function?