Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Django project while trying to dockerise [duplicate]
im trying to run my django project as a Webserver. Dockerfile: FROM python:3.8.3-slim WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 #install dependencies RUN pip install --upgrade pip RUN pip install --upgrade setuptools COPY ./webserver /usr/src/app/ RUN pip install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 8000 CMD [ "python", "manage.py", "runserver", "0.0.0.0:8000" ] while the makemigrations is running i get the error that the DB tables dont exist. I also tried to run makemigrations after the Container started. But that also does not work and i get the same error. I made the github Repo public if you would like to test it for yourself: my Github Repo thank you for your help in advance. -
Langchain : Querying from postgresql database using SQLDatabaseChain
i am querying postgresql database using langchain. For this i am using Claude llm whose api key is anthropic_api_key. I am connecting postgresql database using SQLDatabase.from_uri() method. this is my code inside file postgres_db.py from langchain import SQLDatabase from constants import anthropic_key from langchain.chat_models import ChatAnthropic from langchain_experimental.sql import SQLDatabaseChain from langchain.agents.agent_toolkits import SQLDatabaseToolkit from langchain.agents import create_sql_agent from langchain.agents.agent_types import AgentType import os os.environ["ANTHROPIC_API_KEY"] = anthropic_key API_KEY = anthropic_key # Setup database db = SQLDatabase.from_uri( f"postgresql+psycopg2://postgres:umang123@localhost:5432/delhi_cime_2", ) # setup llm llm = ChatAnthropic(temperature=0) # Create db chain QUERY = """ Given an input question, first create a syntactically correct postgresql query to run, then look at the results of the query and return the answer. Use the following format: "Question": "Question here" "SQLQuery": "SQL Query to run" "SQLResult": "Result of the SQLQuery" "Answer": "Final answer here" "{question}" """ # Setup the database chain db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True) def get_prompt(): print("Type 'exit' to quit") while True: prompt = input("Enter a prompt: ") if prompt.lower() == 'exit': print('Exiting...') break else: try: question = QUERY.format(question=prompt) result = db_chain.run(question) print(result) except Exception as e: print("eeeeeeeeeeeeeeeeeee",e) pass get_prompt() when i am executing the above script using python postgres_db.py command stuck in this error … -
Django multiple database
I'm using two same structure database in Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database1', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' }, 'db_1402': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database2', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' } } and user select a database in login page. I want to use user selected database in whole project and all Models read and write in user selected database. I try to use database router but user logout automatically. I define bellow decorator to save database name in connections['default'].alias and pass it to database router: from django.db import connections def db_login_required(login_url): def decorator(view): def wrapper_func(request, *args, **kwargs): if not request.user.is_authenticated: next_url = request.get_full_path() return redirect(f'{reverse(login_url)}?{urlencode({"next": next_url})}') connections['default'].alias = request.session.get('database', 'default') return view(request, *args, **kwargs) return wrapper_func return decorator and then I create a database router like this: class SessionDatabaseRouter(object): def db_for_read(self, model, **hints): return connections['default'].alias def db_for_write(self, model, **hints): return connections['default'].alias def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True but after login suddenly user logout automatically. How can fix this? -
Django added .well-known before static/style.css and now the website doesn't see the style.css, why and how to fix?
I used: <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel = "stylesheet" href = "{% static 'whatsapp_widget/whatsapp_widget.css' %}"> And it always worked but today I opened the website and see that the website suddenly doesn't see the style.css. I've discovered that in the style's path it indicates the directory as /.well-known/static/style.css instead of just /static/style.css. Maybe this is the reason? How to fix? Many thanks in advance. -
Deployment of Django project on Railway using Nixpacks
Has anyone know about step by step process how to deploy Django project on Railway using Nixpacks? I really mean easy to follow step by step guide follow up my first steps. I am using Windows 10: Django project created with apps tested locally at http://127.0.0.1:8000/ Django project uploaded on github ... . . . -
Order details not saving to database in django
I am a beginner in django and i have been working on this ecommerce platform for a while now and i'm stuck in this place. Whenever i fill order details form, it is not saving to the database. Please i need your help Here is the form class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'phone_number', 'email', 'address_line_1', 'address_line_2', 'country', 'state', 'city', 'order_note'] Here is the view for the place order: def place_order(request, total=0, quantity=0,): current_user = request.user cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') grand_total = 0 tax = 0 for item in cart_items: total += (item.product.price * item.cart_quantity) quantity += item.cart_quantity tax = (3 * total) / 100 grand_total = total + tax if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone_number = form.cleaned_data['phone_number'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] data.order_note = form.cleaned_data['order_note'] data = form.save(commit=False) data.order_total = grand_total data.tax = tax data.ip = request.META.get('REMOTE_ADDR') # Save the data before generating the order number data.save() # Generate Order Number using the date, month, and day ordered yr = … -
Sphinx mock issue with django `get_user_model` in a custom pakage for django
I am creating a custom package for a django project. The package contains two authentication backends. I have modules configured as below, # Backend 1 module from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend UserModel = get_user_model() # ModelBackend = object # This will fix actual import issue and uses mocked import only class AuthBackendOne(ModelBackend): pass # Backend 2 module from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend UserModel = get_user_model() # here calls actual django method class AuthBackendTwo(ModelBackend): pass In my sphinx conf.py I haveautodoc_mock_imports = [ "django.conf", "django.contrib.auth" ] Issue: The problem is when I generate sphinx-build for docs, in module 2 it is trying to call actual django get_user_model(). It is not considering that was mocked. By trying myself, I found the issue was when I use ModelBackend to base my custom backend class. No issue in importing ModelBackend, but using that breaks the module 2. Just before using ModelBackend, I have re-assigned to object and run sphinx-build with successful. Findings: For my test trials I have printed the UserModel and its type in the above two methods, (I didn't call the get_user_model function in this test) cognito - CustomBackend 1 ldap - CustomBackend 2 In the … -
Axios POST Request using JWT in Vue3 and Django
Alright so as the title says I have a working Django application where my API creates a JWT key and saves it to my cookies. Now my frontend which is in Vue is supposed to send a form to the backend which is supposed to generate the jwt key and set it to my cookies. How do I go about this. My apologies if the writing is a little crude, I have been troubleshooting this for well over 4 hours. It shows me a 403 Forbidden error on my console. Here's a snippet of my code for the frontend: try { const response = await axios.post('link/', UserData) const jwtToken = response.data.jwt Cookies.set('jwt', jwtToken) this.confirmed = true console.log(this.confirmed) } catch(error) { console.log(error) } Everything is imported as it should be. But this is the underlying code. the django app sends a response with the jwt code. while this is not secure, it is needed for the troubleshoot. Please what can i do -
What does the code qs = super(OwnerDeleteView, self).get_queryset() do? [duplicate]
super().get_queryset() call will call the superclass's get_queryset() method depending on the MRO, but what do the parameters (OwnerDeleteView, self) mean? Is it the same as super().get_query_set()? Here is the full code from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin class OwnerUpdateView(LoginRequiredMixin, UpdateView): def get_queryset(self): print('update get_queryset called') """ Limit a User to only modifying their own data. """ qs = super(OwnerUpdateView, self).get_queryset() return qs.filter(owner=self.request.user) -
How to Filtter With Foreign key
I have a football stadium booking site -- the user logs in and then selects the stadium he wants to book and then selects the day and how much he wants to book the canned (an hour or two hours, etc.*) example: user John booked the stadium X on the day of 5 at 10 to 12 I want to make sure that there is no reservation at the same stadium, the same day and the same time, and if there is a reservation at the same data, he does not complete the reservation when i try to filtter in models with Foreign key pitche filter = OpeningHours.objects.filter(made_on=self.made_on,pitche=self.pitche,period = self.period).filter(Q(from_hour__range=in_range) | Q(to_hour__range=in_range)).exists() the error happens (relatedobjectdoesnotexist) OpeningHours has no pitche. my models is : enter image description here and views : enter image description here -
Getting error : django.db.utils.OperationalError: (2002, "Can't connect to server on 'db' (115)"), while trying to host django-mysql on docker
So basically I am trying to setup my Django-MySQL backend on Docker but I am getting errors and not able to run the server. I went through previous answers it didn't help that's why I am putting it here again. I have tried various ways , so i'll list them out and provide the errors as well. First of all here are the required files Django settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'PASSWORD': 'pass', 'HOST': 'db', # Use 'localhost' for a local MySQL server 'PORT': '3306', # MySQL default port } } DockerFile FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /Pizza-Delivery-System WORKDIR /Pizza-Delivery-System COPY . /Pizza-Delivery-System RUN apt-get update RUN apt-get update && apt-get install -y iputils-ping RUN pip install -r requirements.txt EXPOSE 8000 docker-compose.yml version: '3' services: db: hostname: 'db' image: mysql:8.1.0 environment: MYSQL_DATABASE: db_name MYSQL_ROOT_USER: "root" MYSQL_ROOT_PASSWORD: "password" ports: - "3306:3306" volumes: - ./mysql-data:/var/lib/mysql web: build: context: . dockerfile: Dockerfile command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - .:/Pizza-Delivery-System ports: - "8000:8000" depends_on: - db Now here is the method I have tried running all services at once docker-compose up -d In this case I got following error: manually running db service first … -
Add method to the Django CMS Page Model
Problem/Gap The Django CMS documentation clearly describes the process for extending the Page and Title Models. However, documentation on the possibility of adding a method such as the property method below is lacking, or I can't seem to find it. Note: The example provided works perfectly when I include it directly under the Django CMS Page model. This is not the preferred way of course. Question Say I want to add the below method to the Page (cms.models.pagemodel.Page) or Title Model (assuming they are likely to follow the same process) outside the CMS app. How can this be achieved? @property def my_custom_page_property(self): try: logger.info(f'Working....') return {} except Exception as e: logger.error(f'Error: {e}') return {} Attempt In a seperate app I added the code below, and migrated. The image field is properly configured and works fine. The method however doesn't seem to return anything. from cms.extensions import PageExtension from cms.extensions.extension_pool import extension_pool class MyCustomExtension(PageExtension): image = models.ForeignKey(Image, on_delete=models.SET_DEFAULT, default=None, blank=True, null=True) @property def my_custom_page_property(self): .. -
Why does one of my django model classes not return any data, when using a filter
Here is the first section of the view: class PropertyView(models.Model): idproperty = models.IntegerField(db_column='idProperty', primary_key=True, blank=False, null=False) # Field name made lowercase. address1 = models.CharField(db_column='Address1', max_length=50) # Field name made lowercase. address2 = models.CharField(db_column='Address2', max_length=50, blank=True, null=True) # Field name made lowercase. I am trying to filter on the first field, 'idproperty'. Here is the Django view: def property_detail(request, pk): prop = Propertytable.objects.get(pk=pk) propertylist = PropertyView.objects.filter(idproperty=prop.idproperty) context = { "property": propertylist, "thisprop": prop } return render(request, "property/property_detail.html", context) The 'prop' is returned correctly (from a mysql table). But the 'propertylist' returns nothing. I do not get any error. The database view, when run directly in mysql, returns the correct data. I constructed the model manually, and I wonder if I have made a mistake. In the same app, there are other views (i.e. model based on mysql views) which work fine. -
I accidentally closed my cmd and i cant re run my Django server again
when I open my cmd again it doesnt run my server and shows this error C:\Users\16478\my_tennis_club>py manage.py runserver Unable to create process using 'C:\Users\16478\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver' I even tried activating my env again but it didn't work out -
Error Failed building wheel for pillow while installing on Windows
I'm trying to install Pillow on python 3.10 using command pip install Pillow and it occurs ERROR: Failed building wheel for Pillow below: (venv) PS C:\Users\Mohamad\PycharmProjects\faracode_project> pip install Pillow Collecting Pillow Using cached Pillow-10.0.1.tar.gz (50.5 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: Pillow Building wheel for Pillow (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for Pillow (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [198 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.mingw_x86_64-cpython-310 creating build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BdfFontFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ContainerIO.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\CurImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\ExifTags.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\features.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FliImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FontFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GdImageFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GifImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GimpGradientFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.mingw_x86_64-cpython-310\PIL copying … -
Check decorator is attached to a view function
@permission_required() def my_home(request): import functools from walterwhite.views import my_nav # Replace with your view function if hasattr(my_nav, 'wrapped') and isinstance(my_nav.wrapped, functools.partial): print(f'{my_nav.name} has the @permission_required decorator') else: print(f'{my_nav.name} does not have the @permission_required decorator') return HttpResponse('In home') @permission_required() def my_nav(request): Res='Hello this is the navigation bar' return render(request,'index.html') Here it giving me the response as my_nav does not have @perm decorator even though it has decorator attached. How to check whether permission_required is attached or not -
Is there away of Reloading(Refreshing)Django Server automatically without using Ctrl +s or even Ctlrl +c and then runing it again
your text** """ I have Managed to build a web hosting platform using django i intend to make the platform free webhosting platform but the problem i have is that my django server needs to reload from time to time .i have tried the following options bellow. import time import schedule import keyboard from threading import * from datetime import datetime import django from django.utils import autoreload class ExitCommand(Exception): pass def load(): try: django.setup() keyboard.press_and_release("Ctrl+c") autoreload.autoreload_started autoreload.DJANGO_AUTORELOAD_ENV autoreload.file_changed run=autoreload.StatReloader() run.should_stop=False run.run_loop() print("Server changes detected") now=autoreload.get_reloader() now.notify_file_changed(os.path.join(BASE_DIR)) raise ExitCommand() except ExitCommand: keyboard.press_and_release("Ctrl+s") # autoreload.autoreload_started # autoreload.get_reloader() # autoreload.DJANGO_AUTORELOAD_ENV # autoreload.raise_last_exception() # autoreload.iter_all_python_module_files() # autoreload.restart_with_reloader() os.system("python manage.py runserver 8080") print("++Reloading Server+++") def relaod_server(): load_time="22:59:00" now=datetime.now() current_time=now.strftime("%H:%M:%S") start_time=datetime.strptime(load_time,"%H:%M:%S") stop_time=datetime.strptime(current_time,"%H:%M:%S") time_diffrence=start_time-stop_time os.environ["RELOAD_HOURS_REMAINING"]=str(time_diffrence) schedule.every().day.at("23:47").do(load) while True: schedule.run_pending() time.sleep(1) refresh=Thread(target=relaod_server,args=[]) refresh.setDaemon(True) refresh.start() `your text` What am trying to do is to make django server reload automatically after some time kindly help,i am working on my company start up.i am working on a webhosting paltform which i have finished writing the only challange i have is that my django server needs to reload and i dont know how to do that. -
More than one Django website on IIS server - it is possible?
I'm trying to run a Django website on an IIS server. After several tries, I finally succeeded. It works quite nicely. Now it's time for the next stage with which I have a bit of a problem. My question is: Is it possible to run more than one Django service on an IIS server? If I look at the web.config file, there are references to only one Django website. <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\inetpub\wwwroot\test_3\venv\Scripts\python.exe|C:\inetpub\wwwroot\test_3\venv\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\test_3" /> <add key="WSGI_HANDLER" value="mysite.wsgi.application" /> <add key="DJANGO_SETTINGS_MODULE" value="mysite.settings" /> </appSettings> </configuration> Especially when each website will be in a separate venv. Thanks for any help and suggestion -
How to prevent increase a field in Django
i have a model in django called products. that have a field called star that store my score of products (from 0 to 5) and i want to not allow to increase more that 5 (or even be negative number). star = models.IntegerField(default=0, max_length=5) <div class="d-flex justify-content-center small text-warning mb-2"> {% with ''|center:item.star as range %} {% for _ in range %} <div class="bi-star-fill"></div> {% endfor %} {% endwith %} </div> what can i do? for example if one of my products have star field with 7 it show 7 star in product page! -
Elasticsearch query not working with custom field
I have two models: class Teacher(models.Model): name = models.CharField(max_length=50) class TeacherSalary(models.Model) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) salary = models.IntegerField() year = models.IntegerField() I created two corresponding documents: @registry.register_document class TeacherDocument(Document): class Index: name = 'teachers' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = Keyword fields = [ 'id', 'name' ] @registry.register_document class TeacherSalaryDocument(Document): name = fields.KeywordField() class Index: name = 'teacher_salary' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = TeacherSalary def prepare_name(self, instance): return instance.teacher.name When I search for some teachers by name, for example: documents = TeacherDocument.search().query('match', name="John") I have all teachers with name contains "John" for example John Thomson, Thomas John... However, when I do the same search with the TeacherSalaryDocument, I got nothing, i have to search the exact name. For example: documents = TeacherSalaryDocument.search().query('match', name="John") returns [], but documents = TeacherSalaryDocument.search().query('match', name="John Thomson") returns all salary histories of the "John Thomson" teacher. How could I get the salary of all teachers that their names contain "John"? Thank you! -
Django websockets connection failed
I have hosted a django application on Linode which includes a chatting functionality. I am using django-channels to implement that functionality. I am not using any particular technology like Redis, just the inbuilt django thing to implement the websockets because I am just testing the site for now. The following is the chatroom.html file: {% extends 'common_anime_chat/base.html' %} {% load static %} {% block stylesheet %} <link rel="stylesheet" type="text/css" href="{% static 'chatroom.css' %}"> {% endblock stylesheet %} {% block content %} <div class="chat-container"> <div id="chat-messages" style='height: 75vh;'></div> <div id="input-container"> <textarea id="input" rows="1"></textarea> <input type="button" id="submit" value="Send"> </div> </div> {{ request.user.username|json_script:"user_username" }} {{ request.user.profile.profile_picture.url|json_script:"user_pfp"}} <script> const hardcodedProfilePictures = { 'itsmyname': '/media/profile_pictures/profile1.png', 'user123': '/media/profile_picturues/profile2.png', // Add more hardcoded profile pictures here for other usernames }; document.querySelector('#submit').onclick = function (e) { const messageInputDOM = document.querySelector('#input'); const message = messageInputDOM.value; chatSocket.send(JSON.stringify({ 'message': message, 'username': userUsername, 'user_pfp':userPfp, 'room_name':roomName })); messageInputDOM.value = ''; }; const chatMessagesDOM = document.querySelector('#chat-messages'); const userUsername = JSON.parse(document.getElementById('user_username').textContent); // console.log(userUsername) const pathArray = window.location.pathname.split('/'); const roomName = pathArray[pathArray.length - 2]; // Use -1 if the room name is in the last segment let userPfp = JSON.parse(document.getElementById('user_pfp').textContent); // Object to store profile pictures associated with usernames let profilePictures = {}; const chatSocket = … -
How to save settings for each user on the site?
I have a site based on django. And it shows some graphs. Graphs have several settings. I need each user to be able to change these settings for themselves. How is this possible? And another question, is it possible for these parameters to be saved the next time for each user? -
The same code in django cannot run properly
enter image description here 上面注释的部分无法让程序运行会报错AttributeError: 'WSGIRequest' object has no attribute 'get' 而下面可以运行。是编译器的问题的,python版本是 3.8.3 ,django 版本是 4.2,pycharm是2022.3.3 (Professional Edition) 重新编写一样的代码可以运行,但是唯独第一次的那个代码无法运行。 -
Seeking General Django Deployment Advice
This is isn’t a conventional stack overflow question but was seeking help and wanted to ask a good community. I’m trying to deploy my Django app and was wondering what’s a good hosting service to do so. It’s not a large application and doesn’t even use a database at the moment (it will later). So free would be ideal. I’ve tried to follow some tutorials but it never works and I don’t know enough about deployment to debug and fix it effectively. If someone could dm me with Django deploying experience that’d be so good! My name is d.sons#3851 If not any help or advice on here would be greatly appreciated. -
celery nested task (tasks inside tasks)
I wrote 2 update_all_rss task but don't know which one is better. can someone explain it which one should I use? Info: each task is independent and doesn't need other task result. It would be greatly appreciated if you could provide me any suggestion to optimize overall performance of these tasks @shared_task(base=BaseTaskWithRetry, task_time_limit=600) def update_all_rss(): for xml_link_obj in XmlLink.objects.all().iterator(): update_single_rss.delay(xml_link_obj) vs @shared_task(base=BaseTaskWithRetry, task_time_limit=600) def update_all_rss(): xml_links = list(XmlLink.objects.all().iterator()) tasks = (update_single_rss.s(xml_link_obj) for xml_link_obj in xml_links) result_group = group(tasks) result_group() if it helps this is update_single_rss task: @shared_task(base=BaseTaskWithRetry, task_time_limit=120) def update_single_rss(xml_link_obj): channel_qs = Channel.objects.select_related('xml_link').prefetch_related("xml_link__rss_type").filter( xml_link=xml_link_obj) if channel_qs.exists(): channel = channel_qs.get() channel_parser = channel_parser_mapper(xml_link_obj.channel_parser) channel_info = channel_parser(xml_link_obj.xml_link) if channel.last_update != channel_info.get("last_update"): channel.last_update = channel_info.get("last_update") items_parser = items_parser_mapper(xml_link_obj.items_parser) items_info = items_parser(xml_link_obj.xml_link) ItemClass = item_model_mapper(xml_link_obj.rss_type.name) try: with transaction.atomic(): channel.save() items = ( ItemClass(**item, channel=channel) for item in items_info if not ItemClass.objects.filter(guid=item.get("guid")).exists() ) ItemClass.objects.bulk_create(items) except IntegrityError as e: return {"Message": str(e)} return {"Message": f"Channel {channel.title} was Updated"} return {"Message": f"Channel {channel.title} is Already Updated"} return {"Message": f"No channel for {xml_link_obj.xml_link} Exist"}