Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wait until subtask is ready (celery + unittest)
I have a task which called by parent task. @shared_task def task1(): if condition: task2.apply_async() @shared_task def task2(): pass I want to test all flow starting by calling task1 with unittest: class NewTestCase(TestCase): def test_tasks(self): celery_task = task1.apply() celery_task.get() self.assertEqual(celery_task.state, "SUCCESS") But in that case subtask task2 goes into my local celery worker and executes there. Is there any way to execute all task in test enviroment and wait until subtask is ready? P.S. CELERY_ALWAYS_EAGER=True isn't a solution. -
Django and two telegram bots
I want to make 2 telegram bots with a common admin panel in Django. The question is how best to implement this. The first bot will be for sellers, let's call it “seller bot”. The second one will be for "buyer bot" buyers. I already have sketches for the first bot, a model in Django telegram_bot. There should also be a chat so that you can communicate from the first to the second bot. How can I best create a database to store users from two bots? make one table and separate the data there by chat_id? Then how can I determine which bot I am a member of? I was thinking of creating two separate applications telegram_bot_seller and telegram_bot_buyer. Please tell me which approach would be better. I've never worked with two bolts at the same time .. Each bot will have its own separate functions. But some, such as the technical support chat, are common (just don’t interfere with each other) -
Post request do Django app deployed with Gunicorn and Nginx retuns 405 code
I am sorry that my question is not quite suitable for Stack overflow community, but I am desperate to find the solution to my issue and hope that somebody will be able to please help me. My Django application is deployed on AWS. EC2 UBUNTU. I used Nginx and Gunicorn. Socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/home-admin ExecStart=/home/ubuntu/home-admin/.venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ home_admin.wsgi:application [Install] WantedBy=multi-user.target Nginx server conf: server { listen 80; server_name XX.170.235.232; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://unix:/run/gunicorn.sock; } } This configuration serves Get requests perfectly, but when I send POST request I receive 405 code. Besides, I see that on some stage the url is augmented by unnesessary domain. This is response error: POST http://127.0.0.1:5500/XX.170.235.232/ 405 (Method Not Allowed). -
Using Django Allauth without allauth urls?
I want to use django allauth package without its built in urlpatterns. Main reason for that is that I want to have the ulrs in different language. Also I dont want to have the allauth url available even if there is no redirectons to those pages in my site. Main reason I started to use allauth was the social login but I noticed that the regural account logic was nice and fast to implement. Is it neccesary to include allauth url to project if you want to use only the views and forms functionality? Or is there a better way to do it? I have made custom views and forms all of the views and forms that I use but they all inherit allauth views and forms. I have also custom ulrs to all those views. Example of my custom view: class LogInView(AllAuthLoginView): template_name = 'accounts/log_in.html' form_class = SignInForm I have tested that it works well when allaut urls are included. But if exlude allauth url I get this error when loading login page: Reverse for 'account_signup' not found. 'account_signup' is not a valid view function or pattern name. I noticed that it comes from this function in allauth LoginView … -
allauth providers not present in user details
I am trying to setup SSO in my django project using Allauth which I have previously done, but for some reason my defined provider is not present in the user section to link the user to an external provider. This is the config: ACCOUNT_ADAPTER = "myproject.users.adapters.AccountAdapter" ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True) ACCOUNT_AUTHENTICATION_METHOD = "username_email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_USERNAME_REQUIRED = False # Username is not required ACCOUNT_UNIQUE_EMAIL = True SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_EMAIL_AUTHENTICATION = True SOCIALACCOUNT_EMAIL_AUTHENTICATION_AUTO_CONNECT = True SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' # None because we trust azure SOCIALACCOUNT_LOGIN_ON_GET = True SOCIALACCOUNT_ADAPTER = "myproject.users.adapters.SocialAccountAdapter" OIDC_CLIENT_ID = env("DJANGO_SOCIALACCOUNT_OIDC_CLIENT_ID", default="") OIDC_CLIENT_SECRET = env("DJANGO_SOCIALACCOUNT_OIDC_CLIENT_SECRET", default="") OIDC_CLIENT_URL = env("DJANGO_SOCIALACCOUNT_OIDC_CLIENT_URL", default="") SOCIALACCOUNT_PROVIDERS = { "openid_connect": { "APPS": [ { "provider_id": "keycloak", "name": "Keycloak SSO", "client_id": OIDC_CLIENT_ID, "secret": OIDC_CLIENT_SECRET, "settings": { "server_url": OIDC_CLIENT_URL, }, } ] } } MIDDLEWARE += ["allauth.account.middleware.AccountMiddleware"] And the errorlog -
Design Strategies for Integrating Enroll Plan-Specific Features in a Django Project
I am working on a Django project that comprises three main components: nkb_assessment_backend: Handles assessments and exams, featuring apps like nkb_exam and nkb_exam_extensions. nkb_learning_backend: Manages learning-related functionalities including user enroll plans, with apps such as nkb_auth_v2. nkb_backend: Serves as an overarching layer that possibly integrates or orchestrates functionalities of the above two components. Requirement: We need to introduce functionality for enroll plan-specific exam slots in the nkb_assessment_backend, where these slots are dependent on user enroll plans managed in the nkb_learning_backend. The challenge is to implement this feature without creating direct dependencies or coupling between the two backend components. Constraints: Avoid modifications to the nkb_assessment_backend, particularly its database schema or existing models. Maintain a loosely coupled architecture. Ensure the solution is scalable and maintainable. Question: What are the best practices or strategies to implement this feature within the given constraints and architecture? I am looking for insights or alternative approaches that could efficiently integrate this functionality while maintaining the structural integrity of our Django project. -
Bad format after converting a JSONField to a TextField
I encountered an issue with a Django project where a JSONField was initially used to store data. To maintain the order of the data as it was saved, I implemented a sorting functionality. However, I found that this sorting operation, although necessary for display, seemed inefficient when the data was accessed. To address this, I decided to convert the JSONField to a TextField and use json.dump to ensure the order is preserved without the need for sorting each time the data is accessed. Unfortunately, the conversion process didn't work as expected. Django successfully converted some fields to the correct JSON string format, but others were not handled correctly. An example of the incorrect format is as follows: '{'is_valid': True, 'name': 'John Doe'}' As seen above, Django converted the data to a string, but boolean values, such as True, were not handled correctly. I am seeking suggestions on how to address this issue. Currently, I am considering replacing the single quotes with double quotes and converting boolean values like this: data = '{'is_valid': True, 'name': 'John Doe'}' formatted_data = data.replace("'", '"').replace('True', '"true"') However, I believe there might be a more elegant or efficient solution. I would appreciate any insights or recommendations. … -
Django SMTPServerDisconnected: Connection unexpectedly closed
I have everything set up, gmail using app password EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'emailtam1231@gmail.com' EMAIL_HOST_PASSWORD = "appp pass word some" EMAIL_USE_SSL = False EMAIL_DEBUG = True Here is my send email func: def send_price_drop_notification(product, latest_item): favorite_users = Favourite.objects.filter(product=product) if favorite_users: subject = f'Price Drop Alert for {product.name}' message = f'The price for {product.name} has dropped to {latest_item.current_price}.\nCheck it out now!' from_email = 'emailtam1231@gmail.com' recipient_list = [favorite.user.email for favorite in favorite_users] print(f"Subject: {subject}") print(f"Message: {message}") print(f"From: {from_email}") print(f"To: {recipient_list}") try: send_mail(subject, message, from_email, recipient_list, fail_silently=False,) except smtplib.SMTPServerDisconnected as e: print(f"SMTPServerDisconnected: {e}") # Handle this specific exception (e.g., reconnect to the SMTP server, or log the issue) except smtplib.SMTPException as e: print(f"SMTPException: {e}") # Handle SMTP exceptions in a specific way except BadHeaderError as e: print(f"BadHeaderError: {e}") # Handle BadHeaderError or other exceptions except Exception as e: print(f"Exception occurred while sending email: {e}") The output i getting: Subject: Price Drop Alert for Fake Product Message: The price for Fake Product has dropped to 120.53. Check it out now! From: emailtam1231@gmail.com To: ['ntd8466@gmail.com'] And when i check, the app password was never been use. -
Redshift serverless - Django connection active all the time
I have Django application running which connects to postgres for basic django functionality/setup. But this application also connects to Redshift serverless using psycopg2 library. The problem is that the RS serverless is always up and running which is costing a lot. Digging into the issue, I found that psycopg2 is executing below query every 5-6 seconds: "SET datestyle TO 'ISO'" Looking at the psycopg library file, every time the connection is setup, a function is called conn_is_datestyle_ok. For reference: https://github.com/psycopg/psycopg2/blob/5fb59cd6eebd96e2c8a69a3a9d606534eb95abf0/psycopg/connection_int.c#L678 Is there a way we can set the parameter or any option for library not to execute this query? -
Unable to update the data in python
I'm unable to update the organisation details in the singleuser file a python project using the framework django. the value is not updating in the database. enter code here {% extends "caas_apps/layouts/base.html" %} {% load static %} {% block content %} {% include 'caas_apps/layouts/sidebar.html' %} {% include 'caas_apps/layouts/header.html' %} Organization Details {% csrf_token %} {{ org_form.as_p }} {{ formset.management_form }} {% for form in formset.forms %} {{ form.as_table }} {% endfor %} Organization Name: {{ organization.orgname }} License Type: {{ organization.license }} Certification Settings: {{ organization.certification }} Security Framework: {{ organization.framework }} Contact Person Name: {{ organization.cpname }} Email: {{ organization.orgemail }} Phone: {{ organization.phone }} Address: {{ organization.address }} Third Party Contact Details: {% for contact in third_party_contacts %} Name: {{ contact.thirdpartyname }} Email: {{ contact.thirdpartyemail }} Phone: {{ contact.thirdpartyphone }} {% endfor %} Submit Reset {% endblock content %} {% block scripts %} $(document).on("click", "label.orgdetails", function () { var $label = $(this); var txt = $label.text(); var fieldName = $label.attr('id'); $label.replaceWith(<input class='orgdetails' type='text' name="${fieldName}" value='${txt}'>); $(input[name="${fieldName}"]).focus(); }); $(document).on("blur", "input.orgdetails", function () { var $input = $(this); var txt = $input.val(); var fieldName = $input.attr('name'); $input.replaceWith(<label class='orgdetails' id="${fieldName}">${txt}</label>); $(input[name="${fieldName}"]).val(txt); }); $("#reset-btn").on("click", function () { $("#org-details-form")[0].reset(); $("label.orgdetails").each(function () { var … -
What difference between AdminSiteOTPRequired and OTPAdminSite?
What difference between AdminSiteOTPRequired and OTPAdminSite? couldn't understand at first glance almost identical I use authorization by email, I changed the class in the code to another one, but I didn’t see the difference in the documentation. The only thing I deducted was that one class is specifically for administering admin users, but the second one too? from two_factor.urls import urlpatterns as tf_urls from two_factor.admin import AdminSiteOTPRequired from django_otp.admin import OTPAdminSite admin.site.__class__ = AdminSiteOTPRequired urlpatterns = [ path('', include(tf_urls)), ] -
Django - While registering, registered data are not saved on database and so can't perform LogIn
I have been trying so hard to make an user registration and login using Django. I am using AbstractUser for this. Whenever, I enter the form fields, and click Signup the page is not getting redirected and the entered data aren't saved on the database This is my view.py def register(request): if request.method == "POST": print("method is post") form = UserRegisterForm(request.POST or None) if form.is_valid(): print("form is valid") form.save() username = form.cleaned_data.get("username") messages.success(request, f"hey {username}, account created successfully") new_user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password1']) login(request, new_user) return redirect("jew_app:home") else: print(form.errors) else: print("user can't be registered") form = UserRegisterForm() context = { 'form': form } return render(request, 'user/register.html', context) def user_login(request): if request.user.is_authenticated: messages.warning(request, f"Hey you are already logged in") return redirect("accounts:profile") if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") try: user = User.objects.get(email=email) user = authenticate(request, email=email, password=password) if user is not None: login(request, user) messages.success(request, "You are logged in") return redirect("jew_app:home") else: messages.warning(request, "User Does Not Exist. Create an account") except: messages.warning(request, f"User with {email} does not exist") context = { } return render(request, 'user/login.html', context) models.py class User(AbstractUser): email = models.EmailField(unique=True, null=False) username = models.CharField(max_length=100) dob = models.DateField(null=True, blank=True) mobile_number = models.CharField(max_length=10, null=True, blank=True) USERNAME_FIELD = "email" REQUIRED_FIELDS … -
Reportlab Muiltidoc pass args to canvasmaker
I am trying to pass custom values via my canvasmaker. But i can't create an instance of Canvas or pass values to it. This is my canvas Class. class PracticeBookCanvas(canvas.Canvas): #---------------------------------------------------------------------- def __init__(self, *args, **kwargs): """Constructor""" # canvas.Canvas.__init__(self, *args, **kwargs) canvas.Canvas.__init__(self, *args, **kwargs) self.pages = [] # def __init__(self, filename, subject_name, branch_name, *args, **kwargs): # canvas.Canvas.__init__(self, filename, *args, **kwargs) # self.pages = [] # self.subject_name = subject_name # self.branch_name = branch_name #---------------------------------------------------------------------- def showPage(self): """ On a page break, add information to the list """ self.pages.append(dict(self.__dict__)) self._startPage() #---------------------------------------------------------------------- def save(self): """ Add the page number to each page (page x of y) """ page_count = len(self.pages) for page in self.pages: self.__dict__.update(page) self.draw_page_number(page_count) self.draw_page_header() canvas.Canvas.showPage(self) canvas.Canvas.save(self) #---------------------------------------------------------------------- def draw_page_number(self, page_count): """ Add the page number """ page = "Page %s" % (self._pageNumber) self.setFont("Noto-Sans", 9) # self.drawRightString(195*mm, 272*mm, page) self.drawCentredString(195*mm, 0.4 * inch, page) def draw_page_header(self): self.setFont('Raleway', 14) self.drawString(self._pagesize[0] / 2, letter[1] - 0.5 * inch, "Practice Workbook") # self.drawString(self._pagesize[0] / 2, letter[1] - 0.5 * inch, f"{self.subject} / {self.branch}") This is my function which generates doc. def genPracticeWorkbook(user, branch, level): logger.info(f"Generating Practice Workbook {user}") BASE_DIR = Path(__file__).resolve().parent.parent usr = User.objects.get(id=user) # user_downloads = UserDownloads.objects.all() user_downloads = UserDownloads( user=usr, status="in_progress", file_name=f"Practice Workbook_{level}" … -
Dynamic custom fields in the Django Admin panel?
I have a number of Custom Fields in the Django Admin panel in which I'd like to be able to add values into and I'm wondering if that's possible to implement. Currently, I have one Custom Field in use that on the frontend shows "Masses: " and next to it I have a field but it's free text. The other Custom Fields are NULL and do not show on the frontend side. Below is a snippet of the loop which iterates through the items: {% for field in form %} {% for key, value in custom_fields_used.items %} {% if key == field.name %} <div class="row"> <div class="col-sm-2 text-right"> {{ value }} </div> <div class="col-sm-4"> {{ field }} </div> <div class="col-sm-2 text-right"> </div> <div class="col-sm-4"> </div> </div> {% endif %} {% endfor %} {% endfor %} Below I have also a JSON snippet from that specific table in which the values reside, the Custom Fields are part of the JSON template: "tenant": { "custom_field_1": "Masses:", # this field "custom_field_2": null, "custom_field_3": null, "custom_field_4": null, "custom_field_5": null, "custom_field_6": null, "custom_field_7": null, "custom_field_8": null, } I managed to implement a Multiselect in the Admin Panel...However the fields are empty and those fields I … -
Implementing django_multitenant in django 4.2
I'm working on a new django 4.2 project. To implement multi-tenancy, I'm using the django_multitenant library with Citus 12.1 and PostgreSQL 16. While defining the models I see that there is ambiguity in the recommended steps. There are multiple guides but with different suggestions. https://www.citusdata.com/blog/2023/05/09/evolving-django-multitenant-to-build-scalable-saas-apps-on-postgres-and-citus/ https://github.com/citusdata/django-multitenant#readme There is no clear explanation on how migrations are addressed. The former asks to write a custom migration file while the latter skipped that step. What is the recommended way and model structure if one is implementing django_multitenant in a new django 4.2 project using citus 12.1 and postgresql 16 using the default row-based sharding option? -
display django ckeditor uploaded images in vuejs frontend
I want to make a blog with django rest backend and vuejs frontend and I want to use ckeditor When I upload images in the RichTextUploadingField, the images are stored in '/media/ck/' address and as you know i can't display images with this address in vuejs frontend i need absolute url of images...i need this address -> http://127.0.0.1:8000/media/ck/ how can i display django ckeditor uploaded images in vuejs frontend actually how can i send the uploaded images in the django ckeditor with absolute url to vuejs settings: STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' CKEDITOR_UPLOAD_PATH = 'ck/' model: class Post(models.Model): name = models.CharField(max_length=200,) information = RichTextUploadingField() serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('name','information') views: def get_all_posts(request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True, context={'request':request}) return JsonResponse(serializer.data,safe=False) -
Prefetch objects of Proxy model Django ORM
I have 2 models in my Django 3.2. class Order: ... daily_order = models.ForeignKey( DailyOrder, null=True, blank=True, on_delete=models.SET_NULL, related_name='orders', ) class DailyOrder: class Meta: proxy = True ordering = ('id', ) default_related_name = 'daily_orders' verbose_name = 'Daily order' verbose_name_plural = 'Daily orders' My question is when i try to get info from related manager and iterate through it it's increase db queries. In Order model I have method: def available(self): orders_time = [order.time for order in self.orders.all().prefetch_related('daily_order')] #But this prefetch isn't work I want to decrease my DB queries, any ideas ? -
Is there a BPMN painter compatible with viewflow?
I want to integrate D with my existing Django application and want a graphical BPMN painter that my users can use to build workflows for viewflow. Someone recommended "flow designer", but that appears to be dedicated to service now. Another person recommended CWL,but I could find no supporting information. The viewflow demo lists 'material' but that too doesn't quite fit. So if someone knows a BPMN painter that is compatible with viewflow -
why next table repeated when first table take full page?
I am using weasyprint lib for make html to pdf. I have two table - product and summary. when product table take full page in pdf then summary table after page break repeated. it seems css issue. I tried page-break-insert, before, after. Its not working for me. see image for ref. 1. product table, page break, 2. summary table -
Django Email Already Exists
So i have tried to create Custome Users for my project Provider and Seeker, also i have create a register view, however, whenever i want to add a user (provider) it tells me that the email already exists, despite there is no users in the database yet I have tried to remove the UniqueValidator from the ProviderSerializer and implement the logic of finding duplicate emails in the view I have tried to save the user to the database then check if there is a email duplicate from django.shortcuts import render from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes, authentication_classes from rest_framework.permissions import AllowAny, IsAdminUser from .models import Provider, Seeker from .serializer import ProviderSerializer from django.contrib.auth.models import Group from rest_framework import serializers @api_view(['POST']) @permission_classes([AllowAny]) def Register(request): if request.data.get('work_email'): seri = ProviderSerializer(data=request.data) if seri.is_valid(): try: user = seri.save() try: group = Group.objects.get(name='Provider') user.groups.add(group) except Group.DoesNotExist: return Response({"Message": "Exception at group assigning"}) except serializers.ValidationError as e: return Response(e.errors, status=status.HTTP_400_BAD_REQUEST) return Response({"Message": "User created successfully"}) else: return Response(seri.errors, status=status.HTTP_400_BAD_REQUEST) else: return Response({"Message": "No Work_email"}, status=status.HTTP_400_BAD_REQUEST) from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class GenericUser(AbstractUser): username = models.CharField(max_length=150, blank=True,null = True) email = models.EmailField(max_length=255,unique=True,db_index=True) … -
Online Quiz System Design [closed]
I looking for system design architecture for online quiz system using python, django and any SQL or nosql db, frontend framework. All possible type of questions and inputs from user should save in db. Full system design for online quiz system. -
Getting KeyError: 'id' when importing a CSV file using django-import-export
I am tring to update sqlite data by importing a csv file to django admin, only to get the error message for each single record I upload: Line number: 1 - 'id' Traceback (most recent call last): ... import_id_fields = [self.fields[f] for f in self.get_import_id_fields()] KeyError: 'id' Here is my models.py, which indicates a primary key: class HCPMaster(models.Model): external_id = models.CharField(max_length=200, primary_key=True) bi_external_id = models.CharField(max_length=200) name = models.CharField(max_length=200) ... The resources.py, which has the import_id_fields: class HCPMasterResource(resources.ModelResource): class Meta: model = HCPMaster import_id_fields = ['external_id'] The admin.py: class HCPMasterAdmin(ImportExportModelAdmin): resources_class = HCPMasterResource admin.site.register(HCPMaster, HCPMasterAdmin) The uploaded csv file (The columns match the HCPMaster model exactly): external_id,bi_external_id,name,primary_parent_name,parent_external_id,parent_parent_external_id,personal_title,administrative_title,license,network_external_id,status,verified_time,updated_time CNC1562173,CN1183335,John,Hospital A,Hospital A,CNHABCD,Doctor,Agent,,9.36678E+17,Active,44851,45231 CNC1531568,CN1183339,Mary,Hospital B,Hospital B,CNHABCE,Doctor,Agent,,9.37537E+17,Active,44799,45231 I have tried every possible solution on stackoverflow and github like: Specify import_id_fields to the actual primary key 'external_id'. Specify exclude = ['id'] in Meta Class of ModelResource. Specify fields in Meta Class of ModelResource: List all the fields in CSV file. Manually Create a id columns in the csv file with blank value. Sadly, none of them works. pip list: Django 4.2.7 django-import-export 3.3.3 -
CSRF token missing when making a POST request via Hoppscotch to Django
I'm working with a Django (version 4.0+) application and facing a CSRF verification issue when trying to make a POST request using Hoppscotch. I'm receiving the following error: { "detail": "CSRF Failed: CSRF token missing." } Here's the JSON body of my POST request: { "title": "Fiestaaaaaaaaaaaaaaaaaaaaaaaa", "description": "Para celebrar", "date": "2023-11-28T01:16:10Z", "location": "En mi casa" } I understand that I need to include a CSRF token in my request headers, but I'm not sure how to obtain this token when using Hoppscotch. I've made a GET request to my server expecting to see a csrftoken cookie that I can use for subsequent POST requests, but I couldn't find it in the response headers. Here are the response headers I received: allow: GET, POST, HEAD, OPTIONS content-length: 141 content-type: application/json ... (other headers) No Set-Cookie header appears with the CSRF token. Is there a specific way to configure Hoppscotch or Django to make this work? I'm lost on how to proceed with CSRF tokens in this environment. Any advice or guidance would be greatly appreciated. Thank you in advance. -
Not getting the right fields in Django
I am trying to create a subscription feature in my Django site where a user enters his name and email and clicks the 'Subscribe' button. I have written this code in the subscribe.html form but it keeps showing the main post form which is used to write the blog post. Can anyone help me fix this? Here are the relevant codes. forms.py Subscribe form (Please note that when I type http://127.0.0.1:8000/subscribe/, I see the 'Title' and 'Body' of the post form but not the Name and Email of the subscribe form.) class SubscribeForm(forms.Form): class Meta: model = Subscribe fields = ('Name', 'Email') widgets = { 'Name': forms.TextInput(attrs={'class': 'textinputclass'}), 'Email': forms.EmailField(widget=forms.TextInput(attrs={'class': 'emailinputclass'})) } class PostForm(forms.ModelForm): class Meta: model = Post # fields = ('author','title', 'body',) fields = ('title', 'body') widgets = { 'title': forms.TextInput(attrs={'class': 'textinputclass'}), 'body': forms.Textarea(attrs={'class': 'editable medium-editor-textarea postcontent'}), } views.py class SubscribeView(generic.CreateView): model = Subscribe form_class = PostForm template_name = 'blog/subscribe.html' success_url = reverse_lazy('subscribe') Templates Subscribe.html {% extends 'blog/base.html' %} {% block content %} <h1>Join my List</h1> <form method="POST" class="subscribe-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="save btn btn-default">Subscribe</button> </form> <script>var editor = new MediumEditor('.editable');</script> {% endblock %} Postnew.html {% extends 'blog/base.html' %} {% block content %} <h1>New post</h1> … -
How to set priorities for RQ queues under different supervisor programs
I'm using supervisor to run rqworker. I want to assign different number of workers for different queues, so I put each queue under a different program. How do I set priorities for these queues in this case? I know if I run workers for all the queues under single program, the order I specify queues in rqworker command is the priority of these queues. (https://python-rq.org/docs/workers/#strategies-for-dequeuing-jobs-from-queues) However, for my case, each queue is under a different program, wondering how I can set the priority. Should I start rqworker with nice command? Some config example would be nice. Thx!