Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        How to implement DB Connection Pool in DjangoDjango kills db connection after every request. It is an overhead to create a new db connection every time so how can we implement a connection pool from where we can use connection objects.
- 
        Is there a clean way to lower the cyclomatic complexity of Django templates?I have a Django template I'm working on that takes an object that has multiple properties and adds different tags based on those properties. For example if object.bold == True it adds the <b></b> tag, and if object.strikethrough == True it adds the <strike></strike> tag. I've seen some other posts that smell which suggest nesting the ifs like: {% for object in objects %} {% if object.bold == True %} {% if object.strikethrough == True %} <b><strike>{{object.name}}</strike></b> {% else %} <b>{{object.name}}</b> {% endif %} {% else %} {% if object.strikethrough==True %} <strike>{{object.name}}</strike> {% else %} {{object.name}} {% endif %} {% endif %} {% endfor %} This code hurts me. I've also seen some wonky logic with only wrapping the beginning tags in if statements. Again, it's painful to introduce console errors. Is there a better, cleaner way to achieve this result without nesting ifs? I'm leaning towards making a custom Django tag but that seems like overkill for something that I'm really hoping can be simpler.
- 
        Heart disease predictionI have source code to predict heart diseases, but it shows 1-if disease is exist, and 0-if none disease. I need to make precent of disease. Here is an example with logistic regression, but i have 4 algorithms, so i need to show precentege of risk. Actually, i am new in AI, so this is not my code at all but i need to improve it view.py: import csv,io from django.shortcuts import render from .forms import Predict_Form from predict_risk.data_provider import * from accounts.models import UserProfileInfo from django.shortcuts import get_object_or_404, redirect, render from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required,permission_required from django.urls import reverse from django.contrib import messages @login_required(login_url='/') def PredictRisk(request,pk): predicted = False predictions={} if request.session.has_key('user_id'): u_id = request.session['user_id'] if request.method == 'POST': form = Predict_Form(data=request.POST) profile = get_object_or_404(UserProfileInfo, pk=pk) if form.is_valid(): features = [[ form.cleaned_data['age'], form.cleaned_data['sex'], form.cleaned_data['cp'], form.cleaned_data['resting_bp'], form.cleaned_data['serum_cholesterol'], form.cleaned_data['fasting_blood_sugar'], form.cleaned_data['resting_ecg'], form.cleaned_data['max_heart_rate'], form.cleaned_data['exercise_induced_angina'], form.cleaned_data['st_depression'], form.cleaned_data['st_slope'], form.cleaned_data['number_of_vessels'], form.cleaned_data['thallium_scan_results']]] standard_scalar = GetStandardScalarForHeart() features = standard_scalar.transform(features) SVCClassifier,LogisticRegressionClassifier,NaiveBayesClassifier,DecisionTreeClassifier=GetAllClassifiersForHeart() predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True colors={} if predictions['SVC']=='0': colors['SVC']="table-success" elif predictions['SVC']=='1': colors['SVC']="table-danger" if predictions['LogisticRegression']=='0': colors['LR']="table-success" else: colors['LR']="table-danger" if predictions['NaiveBayes']=='0': …
- 
        install a django application for a client and protect its source code or convert it to an executableI have a Django web application, I want to install it for a client who doesn't want to use the internet so I have to install it locally on his pc, My question: what should I do to protect my source code. See that I have to put all my source code on his pc to be able to install the application, is there a possibility to encrypt the source code or to convert the django project into exe? thank you !
- 
        how to update multiple fields viahow to update multiple fields via Model.objects.bulk_create(list) I try it Model.objects.bulk_create(list).update(startD=startD, endD=endD) but error show 'list' object has no attribute 'update'
- 
        How I can create registration form using using my own usermodel in djangoI wanted to create my own registration form without using the crispy forms, I wanted to give my own styling to the form, please help me with steps or provide me a tutorial link. Thank You
- 
        Using a custom form inside django wizardHow would I use a custom form to display inside the session wizard so when it goes through each step it displays the html for each form inside the signup.html. createUser.html {% extends 'base.html' %} {% block title %}Create User{% endblock %} {% block content %} <form method="POST" action='.' enctype="multipart/form-data"> {% csrf_token %} <!-- A formwizard needs this form --> {{ wizard.management_form }} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button><a href="{% url 'signup' %}">Sign up</a></button> <button><a href="{% url 'login' %}">Log In</a></button> </form> {% endblock %} views.py class UserWizard(SessionWizardView): template_name = "registration/signup.html" form_list = [SignUpForm] def done(self, form_list, **kwargs): process_data(form_list) return redirect('home') signup.html {% extends 'base.html' %} {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block title %}Sign up{% endblock %} {% block content %} <h2>Sign up</h2> <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in …
- 
        Exception: Matching query does not existI am trying to generate a token for users requesting for forget password. I have a model to handle and store this. models.py class ForgetPassword(models.Model): user = models.ForeignKey(CustomUser, on_delete= models.CASCADE) forget_password_token = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add= True) def __str__(self): return self.user.email The view functions that handles the request are below views.py def forget_password(request): try: if request.method == 'POST': user_email = request.POST.get('email') if CustomUser.objects.filter(email = user_email).exists(): user_obj = CustomUser.objects.get(email = user_email) name = user_obj.full_name plan = user_obj.plan print("\n this is the user : ", user_obj, " this is its name : ", name,"\n") token = str(uuid.uuid4()) fp = ForgetPassword.objects.get(user = user_obj) fp.forget_password_token = token fp.save() forget_password_mail.delay(user_email, name, token) messages.info(request, 'An email has been sent to your registered email.') return redirect('forget-password') else: messages.info(request, 'User does not exist') return redirect('forget-password') except Exception as e: print("\nthe exception is comming from forget_password : ", e, "\n") return render(request, 'fp_email_form.html') So, here I am trying to get the user first in user_obj from my CustomUser model and then I am trying to get the same user in the ForgetPassword model and store the token against that user. But I am getting the below exception ForgetPassword matching query does not exist. Please suggest or correcct me where …
- 
        Django pagination not showing using class base viewHi looking for a solution and yet nothing solve to my problem, I do not know why but it is not showing the paginate number in html file. here is structure code: class ListEmployeeActivity(ListView, LoginRequiredMixin): paginate_by = 1 model = EmployeePersonalDetailsModel template_name = 'layout/employee_list_layout.html' context_object_name = 'datalist' def get_queryset(self): return self.model.objects.prefetch_related('ecdm_fk_rn').all() html file: {% if is_paginated %} <div class="pagination pagination-centered"> <ul> {% if datalist.has_previous %} <li><a href="?page={{ datalist.previous_page_number }}"><i class="icon-double-angle-left"></i></a></li> {% endif %} {% for total_pages in datalist.paginator.page_range %} <li><a href="?page={{ total_pages }}">1</a></li> {% endfor %} {% if datalist.has_next %} <li><a href="?page={{ datalist.next_page_number }}"><i class="icon-double-angle-right"></i></a></li> <li><a href="?page={{ datalist.paginator.num_pages }}">Last</a></li> {% endif %} </ul> </div> {% else %} <h3>Pagination not working.</h3> {% endif %}
- 
        Django causes error when I'm trying to send email. Error message: [Errno 61] Connection refusedI'm trying to send email from Django. My Django settings configurations are as follows: # SMTP Settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "my_email@gmail.com" # my email address goes here. EMAIL_HOST_PASSWORD = "my_generated_password" # generated password EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "fmk@gmail.com" However when I'm trying to send email from it either using celery or directly from views it says "[Errno 61] Connection refused". N.B: I'm using a mac matchine for the development. Is there any security reason for send email using Mac. Views Code Sample: def send_mail_to_all(request): send_mail('Celery Test Mail Subject', "Test Mail Body", from_email='sender@gmail.com', recipient_list=['repientsemail@gmail.com'], fail_silently=False ) # send_mail_func.delay() return HttpResponse('Sent') Celery Task Schedular Code: @shared_task(bind=True) def send_mail_func(self): users = get_user_model().objects.all() for user in users: mail_subject = "Celery Testing" message = f"This is the celery testing message at {datetime.now()}" to_email = user.email send_mail(mail_subject, message, from_email=settings.EMAIL_HOST_USER, recipient_list=[to_email,], fail_silently=False ) return 'Done'
- 
        create a dictionary of with key as the attribute and value as model objectSay i have this table: class Blog(models.Model) title = models.CharField() body = models.CharField() author = models.ForeignKey(Author) I need to create 3 rows with the title (title_1, title_2, title_3). I need to fetch all the blog objects and create a dictionary with key as the title and value as blog object. blog_dict = {'title_1': <blog_object_1>, 'title_2': <blog_object_2>, 'title_2': <blog_object_3>} I have 1 million records to work. Is there any efficient way to do it?
- 
        Django Python urlencode same key with multiple valuesAs the title suggest I am trying to urlencode using Ordered Dict in python def url_replace(request, field, value, direction=""): dict_ = request.GET.copy() if field == "order_by" and field in dict_.keys(): if dict_[field].startswith("-") and dict_[field].lstrip("-") == value: dict_[field] = value elif dict_[field].lstrip("-") == value: dict_[field] = "-" + value else: dict_[field] = direction + value else: dict_[field] = direction + str(value) print("UNORDERED___________________") print(dict_) print(super(MultiValueDict, dict_).items()) print("ORDERED_____________") print(OrderedDict(super(MultiValueDict, dict_).items())) print(OrderedDict(dict_.items())) return urlencode(OrderedDict(dict_.items())) The output for the above code UNORDERED___________________ <QueryDict: {'assigned_to_id': ['1', '2'], 'client_id': ['2', '1'], 'page': ['2']}> dict_items([('assigned_to_id', ['1', '2']), ('client_id', ['2', '1']), ('page', ['2'])]) OrderedDict([('assigned_to_id', '2'), ('client_id', '1'), ('page', '2')]) ORDERED_____________ OrderedDict([('assigned_to_id', ['1', '2']), ('client_id', ['2', '1']), ('page', ['2'])]) OrderedDict([('assigned_to_id', '2'), ('client_id', '1'), ('page', '2')]) As you can see the assigned_to_id has only 2 in the end . What I am expecting is a ordered dict with OrderedDict([('assigned_to_id', '2'),('assigned_to_id', '1'), ('client_id', '1'), ('client_id', '2'),('page', '2')]) Maybe there might be a better approach for this, I am a bit new to python My final aim is to return a dict with multiple keys or anything that can be used in urlencode
- 
        Display Model Hierarchy of a field in django admin formI have django models like below: class Subscription(models.Model): """ A subscription to a product. """ # Possible interval values. user = models.ForeignKey( to='account.User', related_name='subscriptions', on_delete=models.PROTECT, ) uuid = models.UUIDField(unique=True, default=uuid4) product = models.ForeignKey( to='product.Product', related_name='subscriptions', blank=True, null=True, on_delete=models.PROTECT, ) base_plan = models.ForeignKey( to='product.Plan', on_delete=models.PROTECT, ) #code goes on... class Plan(models.Model): """ Specifies a given set of billing parameters for a package. """ name = models.CharField(_('name'), max_length=50) uuid = models.UUIDField(unique=True, default=uuid.uuid4) product = models.ForeignKey(to=Product, related_name='plans', on_delete=models.PROTECT) package = models.ForeignKey(to=Package, related_name='plans', on_delete=models.PROTECT) #code goes on... class Product(BillingProduct): """ A product is a collection of features that can be subscribed to. """ name = models.CharField(_('name'), max_length=50) uuid = models.UUIDField(unique=True, default=uuid.uuid4) slug = models.SlugField(_('slug')) active = models.BooleanField(_('active'), default=True) description = models.TextField(help_text=_("The public-facing description for the product can include HTML."), blank=True) #code goes on... class Package(models.Model): """ Specifies a collection of features that a user can buy or trial. """ name = models.CharField(_('name'), max_length=50) uuid = models.UUIDField(_('UUID'), unique=True, default=uuid.uuid4) product = models.ForeignKey(to=Product, related_name='packages', help_text=_("Must match features selected."), on_delete=models.PROTECT) feature_set = models.OneToOneField(to='product.FeatureSet', related_name='+', on_delete=models.PROTECT) #code goes on... and Django Form like below that will be used in SubscriptionAdmin: class SubscriptionForm(forms.ModelForm): class Meta: model = Subscription exclude = [] widgets = { 'user': CustomerWidget } base_plan = …
- 
        I have some issues I never had to deal with in the development phase. When the users posts some actions, I sometimes get the following errorWhat really frustrates me is that the project works fine in the local environment and furthermore, the matching query object DOES NOT exist in the Database. And also my password1 and password2 fields does not exits in database table even i created in form.py. Image of error page
- 
        none is saving in django adminproductscreate.html <form data-bind="submit: save" method="post"> {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: $data.title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description" data-bind="value: $data.description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image" ></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: save">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script> var ViewModel = function () { var self = this; self.title = ko.observable(""); self.description = ko.observable(""); var FormData = { title: self.title, description: self.description, }; console.log(FormData); self.save = function () { $.ajax({ type: "POST", url: 'http://127.0.0.1:8000/productsadd', data: FormData, contentType: "application/json", headers: {'X-CSRFToken': csrftoken}, cache: false, enctype: "multipart/form-data", //processData: false, success: function (FormData) { alert("successfull") window.location = '{% url "productslist" %}'; }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new ViewModel()) </script> views.py class ProductsCreate(CreateView): model …
- 
        Django application run without command line like php web applicationI want to launch Django application without giving command "python manage.py runserver". Like how php works, when hit the index file it will launch the application but in django/python i didn't find any way to do that in windows OS except run the project from command line which is cautious for robust application. Please let me know/suggest any idea about if it is possible for windows or not??
- 
        Issue to call message handler (Django Channels)I have this portion of code in my app/views.py (to send signals to the group over the websocket just priori posting a new object in my db): from django.core import serializers import channels.layers from .consumers import serialize_games from asgiref.sync import async_to_sync def send_game_update(event): ''' Call back function to send message to the browser ''' print('@call_back:into it') message = event['message'] channel_layer = channels.layers.get_channel_layer() # Send message to WebSocket async_to_sync(channel_layer.send)(text_data=json.dumps( message )) print('@call_back: messages sent to lobby') def send_update_signal(): games = serialize_games() channel_layer = channels.layers.get_channel_layer() # Send new game info to Lobby async_to_sync(channel_layer.group_send)( 'Lobby', { 'type': 'send_game_update', 'message': games }) print('@receiver: just before messages sent to lobby') And django raises: ValueError: No handler for message type send_game_update Exception inside application: No handler for message type send_game_update Is that a namespace issue?
- 
        How to link comment model to Post model djangoI want to link a comment model to post when multiple posts are displayed in a page i want to access the post id of the post i am commenting on but i do not know how please tell me how to link the comment model I am a begginner here so i apologize for any errors Please comment if any more of code is needed template : {% for Img in imgs %} <div class="container"> <div class="card"> <div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="{{ Img.Post_Img.url }}" alt="image"> </div> <div class="card-content"> <img src="{{ Img.op.userprofile.Profile_pic.url }}" class="profiles" alt="{{ Img.op.userprofile.Nick_Name }}"> <span class="OP">{{ Img.op.userprofile.Nick_Name }}</span> <span class="card-title activator white-text text">{{ Img.Title }}<i class="material-icons right">more_vert</i></span> <p><a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">Vote</a></p> </div> <div class="card-reveal darken-4 black"> <span class="card-title white-text text">{{ Img.Title }}<i class="material-icons right">close</i></span> <form method="post"> {% csrf_token %} {{ comment }} <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </form> {% for comment in comments %} {{ comment.op.userprofile.Nick_Name }}{{ comment.comment }} {% endfor %} </div> </div> </div> {% endfor %} models : class MemeImg(models.Model): Title = models.CharField(max_length=500) date_created = models.DateTimeField(auto_now_add=True) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) Post_Img = CloudinaryField('Post') def __str__(self): return self.Title class Comments(models.Model): post = models.ForeignKey(MemeImg, on_delete=models.CASCADE) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) …
- 
        Install django on windows with a VirtualenvI'm at the end of my rope here. I have been trying for two days to get django deployed on a windows machine (as in full deployment). I can get python and django, postgres everything in place and the django test server works. Then all goes to pot!! I have tried configuring IIS, and tried Nginx/Waitress and had issues with both. On the last one django manage.py just stopped working. Does anybody know of a guide that actually works on prod deployment on windows. without having to guess at missing pieces and the need to reinstall windows half a dozen times. I would also like to deploy in a virtualenv as I and using cython compiled files so need to use a specific python version Thanks Pigged off Linux User!!!
- 
        Django: Why does my custom command starts the server?I am trying to use Scrapy with Django so I defined the following custom management command: from django.core.management.base import BaseCommand from scraper.spiders.sparerooms import SpareroomsSpider from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from scrapy.settings import Settings import os class Command(BaseCommand): help = "Release the spiders" def handle(self, *args, **options): os.environ.setdefault('SCRAPY_SETTINGS_MODULE', 'scraper.settings') process = CrawlerProcess(get_project_settings()) process.crawl(SpareroomsSpider) process.start() When I run the command python3 manager.py crawl the server is instantiated; I can see libraries and files from another app being loaded before crawling, which is really annoying as I have a large amount of data to load (30min wait). It wouldn't be such a problem if the server was usable. However, request.META is not set (unable to use request.build_absolute_uri()) and the endpoints are not reachable Error 111: Connection Refused. All of this works fine if I start the server with python3 manage.py runserver and than use the custom command (which loads the server again). What am I doing wrong? Can it be fixed?
- 
        Unable to create API from django rest_frameworkCan anyone please help me? I am not able to create API with GET POST PUT DELETE methods. Also when I go to this url: "http://127.0.0.1:8000/api/packages/" I cant see Django default API view. My users API is working fine with all methods but not packages. Models.py class Customer(models.Model): user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True) phone = models.CharField(max_length= 200, null = True) dob = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Packages(models.Model): STATUS = ( ('Drafts', 'Drafts'), ('Published', 'Published'), ) name = models.CharField(max_length=50, null=True) details = models.CharField(max_length=200, null=True) price = models.PositiveIntegerField() days = models.CharField(max_length=10, null=True) nights = models.CharField(max_length=10, null=True) image = models.ImageField(null=True, blank=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.name Views.py @csrf_exempt def packagesAPI(request, id=0): if request.method == 'GET': packages = Packages.objects.all() packages_serializer = PackagesSerializer(packages, many=True) return JsonResponse(packages_serializer.data,safe=False) elif request.method == 'POST': packages_data = JSONParser().parse(request) packages_serializer = PackagesSerializer(data = packages_data) if packages_serializer.is_valid(): packages_serializer.save() return JsonResponse("Added Successfully",safe=False) return JsonResponse("Failed to Add",safe=False) elif request.method == 'PUT': packages_data = JSONParser().parse(request) packages = Packages.objects.get(package_id = packages_data['package_id']) packages_serializer = PackagesSerializer(packages,data = packages_data) if packages_serializer.is_valid(): packages_serializer.save() return JsonResponse("Updated Successfully",safe=False) return JsonResponse("Failed to Update") elif request.method == 'DELETE': packages = Packages.objects.get(package_id=id) packages.delete() return JsonResponse("Deleted Successfully",safe=False) @csrf_exempt def SaveFile(request): file = requestFILES['file'] file_name …
- 
        Trying to connect Docker + Django to Postgres - could not translate host name "db" to address: Name or service not knowI'm trying to Dockerize a Django + Postgres project following this tutorial: https://docs.docker.com/samples/django/ When I run docker-compose up I get: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Dockerfile # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': 5432, } }
- 
        Need to add a search functionality on Django class based viewI have a search function on a function based view that works fine. This is the function based view code: def BlogList(request): blogs = Blog.objects.all() if request.method == 'GET': search = request.GET.get('search', '') blogs = Blog.objects.filter(blog_title__icontains=search) return render(request, 'App_Blog/blog_list.html', context={'search':search, 'blogs':blogs}) But now I want to replace that function based view by implementing it on this class based view. class BlogList(ListView): context_object_name = 'blogs' model = Blog template_name = 'App_Blog/blog_list.html' This is my models.py: class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name="Put a Title") slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What is on your mind?") blog_image = models.ImageField(upload_to='blog_images', verbose_name="Image") publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['-publish_date',] def __str__(self): return self.blog_title html part for search function: <form class="form-inline ml-auto" method="GET"> <input class="form-control mr-sm-2" type="text" name="search" placeholder="Search the topic"> <button class="btn btn-success" type="submit">Search</button> </form> As I am a newbie, I have tried different solutions but not getting it through. I'll be glad if someone help me on this.
- 
        How to return raw sql queries as json objects?(Django)I am using the following function to display the sql join query as json: def toggle_query(request,id): obj = DibbsSpiderDibbsMatchedProductFieldsDuplicate.objects.raw('''SELECT * FROM dibbs_spider_solicitation JOIN dibbs_spider_dibbs_matched_product_fields_duplicate ON dibbs_spider_solicitation.nsn = {nsn};'''.format(nsn=id)) context = serializers.serialize('json',obj) return JsonResponse(context,safe=False) This displays data as : "[{\"model\": \"dibbs_spider.dibbsspiderdibbsmatchedproductfieldsduplicate\", \"pk\": 39, \"fields\": {\"nsn\": \"1650011162908\", \"nsn2\": \"6550015746831\", \"cage\": \"34807\", \"part_number\": \"6903A-J\", \"company_name\": null, \"supplier\": \"GraingerOM\", \"cost\": \"18.16\", \"list_price\": \"19.12\", \"gsa_price\": null, \"hash\": \"665\", \"nomenclature\": \"HOUSING, CONTROL MOD\", \"technical_documents\": \"Tech Docs\", \"solicitation\": \"SPE2DS22T1575\", \"status\": \"Awarded \", \"purchase_request\": \"0091648844\\nQty: 5\", \"issued\": \"2021-12-09\", \"return_by\": \"2021-12-14\", \"file\": \"https://dibbs2.bsm.dla.mil/Downloads/RFQ/5/SPE2DS22T1575.PDF\", \"vendor_part_number\": \"269P71\", \"manufacturer_name\": \"LAMOTTE\", \"product_name\": \"Reagent Tablet Type 0 to 4 ppm Range\", \"unit\": \"EA\"}}, {\"model\": How to remove the \ symbol which is not the part of the data here ?
- 
        Python Billiard cannot find project module on restarting Celery worker processRunning Python 2.7, Celery 3.1.23, Billiard 3.3.0.23. I'm getting the Celery workers crashing on any stack trace. Inspecting the workers using celery worker from the shell gives this stack: [2022-01-03 03:39:17,822: ERROR/MainProcess] Unrecoverable error: ImportError('No module named <my project>',) Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/celery/worker/__init__.py", line 206, in start self.blueprint.start(self) File "/usr/local/lib/python2.7/site-packages/celery/bootsteps.py", line 123, in start step.start(parent) File "/usr/local/lib/python2.7/site-packages/celery/bootsteps.py", line 374, in start return self.obj.start() File "/usr/local/lib/python2.7/site-packages/celery/concurrency/base.py", line 131, in start self.on_start() File "/usr/local/lib/python2.7/site-packages/celery/concurrency/prefork.py", line 119, in on_start **self.options) File "/usr/local/lib/python2.7/site-packages/celery/concurrency/asynpool.py", line 401, in __init__ super(AsynPool, self).__init__(processes, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/billiard/pool.py", line 972, in __init__ self._create_worker_process(i) File "/usr/local/lib/python2.7/site-packages/celery/concurrency/asynpool.py", line 415, in _create_worker_process return super(AsynPool, self)._create_worker_process(i) File "/usr/local/lib/python2.7/site-packages/billiard/pool.py", line 1068, in _create_worker_process w.start() File "/usr/local/lib/python2.7/site-packages/billiard/process.py", line 137, in start self._popen = Popen(self) File "/usr/local/lib/python2.7/site-packages/billiard/forking.py", line 91, in __init__ _Django_old_layout_hack__save() File "/usr/local/lib/python2.7/site-packages/billiard/forking.py", line 379, in _Django_old_layout_hack__save project = __import__(project_name) ImportError: No module named <my_project> It looks like Billiard is unable to load in the project module at all. However, you can run a shell on the celery worker by calling celery shell, and running forking._Django_old_layout_hack__save() works just fine.