Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keep getting "FOREIGN KEY constraint failed" in Django
I am new to django and i am making a multivendor ecommerce website for my final year project. for the past three hours i keep having the foreingnkey constraints error when i want to add products. please i need smeone to help me and solve the problem. views.py def AddProduct(request): """this page will be used for adding products""" if request.method =='POST': form=ProductForm(request.POST) if form.is_valid(): model=User user=form.save() return HttpResponseRedirect('/becomeaseller/DashBoard') else: form=ProductForm() context={'form':form} return render(request, 'app/addproduct.html',context) return HttpResponse("enter the details and description of your products") models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_customer = models.BooleanField(default=False) is_seller = models.BooleanField(default=False) class Category(models.Model): category_name=models.CharField(max_length=100) def __str__(self): return self.category_name class Product_Details(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) product_name=models.CharField(max_length=100) category=models.ForeignKey(Category, on_delete=models.CASCADE) product_image=models.ImageField(null=True) product_description=models.CharField(max_length=100) product_price=models.IntegerField() product_quantity=models.IntegerField(default=1) shop_name=models.CharField(max_length=100) shop_location=models.CharField(max_length=100) shop_description=models.CharField(max_length=100) def __str__(self): return self.product_name -
icons are not visible for django, how to fix that?
I am trying to convert a bootstrap template to django project. I places all the css and other files to static and replaced with static tags. But, fontawesome icons are not showing. But with django: The html code: <div class="social-icons"> <a class="social-icon" href="#"><i class="fab fa-linkedin-in"></i></a> <a class="social-icon" href="#"><i class="fab fa-github"></i></a> <a class="social-icon" href="#"><i class="fab fa-twitter"></i></a> <a class="social-icon" href="#"><i class="fab fa-facebook-f"></i></a> </div> -
Django Admin - Disable the 'Add' action for a specific model Ask
hello there i want to add images in form from my admin panel with django when I created my class I do: photo = models.ImageField(null=True, blank=True, upload_to='images/') but I have an error: no such column: blog_post.company Request Method: GET error: 500 151197 -
WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/hi%20hi/' failed: WebSocket is closed before the connection is established
I am making a chat application in Django. I am following a YouTube tutorial and for most part the application is working fine, but there is some problem with my routings. When the name of the room is a single word like "room1", the Websocket is connected and I can send and receive messages. But when name of room is made or two or more words like "habiba room", the connection is not establishing. in console I get this error WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/habiba%20room/' failed: WebSocket is closed before the connection is established. and on server I get this error WebSocket DISCONNECT /ws/chat/habiba%20room/ [127.0.0.1:62063] [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'ws/chat/habiba room/'. E:\New folder\env\lib\site-packages\autobahn\websocket\protocol.py:2839:processHandshake E:\New folder\env\lib\site-packages\txaio\tx.py:366:as_future E:\New folder\env\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred E:\New folder\env\lib\site-packages\daphne\ws_protocol.py:72:onConnect --- <exception caught here> --- E:\New folder\env\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred E:\New folder\env\lib\site-packages\daphne\server.py:200:create_application E:\New folder\env\lib\site-packages\channels\staticfiles.py:41:__call__ E:\New folder\env\lib\site-packages\channels\routing.py:54:__call__ E:\New folder\env\lib\site-packages\channels\sessions.py:47:__call__ E:\New folder\env\lib\site-packages\channels\sessions.py:145:__call__ E:\New folder\env\lib\site-packages\channels\sessions.py:169:__init__ E:\New folder\env\lib\site-packages\channels\middleware.py:31:__call__ E:\New folder\env\lib\site-packages\channels\routing.py:150:__call__ ] in project/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) in chat/routing.py # chat/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer), ] in my index.js var … -
I only want the data of the table row whose checkbox is checked. my table row is in for loop how can i9 access them by jinja
I only want the data of the table row whose checkbox is checked. my table row is in for loop how can i9 access them by jinja. i tried with ajax but i am not able to redirect page with data please help me. this is my search.html : <form name="form" method="POST" id="form"> {% csrf_token %} <table class="table table-bordered table-responsive" id="flip-scroll"> <thead> <tr> <th scope="col">Visa Option</th> <th scope="col">Processing Type</th> <th height="60" scope="col">Travel Date</th> <th scope="col">Price</th> </tr> </thead> <tbody> {% for j in package %} <tr class="valid-container" data-id="{{ j.id }}"> <td style="cursor:pointer;" width="200"><input type="checkbox" name="c1" class="checkbox">&nbsp; <output class="visa_type" style="font-size:14.5px !important;">{{ j.visa_type }}</output></td> <td height="52" width="158"> <select class="custom-select processing_type" name="processing_type" required> <option value="{{ j.price }}" selected>Normal</option> <option value="{{ j.express_price }}">Express</option> </select> </td> <td width="190" height="60"> <div class="input-group date" data-date-format="dd.mm.yyyy"> <div class="input-group mb-2"> <input type="text" class="form-control travel_date" name="travel_date" value="dd.mm.yyyy" placeholder="dd.mm.yyyy"> <div class="input-group-text"><i class="ti-calendar"></i></div> <div class="input-group-addon"> </div> <div class="input-group-prepend"> </div> </div> </div> </td> <td width="166">{{ j.currency_type }}&nbsp;&nbsp; <output name="result" class="package_price">{{ j.price }}</output>.00</td> </tr> {% endfor %} </tbody> </table> <button type="submit" class="btn btn-primary col-md-4 offset-md-4 mb-3" id="check">Next</button> </form> please help I am stuck in it since yesterday -
Modify simpleJWT response
I'm using the simpleJWT authentication in Django. By default the response is like this: { "refresh"="" "access"= "" } I want to customize the response not to have a header and to contain some user details eg { username: ' ', detail1: ' ', detail2: ' ', accessToken: ' ', refreshToken: ' ' } How can I implement a response like this using simpleJWT? -
Django HTML Email Message Automatically pick receiver's email from form
Please can anyone help me with this issue. I am trying to allow the users of my website to send out review request to customers by filling out a form on their profile page. They only have to provide the email address of the recipient then the backend would use this to configure a HTML message then send to the recipient. Currently, the whole system works just fine if I hard code the recipient email address. But once I try to get the email from request.POST['receiver'] it seems not to be passing the argument to the function. Here is the view function: def request_review_api(request): receiver_email = request.POST['receiver'] print(receiver_email) request_review(request, receiver_email) return redirect('profile_company') @login_required(login_url='loginpage_company') @allowed_users_company(allowed_roles=['company']) def request_review(request, receiver_email): company = get_object_or_404(Company, user=request.user) company_id = company.pk print(company) html_tpl_path = 'companyusers/request_review.html' context_data = {'company': company, 'company_id': company_id,} email_html_template = get_template(html_tpl_path).render(context_data) receiver = receiver_email email_msg = EmailMessage('Review Request', email_html_template, settings.EMAIL_HOST_USER, [receiver], reply_to=['no-reply@bbb.com'], ) # this part allows the message to be send as html instead of plain text email_msg.content_subtype = 'html' email_msg.send(fail_silently=False) This is what I have in my Template: <p class="tm-request-review-display card-text"> <form class="tm-request-review-display" action="{%url 'request_review' %}" method="POST"> {% csrf_token %} <div class="form-group"> <div class="col-md"> <input type="email" class="form-control" name="receiver" id="receiver" placeholder="Enter Reviewer's Email"> … -
User deactivation in Django
I am trying to allow users to deactivate their accounts on my django website. Here is what I have tried: views.py from django.contrib.auth.models import User @login_required def deactivate_user(request, username): context = {} try: user = User.objects.get(username=username) user.is_active = False user.save() context['msg'] = 'Profile successfully disabled.' except User.DoesNotExist: context['msg'] = 'User does not exist.' except Exception as e: context['msg'] = e.message return render(request, 'index.html', context=context) urls.py path('deactivate-user/<slug:username>', deactivate_user, name='deactivate_user'), base.html <form action="{% url 'users:deactivate_user' slug=username.slug %}" method="post"> {% csrf_token %} <button type="submit" class="active">Yes, Deactivate</button> <button type="button" data-dismiss="modal">Cancel</button> </form> I am getting a NoReverseMatch error Reverse for 'deactivate_user' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['users/deactivate\\-user/(?P<username>[-a-zA-Z0-9_]+)$'] Have tried a few different parameters in the template but can't get anything to work. -
add a pop up dropdown list when choose a radio button in django
I use Django 2.2.16 in windows 10. In my frontend page, I have to achieve this function, after choosing a radio button, a dropdown list will pop up. I have finished the radio button editing and know how to do dropdown list, but I do not know how I could achieve such kind of popup function after choosing the radio button. HTML: {% extends 'base.html' %} {% load static %} {% load humanize %} {% block content %} <div class="row"> <form> <label class="radio-inline"> <input type="radio" name="optradio" checked>&nbsp;Latest Available Semester </label> <label class="radio-inline"> <input type="radio" name="optradio">&nbsp;Specific Semester </label> </form> </div> -
my signup data are not saving in database table auth_user
I have created a signup form using django default django.contrib.auth signup form but it's not saving any data from sign up form.i watched many tutorial but couldn't reslove it tried deleting all my previous migrations as well but still facing this is issue , i am using mysql as my database kindly help if one can my form.py class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username', 'email',] views.py from django.shortcuts import render from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.forms.utils import ErrorList from django.http import HttpResponse from .forms import LoginForm, SignUpForm def login_view(request): form = LoginForm(request.POST or None) msg = None if request.method == "POST": if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("/") else: msg = 'Invalid credentials' else: msg = 'Error validating the form' return render(request, "accounts/login.html", {"form": form, "msg" : msg}) def signup(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): form.save() return redirect('admin') else: form = SignUpForm() else: form = SignUpForm() return render(request, "accounts/register.html", {"form": form}) signup template {% extends "layouts/base-fullscreen.html" %} {% load static %} {% block title %} Login {% endblock … -
Activating virtual environment for django in command line versus activating it in the Atom terminal
I am having a hard time activating virtual environment, after I have created it. The thing is, that when I try to activate virtual environment in command line, it works - virtualenvironmentname\Scripts\activate But when I try to run the same command in Atom, (I am using the Terminus package in order to be able to run the terminal inside of Atom) I get this message - (path) cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. I was trying to run it by using slightly different commands such as - activate virtualenvironmentname or activate (virtualenvironmentname) , but it did not work. I was further investigating a little more and I have found some clues, that I might need to change some script execution policies, but I am little bit afraid to do so, because I do not want to mess up my computer since I am just a beginner when it comes to system configuration. Could anybody please tell me, how could I fix this problem? It would be really convenient for me to be able to run the virtual environment from Atom, since I will be writing my Python and … -
Cann't send email in production
I am developing online shop and everything worked fine on local machine.Client add item to cart, enter his credentials click 'Make Order' and than order confirmation should be sent to his email. And it was working fine, even with redis + celery, but since when I've deployed project to server (linode.com), order confirmation doesn't work. Worker took tasks but never execute this. I thought it was due to celery, and I've made decision to make sending email without task manager and queue. But it didn't help. I use UFW firewall in the server: To Action From -- ------ ---- 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere Anywhere ALLOW 96.126.119.66 443 ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) 443 (v6) ALLOW Anywhere (v6) I get error like this: [Errno 110] Connection timed out Hope you will help me to understand the issue Traceback: Environment: Request Method: POST Request URL: https://bauerdress.ru/orders/create/ Django Version: 3.1 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'shop.apps.ShopConfig', 'cart.apps.CartConfig', 'orders.apps.OrdersConfig', 'wishlist.apps.WishlistConfig', 'widget_tweaks', 'crispy_forms', 'information.apps.InformationConfig', 'promotion.apps.PromotionConfig', 'django_filters', 'email_sub.apps.EmailSubConfig', 'django_simple_coupons', 'ckeditor', 'flower', 'allauth', 'allauth.account', 'allauth.socialaccount'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/kirill/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", … -
How to filter Posts Query in order to just see the posts of friends and Myself in Django
Guys I have built up a friendship system in my social media and it works properly. The last step is to restrict each user to see the posts from his or her own and friends. The following shows everything which I have guessed would be important. The view for the posts: class PostListView(LoginRequiredMixin,ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' def get_queryset(self): friends = User.objects.get(id=self.request.user.id).profile.friends.all() posts = Post.objects.filter(author = self.request.user) return posts def get_friends(self): friends = User.objects.filter(profile.friends).all() return friends the Post model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) content= models.TextField() image = models.ImageField(blank=True, null=True, upload_to='post_pics') likes = models.ManyToManyField(User, related_name='blog_post') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def save(self, *args, **kwargs): super().save() if self.image: img = Image.open(self.image.path) if img.height > 900 and img.width > 900: output_size = (900,900) img.thumbnail(output_size) img.save(self.image.path) def get_absolute_url(self): return reverse('post_detail', kwargs={'pk':self.pk}) def get_number_of_likes(self): return self.likes.count() The profile model which is is created via signals whenever a new user registers: class Profile(models.Model): love_status_choices = [ ('-', '------'), ('married', 'Married'), ('single', 'Single'), ('inrel', 'In Releationship') ] user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') image = models.ImageField(default='default.png', upload_to='profile_pics') bio = models.TextField(blank=True, null=True) expertise = models.CharField(max_length=100, blank=True, null=True) age = models .IntegerField(blank=True, null=True) love_status = models.TextField(choices=love_status_choices, default="-", blank=True, … -
How do I get the path from MEDIA_ROOT to save it as a string in my Model?
So, I've successfully uploaded and saved my uploaded files in the "Media" directory in my project. Now what I'm trying to do is get the path of the saved file and save it as a string in my CharField made in my model. Executing data1.append('doc1', $('#file1').val()) gets the path where the file is originally saved like this: C:\fakepath\<filename>. However, what I need is the full path of the media directory where I've saved the file via the form, which would be: C:\Users\bilal\PycharmProjects\<proj name>\media\<filename>. So how would I go about getting this done? I'm sharing the complete project for clarity as well. Thank you. index.html <body> <div class="container-fluid"> <div class="col-md-4"> <form id="data"> <label for="docn"> <input type="text" id="docn" placeholder="Please enter document name"> </label> <label for="docc"> <input type="file" id="doc" name="docu"> </label> <button type="button" onclick="enterdata()">Submit</button> </form> </div> </div> <script> function enterdata() { var data1 = new FormData() data1.append('dcn', $('#docn').val()) data1.append('dc', $('#doc').val()) data1.append('docf', $('#doc')[0].files[0]) var token = '{{ csrf_token }}'; alert('csrf generated'); $.ajax({ type: 'POST', url: '/user', data: data1, processData: false, contentType: false, headers: {'X-CSRFToken': token}, success: function () { alert("Added"); } }) } </script> </body> views.py def insert(request): return render(request, 'index.html') def testing_data(request): if request.method == 'POST': dcn1 = request.POST['dcn'] upload_file = request.FILES['docf'] path … -
How to consolidate Django (different models) database and store at centralized place
I have created a Django-based webpage where different vendor company employees can logins and can change their Shift Timing. (Now we are controlling this job with Linux script but due to large user size ~8k doing it for all requests is a difficult task). To resolve this I have created a Django webpage( 6 separate models/DB) and used default SQLite DB. Requirement: The user is working on some application which needs to be controlled by updated shift timing on the portal. Question: How to consolidate OR store DB data in a centralized place? so that if tomorrow I have to reset the Timing for all the users in the portal to default consider General Shift. I have the below Idea to do this but not sure if this is the best way to complete this work. by using the REST API I will get the JSON data.OR manage.py dumpdata apple.CompanyName(Model) --indent 5 any help/Suggestion on this would be appreciated. -
Django not displaying images after adding product details
Django can be able to display the image if I comment out the product details page. I would like to know why it does that and how can I make it always display the images. Product model item_name = models.CharField(max_length=20) item_description = models.TextField( max_length=200, verbose_name="Item Description") item_price = models.FloatField(default=0.00) slug = models.SlugField(null=True, unique=True) item_details = models.TextField( max_length=1000, verbose_name="Item Details") item_quantity = models.IntegerField(default=0) item_availability = models.BooleanField(default=False) is_item_featured = models.BooleanField(default=False) is_item_recommended = models.BooleanField(default=False) # Todo: add Is On Carousel Filter item_brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) item_categories = models.ForeignKey( Category, null=True, on_delete=models.CASCADE) item_image = models.ImageField(upload_to='images/product/', default="images/product/image-placeholder-500x500.jpg") Product Views class HomePageView(ListView): model = Product template_name = 'product/index.html' class ProductListView(ListView): model = Product template_name = 'product/product_list.html' def product_detail(request, slug): objec = get_object_or_404(Product, slug=slug) template_name = 'product/product_detail.html' return render(request, template_name, context={'object': objec}) Product Templates {% for product in object_list %} <div class="col-md-3 col-sm-6"> <div class="product-grid4"> <div class="product-image4"> <a href="product/{{ product.slug }}"> <!-- <img src="{{ product.item_brand.brand_image.url }}" alt="{{ product.item_brand.brand_name }}" width="30px"> --> <img class="pic-1" src="{{ product.item_image.url }}" alt="{{ product.item_name }}"> </a> <!-- <span class="product-new-label">Recommended</span> --> <!-- <span class="product-discount-label">-10%</span> --> </div> <div class="product-content"> <h3 class="title"><a href="#">{{ product.item_name }}</a></h3> <div class="price"> Kshs. {{product.item_price }} <!-- <span>$16.00</span> --> </div> <a class="add-to-cart" href="{% url 'add-to-cart' product.slug %}">ADD TO CART</a> </div> </div> … -
join two django models other than foreignkey
I have two models class Invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) quotation_id = models.IntegerField(blank=True, null=True) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) invoice_number = models.IntegerField(blank=True, null=True) quotation_number = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) total_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) total_tax = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) document_type = models.CharField(max_length=50, default='', blank=True, null=True) and class Invoice_Description(models.Model): invoice_id = models.IntegerField(blank=True, null=True) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) quotation_id = models.IntegerField(blank=True, null=True) item_id = models.ForeignKey(tbl_item, on_delete=models.CASCADE) item_qty = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) item_unit_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) Invoice contains information about the invoice document, its total price, date, etc while Invoice_Description keeps the records of items added on that particular invoice, item price, total quantity, discount on each item, etc. I want to display all the records in reports with respect to items like ITEM NAME CUSTOMER NAME INV. NO. QTY DOCUMENT TYPE UNIT PRICE SALE PRICE Item1 Client1 01 950.00 1000.00 I have all the columns available from Invoice_Description except for the INV. NO. and DOCUMENT TYPE which are in the Invoice model. I don't want to use a ForeignKey in this case because these models are already in use in many places, changing the database will require changes everywhere. my problem is just that I want … -
deploy React and Django with Nginx and Docker
I'm trying to deploy my React build and Django API using Nginx and Docker. I'm still really new to deployment and have never hosted a website that would go into production so am a little at a loss. Right now I have my Django API run on port 8000 and the React app runs on port 3000. I'm hoping to use Nginx to direct the IP address to the React app or Django API depending on the URL. Some examples: http://10.2.5.250/: would serve the React build at port 3000 http://10.2.5.250/upload: would serve the Django template file index.html at port 8000 http://10.2.5.250/median-rent?table=MedianRent: would serve the Django api at port 8000 This is my project structure: . ├── docker-compose.yml ├── front-end │ ├── Dockerfile │ ├── README.md │ ├── debug.log │ ├── node_modules │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── src │ └── yarn.lock ├── housing_dashboard_project │ └── housing_dashboard │ ├── Dockerfile │ ├── dashboard_app │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ ├── models.py │ │ ├── serializers.py │ │ ├── static │ │ ├── templates │ │ │ └── dashboard_app │ │ │ └── index.html │ │ ├── urls.py │ … -
Python, Django: New Line in Mail
Good day to all of you, the django-function for sending a mail (see bellow) works perfectly fine! from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) Unfortunately there are no informations about creating new lines inside the message text! Does anyone know the solution or has the same problem? What's the best way to include these? Thanks and a great weekend! -
Fetch data from size table by getting id from mapping table in django?
I am creating a printing ordering service website in django and i am stuck on order page. I have three tables named "product" ,"size" and "sizeProductMap" table. I want to get all those sizes from size table releted to a particular product here a single product can have different sizes. The sizeProductMap tables stores primary key of product table and size table as foreign key, now i want to get those sizes which has mapping with a particular product. -
Prefetch won't filter (django)
If I do following prefetch, django won't do my filter in the prefetch: devices = Device.objects.filter(site__id=site_pk,).prefetch_related( "site", Prefetch( "deckdevice__deck__airspace", queryset=DeckDevice.objects.filter(end__isnull=True), ) ) but doing this works: devices = Device.objects.filter(site__id=site_pk,).prefetch_related( "site", Prefetch( "deckdevice", queryset=DeckDevice.objects.filter(end__isnull=True), ), "deckdevice__deck__airspace", ) Is that normal? Because the second approach seems inefficient to me. -
Django Celery beat 5.x does not execute periodic_task
I'm currently trying to migrate from celery 4.x to 5.x but I'm unable to get celery beat to process a periodic_task. Celery beat simply does not touche the code here it seems. Processing tasks I call manually from a view is not a problem at all and working fine for the worker process. So I would at least expect that my settings are fine but I don't understand why the periodic_task are not processed. Can smb help? did I forget to call something?! Also see docs here: https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html settings.py # Celery Settings: BROKER_URL = 'redis://' + ':' + env.str('REDIS_PWD') + '@' + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT') BROKER_TRANSPORT = 'redis' CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_RESULT_EXPIRES = 3600 CELERY_REDIS_HOST = env.str('REDIS_HOST') REDIS_PWD = env.str('REDIS_PWD') CELERY_REDIS_PORT = env.str('REDIS_PORT') CELERY_REDIS_DB = env.str('REDIS_CACHE_DB') CELERY_CACHE_BACKEND = 'default' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'GMT' CELERYD_TASK_SOFT_TIME_LIMIT = 900 celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery import environ from django.conf import settings from MyApp import settings env = environ.Env() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyApp.settings") app = Celery(settings.SITE_NAME) app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(10.0, … -
How to delete old styles of django
I have multiple projects of django running on my PC for learning. When I open second project, it is still loading the styles of first project. How to clear this? -
how to submit form with ajax and than redirect on another page with data in django
i want to send my form data via ajax and than redirect page and get form on another page in django.But i am not able to access data please help. this is my search.py file : def search(request): if request.method == "GET": get_query = request.GET.get('country') get_nationality = request.GET.get('nationality') if get_query == "" or get_nationality == "": return redirect('/') get_country = Country.objects.filter(name=get_query) legal = Legal.objects.all() get_package = Package.objects.filter(country_name__name__contains=get_query) return render(request,'frontend/search_result.html',{ 'nationality':get_nationality, 'country':get_country, 'package':get_package, 'legal':legal, }) else: return redirect('/') and than i am showing this data on search_result.html : <form name="form" method="POST" id="form"> {% csrf_token %} <table class="table table-bordered table-responsive" id="flip-scroll"> <thead> <tr> <th scope="col">Package Option</th> <th scope="col">Processing Type</th> <th height="60" scope="col">Travel Date</th> <th scope="col">Price</th> </tr> </thead> <tbody> {% for j in package %} <tr class="valid-container" data-id="{{ j.id }}"> <td style="cursor:pointer;" width="200"><input type="checkbox" name="c1" class="checkbox">&nbsp; <output class="type" style="font-size:14.5px !important;">{{ j.type }}</output></td> <td height="52" width="158"> <select class="custom-select processing_type" name="processing_type" required> <option value="{{ j.price }}" selected>Normal</option> <option value="{{ j.express_price }}">Express</option> </select> </td> <td width="190" height="60"> <div class="input-group date" data-date-format="dd.mm.yyyy"> <div class="input-group mb-2"> <input type="text" class="form-control travel_date" name="travel_date" value="dd.mm.yyyy" placeholder="dd.mm.yyyy"> <div class="input-group-text"><i class="ti-calendar"></i></div> <div class="input-group-addon"> </div> <div class="input-group-prepend"> </div> </div> </div> </td> <td width="166">{{ j.currency_type }}&nbsp;&nbsp; <output name="result" class="package_price">{{ j.price }}</output>.00</td> </tr> {% endfor %} … -
Can Django be used to build REST APIs without DRF?
I am developing an application whose front-end will be in React. I am familiar with the Django Templating system, returning html pages on requests. I am not sure how to build REST APIs in Django. Can anyone share code examples. I want to use pure Django not Django REST Framework