Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot migrate in django using mysql
I'm trying to migrate my data from sqlite to mysql database but when I'm migrating the models, i'm getting the following error: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2059, "Plugin http could not be loaded: The specified module could not be found. Library path is 'http.dll'") django.db.utils.OperationalError: (2059, "Plugin http could not be loaded: The specified module could not be found. Library path is 'http.dll'") what can be the problem? I'm using Django 4.0.5, python 3.10.2, mysqlclient 2.1.1 -
Django signals: why create and save profile on 2 different functions?
I noticed from many django tutorials that Profiles are created and/or saved upon User post_save signal. Most codes go like this: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() My question is, why do they use 2 functions instead of just one like this? @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() To my understanding, (1) when a new user is created, a new profile will also be created and saved thereafter; and (2) when a user is updated, its profile will also be updated but not created. Am I missing something? -
How do I convert this postgresql code to Django code?
This is my code in Postgresql -- create CREATE TABLE EMPLOYEE ( empId INTEGER PRIMARY KEY, username TEXT NOT NULL, userrole TEXT NOT NULL, roles TEXT NOT NULL, accesses TEXT NOT NULL ); -- insert INSERT INTO EMPLOYEE VALUES (0001, 'Clark','President', 'Admin','privileged'); INSERT INTO EMPLOYEE VALUES (0002, 'Dave','sales rep', 'Operational role','not privileged'); INSERT INTO EMPLOYEE VALUES (0003, 'Ava','finance manager', 'Managerial role','privileged'); -- fetch SELECT * FROM EMPLOYEE; SELECT *, CASE WHEN (roles, accesses) IN ( ('Admin','privileged'), ('Operational role','not privileged'), ('Managerial role','not privileged') ) THEN 'GRANTED' ELSE 'REVOKED' END AS permissions FROM employee; -
Helping with models in DjangoREST
I am making API in Django rest and I am not sure what to do with groupID. I have just 1 model - countries. I have assigned request and response. Request for POST is : {"name": "Czech Republic","countryCode": "CZ"} Response is: { "name": "Czech Republic","countryCode": "CZ","id": 123,"createdAt": "2022-08-21T11:49:39.239Z", "groupId": 123 } And I am supposed to create API for that. I am not sure what to do with groupI in model. class Countries(models.Model): name = models.CharField(unique=True, max_length=100) countryCode = models.CharField(unique=True, max_length=100) createdAt = models.DateTimeField(auto_now=True) groupId = models.CharField(unique=True, max_length=100) def __str__(self):return self.name -
Passing Information from Another Django Model Createview - Listing and Reviews
I have two Django apps, one with listings and another for accounts. Within the accounts app, I have a reviews model attached to the account, and I want users to have the ability to create a review for a listing that ultimately attaches to the account, not the listing, that way any listing reviews under a particular account are attached to the account itself, not necessarily the listing. Part of the reviews model is the listing and listing_author fields, that way I can filter on these fields later on. From the listing detail page, I want users to be able to click "Create Review" and create a review for a listing that is under the profile. I am running into an issue where I cannot pass the user_id and listing_id in the CBV CreateView, as the information from the listing_detail page (including these two fields) is not passed. Accounts Models.py class ProfileReviews(models.Model): user = models.ForeignKey( get_user_model(), on_delete = models.CASCADE, related_name = 'reviews' ) listing_item_id = models.UUIDField() review = models.TextField(max_length = 1000) rating = models.IntegerField() reviewer = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.review Listings Model.py class Listing(models.Model): item_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) lender = models.ForeignKey( get_user_model(), on_delete … -
How to prevent multiple login for a jwt token based authentication in django rest-framework?
https://dev.to/fleepgeek/prevent-multiple-sessions-for-a-user-in-your-django-application-13oo i have followed the above article for achieving preventing multiple login. But the above process is not working and it does not through any errors. What i have done to test after copying above code> I have loged in with user credentials in postman. I have collected the jwt token which is a response. I have stored the first jwt token in notepad. next i have loged again. Now i have used old jwt token ( i mean first token) to get some data and i am able to access it. What i am expecting here is. I don't want first token to be working anymore. Please help me. Thanks in advance. -
Creating a model with a ManyToMany relationship to users, how to extend Users information
I am trying to create a model that has (perhaps several) ManyToMany relationships with users. Basically the model is suppose to hold an event (Madklub) in which users can join. Now this I already successfully implemented, however now I want to make the users be able to bring guests (Users not registered), now this simply need to be a number on how many guests a specific user is bringing, but the amount of guests needs to be tied to the user somehow, so that in case the user leaves the event then the guests are also decremented from the total amount of guests. The following is my current model, DIET_OPTIONS = ( ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ('meat', 'Meat') ) class Madklub(models.Model): owner = models.ForeignKey(MyUser, related_name="owner", null=False, blank=False, on_delete=models.CASCADE) dish = models.CharField(max_length=100, null=True, blank=True) date = models.DateField(null=False, blank=False, unique=True) guests = ??? active = models.BooleanField(default=True) vegan_participants = models.ManyToManyField(MyUser, related_name="vegan_participants", blank=True) vegetarian_participants = models.ManyToManyField(MyUser, related_name="vegetarian_participants", blank=True) meat_participants = models.ManyToManyField(MyUser, related_name="meat_participants", blank=True) diet = ArrayField( models.CharField(choices=DIET_OPTIONS, max_length=10, default="vegetarian") ) class Meta: ordering = ('date',) class GuestInfo(models.Model): ??? So right now I have it so that when a user joins the Madklub (event) they choose one of three options (meat, vegetarian, vegan). And depending … -
How display django models with datetime field in chart using chartjs
Hi everyone I am stuck on a problem, I have a django model which is called ScanBatch, now that Scan batch is made up of fields like the timestamp (datetime field), domain (char field) and total ids found (integer field) My chart code is : const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [], datasets: [] }, options: { scales: { yAxes: [{ id: 'A', type: 'linear', position: 'left', }, { id: 'B', type: 'linear', position: 'right', ticks: { max: 1, min: 0 } }] } } }); models code is class ScanBatch(models.Model): domain = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) valid_ids_found = models.IntegerField(default=0) the trick question is how do I make the chart show the batch data historically from django and then output it to the chart I want to show the batches historically by date and also group by domain -
Giving an error messagebox for the submission of a form : Django
i was following a tutorial and after finishing it i came across and error which should only be shown if the form i have submitted is invalid. I am using recaptcha and several other apis these are few of my functions result = "Error" message = "There was an error, please try again" class AccountView(TemplateView): ''' Generic FormView with our mixin to display user account page ''' template_name = "users/account.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def profile_view(request): ''' function view to allow users to update their profile ''' user = request.user up = user.userprofile form = UserProfileForm(instance = up) if request.is_ajax(): form = UserProfileForm(data = request.POST, instance = up) if form.is_valid(): obj = form.save() obj.has_profile = True obj.save() result = "Success" message = "Your profile has been updated" else: message = FormErrors(form) data = {'result': result, 'message': message} return JsonResponse(data) else: context = {'form': form} context['google_api_key'] = settings.GOOGLE_API_KEY context['base_country'] = settings.BASE_COUNTRY return render(request, 'users/profile.html', context) class SignUpView(AjaxFormMixin, FormView): ''' Generic FormView with our mixin for user sign-up with reCAPTURE security ''' template_name = "C:/Users/adity\OneDrive/Documents/Coding/python/py_tutorial/djangotutorial/googleapi project/googapiproj/templates/users/sign_up.html" form_class = UserForm success_url = "/" #reCAPTURE key required in context def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == … -
Session variable not getting updated during session in django
I'm new to web development and trying to create an auction website as a course project. I'm trying to create a user-specific watchlist. It's able to add a product to the watchlist but when I go to delete an item from the watchlist it doesn't get deleted until I log out and log in again. Here is my code: views.py: def watchlist(request, item_id=None): if request.method == "POST": for item in request.session["watchlist"]: if item["id"] == item_id: ind = request.session["watchlist"].index(item) modified = request.session["watchlist"][:ind] + request.session["watchlist"][ind + 1:] request.session["watchlist"] = modified break data = request.session["watchlist"] return render(request, "auctions/watchlist.html", { "data": data }) watchlist.html: {% block body %} {% if user.is_authenticated %} <h2>Watchlist</h2> <ol> {% for item in data %} <li> <div style="display: flex;"> <div> <img src="{{ item.image_url }}" alt="No image"> </div> <div> <a href="{% url 'listing' item.id %}"><h4>{{ item.title }}</h4></a> </div> <div> Current Price: {{ item.current_price }} </div> <div> <form action="{% url 'watchlist_del' item.id %}" action="post"> <input type="submit" value="Delete"> </form> </div> </div> <div style="border-bottom: 1px solid black;"></div> </li> {% empty %} <h1>No items in watchlist</h1> {% endfor %} </ol> {% endif %} {% endblock %} I checked session data through Django-admin and found that even after deleting an item, its data was not … -
Python Django: ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import) (......)
In a Django project, I need to import class-A from file-1 in file-2. and import class-B from file-2 in file-1. These classes have their unique methods, and I want to use these methods within another file (like description above). I'm working with: Python 3.8.10 (within a virtual environment) Windows 10 - 64 bit (latest build) Django 4.0.4 When I runpython manage.py runserver, I see errors below: (my_ea_proj) PS F:\my_ea_proj\ea_proj> python.exe .\manage.py runserver Traceback (most recent call last): File ".\manage.py", line 30, in <module> main() File ".\manage.py", line 13, in main django.setup() File "F:\my_ea_proj\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "F:\my_ea_proj\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "F:\my_ea_proj\lib\site-packages\django\apps\config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "C:\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "F:\my_ea_proj\ea_proj\ea_app\models.py", line 16, in <module> from .login_request_based import full_request File "F:\my_ea_proj\ea_proj\ea_app\login_request_based.py", line 10, in <module> from ea_app.all_utils.ea_utils import ea_utils_class File "F:\my_ea_proj\ea_proj\ea_app\all_utils\ea_utils.py", line 10, in <module> from ea_app.login_request_based import full_request ImportError: cannot import name … -
Django DeleteView not make delete
I want to convert user deletion from FBV to CBV My FBV def delete_student(request, pk): student = get_object_or_404(Student, pk=pk) student.delete() return HttpResponseRedirect(reverse("students:get_students")) My CBV class DeleteStudentView(DeleteView): model = Student form_class = StudentForm template_name = "students/students_list.html" success_url = reverse_lazy("students:get_students") student_list.html <td><a type="button" class="btn btn-danger" href="{% url 'students:delete_student' student.pk %}">Delete</a> </td> There is no error, but no selection occurs. What could be the problem? -
Create object using django POST method
I have a question regarding Djanog views I have to Create a Task object using the string(the object)that I am getting from POST method. This string is equal to the name field in the Task object. the POST request contains : task \ username. the page is in this url: http://localhost:8000/tasks/ after adding the task the user should see something like this : Task Created: 'Task_Name_Here' this was my code and i know its not correct: def list_create_tasks(request): if request.method == 'POST': task_name = request.POST.get('task_name') task = Task.objects.create(name=task_name) return HttpResponse(f"Task Created: '{task}'") thanks for helping. -
Trying to use whois in python but getting file not found error in windows
I am trying to use whois but getting this error: I have also installed https://docs.microsoft.com/en-us/sysinternals/downloads/whois and it is working fine in my cmd but when I try it with python it shows the above error. I have installed both python-whois and whois using the below commands but still getting the same error. pip install python-whois pip install whois -
i wanted to create a Private Route but error arose
PrivateRoute.js import { Route, Navigate } from "react-router-dom"; const PrivateRoute = ({children, ...rest})=>{ const authenticated =false; console.log('it works');//it is not showing return( <Route {...rest}>{!authenticated ? <Navigate to="/"/>: children}</Route> ) } export default PrivateRoute; App.js import { BrowserRouter, Routes, Route } from 'react-router-dom'; import Add from './Pages/Add'; import EmployeeList from './Pages/EmployeeListAdmin/EmployeeList' import EmployeeForm from "./Pages/EmployeeListAdmin/EmployeeForm" import SharedEmployeeLayout from "./Pages/EmployeeListAdmin/SharedEmployeeLayout" import Index from './Pages/Index' import Error from './Pages/Error' import MyProfile from './Pages/MyProfile' import OrderList from './Pages/OrderList' import Cart from './Pages/CartAdmin/Carts' import SingleCart from './Pages/CartAdmin/SingleCart' import SharedCartLayout from './Pages/CartAdmin/SharedCartLayout' import Producer from './Pages/ProducerListAdmin/Producer' import ProducerForm from './Pages/ProducerListAdmin/ProducerForm' import SharedProducerLayout from './Pages/ProducerListAdmin/SharedProducerLayout' import SharedLayout from './Pages/SharedLayout' import NoPage from './Pages/NoPage' import Supplier from "./Pages/SupplierAdmin/Supplier" import SupplierForm from "./Pages/SupplierAdmin/SupplierForm" import SharedSupplierLayout from "./Pages/SupplierAdmin/SharedSupplierLayout" import Delivery from "./Pages/DeliveryAdmin/Delivery" import DeliveryForm from "./Pages/DeliveryAdmin/DeliveryForm" import SharedDeliveryLayout from "./Pages/DeliveryAdmin/SharedDeliveryLayout" import '../src/Assets/styles/App.css'; import PrivateRoute from './Helpers/PrivateRoute' // import {AuthProvider} from './Auth/AuthContect' function App() { return ( <BrowserRouter> <Routes> {/* <AuthProvider> */} <Route path="/" element={<SharedLayout />}> <Route index element={<Index />} /> <PrivateRoute path="Delivery" element={<SharedDeliveryLayout />} > <PrivateRoute index element={<Delivery />} /> <PrivateRoute path='DeliveryForm' element={<DeliveryForm />} /> </PrivateRoute> <PrivateRoute path="Supplier" element={<SharedSupplierLayout />}> <PrivateRoute index element={<Supplier />} /> <PrivateRoute path='SupplierForm' element={<SupplierForm />} /> </PrivateRoute> <PrivateRoute path="EmployeeList" element={<SharedEmployeeLayout />}> <PrivateRoute index element={<EmployeeList />} /> … -
Dimensional Models in Django
Django typically uses CRUD tables for it's data modelling. Is it possible to create a dimensional model in django? Example data for a given dimensional table could be: id start_date end_date value 1 1999-02-28 2022-01-01 VALUE1 1 2022-01-01 2022-08-18 VALUE2 1 2022-08-18 9999-12-31 VALUE3 -
How to use django_select2 with django 'choices' field option for selecting option in second dropdown based on first dropdown?
I've already looked at this answer, but it did not help since it does not feature choices option. from django.db import models class SelectCar(models.Model): BRAND= ( ('BMW','BMW') ('Mercedes','MR') ) brand = models.CharField(max_length=10, choices=BRAND, default="BMW") CAR_MODELS = ( ('X1','X1') ) -
multiple model objects saved to db even though view screens out MyModel.DoesNotExist breaking application
I am getting the following error trying to retrieve a user profile from the mongodb: New searches for user 555555555 [{'search_term': 'ibm'}, {'search_term': 'ry'}] Internal Server Error: /users/555555555 Traceback (most recent call last): File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/cchilders/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/cchilders/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/cchilders/projects/stocks_backend/users/views.py", line 50, in get_user_profile user = UserProfile.objects.get(user_id=user_id) File "/home/cchilders/.local/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/cchilders/.local/lib/python3.10/site-packages/django/db/models/query.py", line 433, in get raise self.model.MultipleObjectsReturned( users.models.UserProfile.MultipleObjectsReturned: get() returned more than one UserProfile -- it returned 2! [21/Aug/2022 09:45:31] "POST /users/555555555 HTTP/1.1" 500 76920 Having multiple user profiles is application breaking and there should only be one for each user. I am also getting duplicates in another model StockInfo. my view appears to only save a new user when none exists for that user id so I'm confused users/views.py: from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json from helpers.view_functions import parse_request_body from .models import UserProfile @csrf_exempt def get_user_profile(request, user_id): if request.method == 'GET': try: user = UserProfile.objects.get(user_id=user_id) print("user found") except UserProfile.DoesNotExist: print("user does not exist exception") profile = UserProfile() profile.user_id = … -
Django app on Digitalocean takes ages to old - worker always times out -- how ti investigate and fix?
I recently deployd a small Django app on Digitalocean's app platform but for some reason the app is super slow. This is the network debug when hitting a small, static site (the view take some ms in development to execute) which doesn't even hit the db. This is the log from Digitalocean server which is basically the same for all pages I'm trying - the worker always times out. [cherry] [2022-08-21 09:53:58] 10.244.17.174 - - [21/Aug/2022:09:53:58 +0000] "GET /search/ HTTP/1.1" 200 5591 "https://cherry.trading/search/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36" [cherry] [2022-08-21 09:54:29] [2022-08-21 09:54:29 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:169) [cherry] [2022-08-21 09:54:29] [2022-08-21 09:54:29 +0000] [169] [INFO] Worker exiting (pid: 169) [cherry] [2022-08-21 09:54:30] [2022-08-21 09:54:30 +0000] [177] [INFO] Booting worker with pid: 177 I'm on basic subscription with some 512 mb ram (1 CPU) -
Nginx not serving static files for Django website when using with gunicorn
I have made my first Django website and I want to deploy it on Digital ocean. I am using a $4 server option. I followed this tutorial step by step as it is. But, in the end, no CSS is being applied to the admin login page, and as they have mentioned in their tutorial, it means that static files are not being served by Nginx. I did not upload my project files as I first wanted to see if I can get the server running properly with the bare minimum. I have read almost all the answers that I can find on the internet, but just can't get Nginx to serve the static files. I am stuck on this problem for weeks now. Can someone help me, please? -
restrict django choice field on django admin per user
I have an exam like this: class Exam(BaseModel): ... STATE_CHOICES = ( (PASS, PASS), (FAILED, FAILED), (GREAT, GREAT), state = models.CharField(max_length=15, choices=STATE_CHOICES, default=PASS) ... Inside Django admin, I want the user with group X to be able to only change the state only from FAILED to PASS. and users with group Y be able to change the state from FAILED to PASS and PASS to GREAT. here is my admin.py: @admin.register(Exam) class ExamAdmin(NestedModelAdmin): list_display = ('state',) Does anyone know a solution for it? -
Why the payload is not valid. serializers.ModelSerializer | Where is problem ? | Django | views
I was writing the api for booking section. I am trying to make a management ptoject. The registration have feilds and i have to make rest api. When I am passing values from postman it is showing these error Models.py class BookingRegister(models.Model): STATUS = [('Booked','Booked'), ('InTransit','InTransit'), ('AtDestination','AtDestination'), ('Delivered','Delivered'), ('Return','Return')] PAYMENT_TYPE = [('Paid','Paid'), ('ToPay','ToPay'), ('ToBeBilled','ToBeBilled')] TRANSPORT_MODE = [('AIR','AIR'), ('ROAD','ROAD'), ('WATER','WATER')] PACKAGE_TYPE = [('TIN','TIN'), ('BOX','BOX'), ('BUNDLE','BUNDLE'), ('CARTOON','CARTOON')] TAX_PERCENTAGES = [(5,'5%'), (8,'8%'), (10,'10%'), (15,'15%'), (18,'18%')] RATE_AS_PER = [('QTY','QTY'), ('WT','WT')] id = models.AutoField(primary_key=True) #bookingDetails=models.OneToOneField(BookingRegisterDetails, on_delete=models.CASCADE) status = models.CharField(max_length=15, choices=STATUS) paymentType = models.CharField(max_length=10, choices=PAYMENT_TYPE) consignor = models.ForeignKey(Party, on_delete=models.CASCADE, related_name='consignor') consignee = models.ForeignKey(Party, on_delete=models.CASCADE, related_name='consignee') origin = models.ForeignKey(City, on_delete=models.CASCADE, related_name='origin') destination = models.ForeignKey(City, on_delete=models.CASCADE, related_name='destination') bookingPoint = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name='bookingPoint') deliveryPoint = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name='deliveryPoint') bookingDate = models.DateField() transportMode = models.CharField(choices=TRANSPORT_MODE, default='ROAD', max_length=15) createdTime = models.DateTimeField(editable=False, default=datetime.now) updatedTime = models.DateTimeField(editable=False, default=datetime.now) packageType = models.CharField(choices=PACKAGE_TYPE, default='CARTOON', max_length=15) itemName = models.CharField(max_length=30) quantity = models.IntegerField() actualWeight = models.FloatField(default=0) grossWeight = models.FloatField(default=actualWeight) taxPercentage = models.IntegerField(choices=TAX_PERCENTAGES) rateAsPer = models.CharField(choices=RATE_AS_PER, max_length=5) rate = models.FloatField() serviceCharge = models.FloatField(default=0) bookingCharge = models.FloatField(default=0) loadingCharge = models.FloatField(default=0) unloadingCharge = models.FloatField(default=0) total = models.FloatField(default=0) def __str__(self) -> str: return str(self.id)+" "+self.status+" "+self.paymentType+" "+self.consignor+" "+self.consignee <br> views.py class BookingRegisterAPI(APIView): def get(self, request, id=None, format=None): if id: try: booking=BookingRegister.objects.get(pk=id) … -
How to avoid repeating a queryset in Django views.py
what is the best way to avoid repeating a chunk of code that is being used in more than one class view? I'm repeating these 2 lines in couple of classes moderator = ServerModerator.objects.get(user=request.user) server = Server.objects.get(Q(creator=request.user) | Q(moderators=moderator), Q(tag=server_tag)) I've tried to create a function inside models.py like this: class Server(models.Model): ... creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='user_servers') moderators = models.ManyToManyField('ServerModerator', related_name='server') def moderator_checker(self, current_user): moderator = ServerModerator.objects.get(user=current_user) server = Server.objects.get(Q(creator=current_user) | Q(moderators=moderator),Q(tag=self.tag)) return server but this doesn't work views.py: class TagsAndFlairsView(LoginRequiredMixin, View): form_class = CreatePostTagForm form_class_2 = CreateUserTagForm def get(self, request, server_tag): ... # moderator = ServerModerator.objects.get(user=request.user) # server = Server.objects.get(Q(creator=request.user) | Q(moderators=moderator), Q(tag=server_tag)) check = Server.moderator_checker(request.user) server_post_tags = check.post_tags.all() server_user_tags = check.user_tags.all() return render(request, 'servers/tags-flairs.html', {"server":check, "server_post_tags":server_post_tags, "server_user_tags":server_user_tags, "create_post_tag_form":create_post_tag_form, "create_user_tag_form":create_user_tag_form}) -
How can I isolate a function within a view to make it run in the background in Django?
So I deployed my very first app to Digitalocean which is super exciting but also comes with some differences to a development environment. I do have a view that calls a function to update data requested from an API that takes some 2-3 minutes. Digitalocean however terminates the worker - for good reasons - after 30 seconds, so the process is aborted. [2022-08-21 08:40:10 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:25) How can I isolate run_post_publisher() in my view such as the view is finished and the "background" process can take the time it needs? This is the view and the mentioned function run_post_publisher() def execute_post_publisher(request): company = run_post_publisher() return HttpResponse(f'New post about {company} was published') I'm not sure if there is any Django built-in tools to make this happen? -
Boolean Field Django Can't Migrate to Postgresql
Django Version 4.1 I have created migration in SQLite3 and want to change to Postgresql when i connect to Postgresql i've this error django.db.utils.ProgrammingError: cannot cast type smallint to boolean LINE 1: ...R COLUMN "isProduct" TYPE boolean USING "isProduct"::boolean this is my model from django.db import models class Item(models.Model): name = models.CharField(max_length = 150) slug = models.SlugField(unique = True, db_index=True, null=True) pic = models.URLField(max_length = 400) address = models.CharField(max_length = 150) phone = models.CharField(max_length = 15) price = models.IntegerField() original_link = models.URLField(max_length = 400) description = models.TextField(max_length = 1500) additional_desc = models.TextField(max_length = 1500,default='') material = models.TextField(max_length = 200, default = '') weight = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0) weight_unit = models.CharField(max_length = 4, default = '') color = models.CharField(max_length = 50, default = '') dimension_length = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0) dimension_width = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0) dimension_height = models.DecimalField(max_digits = 12, decimal_places = 2, default = 0) dimension_unit = models.CharField(max_length = 4, default='') isProduct = models.BooleanField(default = True) furniture_location = models.CharField(max_length = 100, default='') def __str__(self): return self.name i've tried to change BooleanField to SmallIntegerField, PositiveSmallIntegerField, and IntegerField and the error still says the same …