Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send a command like data from react front-end to back-end through websockets? (React-Django)
Hey I am trying to learn using websockets and currently stuck with certain problems. How can I send data from react to back-end django (django channels)? I need to send a command, say 'join' from the front-end to start and initiate the websocket connection and then a command 'message' if user sends a message. What I am planning is to send a onopen when the page renders and send a 'join' command, but that isn't working. I tried like this, chatSocket.onopen = () => { chatSocket.send(JSON.stringify('command': 'join')) ---> does not work with the back-end and to send the message, I have this.. (which works when the condition is checked with not None) const messageOnSubmit = (e) => { chatSocket.onopen = () => { chatSocket.send(JSON.stringify(message: e.target.value)) setInput('') } } and in the back-end, I have async def websocket_receive(self, event): # when a message is recieved from the websocket print("receive", event) command = event.get("text", None) print(command) if command== "join": 'do something' elif command == "message": 'do something' I would like to implement such a feature..like checking what command is comming from the front-end and then dispatching an action. how to do this? as of now, I am just checking the condition, like … -
Where do i run my code, which requires a intense usage of CPU?
I don't know if my question is weird, but i'm developing a SaaS for a company and using the following technologies: Python Docker Django Redis Celery I have initialized a EC2 instance, with only 1 CPU. My question is: I have to allow users to run features in a asynchronous way (Celery, Redis), but, It doesn't seem to me that run those tasks locally (with only 1 CPU) is right. I'm facing some troubles trying managing tasks/queues in my application, probably due to the unique CPU. Do i initialize a better instance (with 2 CPUs or greater) or i could possibly run those intense tasks in a serveless, like AWS Lambda or Iron.io (I don't know well those technologies, but if someone tell me that this is the best solution, i go deeper) Sorry if it looks confusing. Just for curiosity, one of those intense tasks is processing a lot of readable documents (pdf, txt, and so on), but it cannot stop other tasks. -
Django: ForeignKey vs related_name
I'd like to ask if there is an important distinction between below two ways of expressing a ForeignKey relation, or is it just a "style" difference? In my opinion it is intuitive to first define a "sub-model" and then refer to it in your "main model", as below. version_1 class Track_1(models.Model): order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Album_1(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) tracks = models.ForeignKey(Track_1, on_delete=models.CASCADE) Meanwhile it is less intuitive to express it as below, using related_name, as below. version_2 class Album_2(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track_2(models.Model): album = models.ForeignKey(Album_2, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() Furthermore, I have seen most examples around Django Rest Framwork uses "version_2" to create linked serializers. Is this a style difference by the author or would actually become important when using DRF? class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] -
'URLPattern' object is not iterable after adding channels to my installed apps
I get the error message File "C:\Users\andri\AppData\Local\Programs\Python\Python39\lib\site-packages\channels\routing.py", line 122, in __init__ for route in self.routes: TypeError: 'URLPattern' object is not iterable when i add channels to my installed apps in settings.py. without channels it the urls and templates work as inteded. Do i have to append the URLRouter or am I missing a element? heres my routing.py: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path from tribe_chat.consumers import TribeChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( re_path('tribe_chat/<room_id>/', TribeChatConsumer), ) ) ), }) and heres my settings.py: INSTALLED_APPS = [ 'channels', 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'tribe_chat' ] ASGI_APPLICATION = 'MusicTribe.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } -
How to show all dictionary in template in Django?
I am working with IFC and I need to extract some data from a .ifc file to be displayed in the Django template. The template: {% extends 'base.html' %} {% block content %} <h2>upload</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document"> <button type="submit">Upload File</button> </form> <br> {{result}} {% endblock %} I've tried two methods: OpenIfcFile = ifcopenshell.open(filepath) #select the file BrowseIfcProducts = OpenIfcFile.by_type('IfcElement') #search for the attribute 'IfcElement' for eachproduct in BrowseIfcProducts: #add the .ifc searched data to dict 'context' with 'result' key context['result'] = [ eachproduct.is_a(), eachproduct.GlobalId, eachproduct.get_info()["type"], eachproduct.get_info().get("Name","error"), ] return render(request, 'upload.html', context) In this method, due the key 'result' doesn't change on each iteration, only the last item is stored and in my template i can't see all items. So, to fix this problem, I concatenate the result key to a iterator (i): i = 1 for eachproduct in BrowseIfcProducts: context['{} {}'.format('result', i)] = [ eachproduct.is_a(), eachproduct.GlobalId, eachproduct.get_info()["type"], eachproduct.get_info().get("Name","error"), ] i += 1 return render(request, 'upload.html', context) But, unfortunately, nothing is displayed in the template I'm stuck here, i don't know how can I show the data on template, can someone help me? -
How do I use proxy in Nextjs to send HttpOnly cookie to django on different domain?
I previously posted about not being able to send HttpOnly cookie from nextJS to django either from getServerSideProps or from useEffect here. I think the reason is that my django and Nextjs are running on different domains. So I need to have same domains for both back-end and front-end. Does it mean that requests from nextJS should go from 127.0.0.1:8000 instead of 127.0.0.1:3000? If yes, do I need to use proxy within Nextjs? Also, I have set-up django-cors-headers, does it still require proxy? -
How I can convert the `{'c_like': '99', 'count': 1}` to the colour like button and count the likes in Django
How I can convert this data to visible thing for example if I click on the like button increase the likes +1 and change the button to red if I hit it again thin decrease -1 and change the color my views def like_comment(request): id = request.POST.get('like_id') comment = Comment.objects.get(id=id) data = {} if request.POST.get('action') == 'add_like': account = request.user if comment.likes.filter(id=account.id).exists(): comment.likes.remove(account) c_like = False else: comment.likes.add(account) c_like = True data["c_like"] = id data["count"] = comment.likes.count() print(data) return JsonResponse(data) my template (Html) {% if not request.user in node.likes.all %} <button id="comlike" style="color: #aaaaaa;" onclick="addLikeToComment({{ node.id }})" class="remove-default-btn p-0 border-0 " type="submit" style="border: none; color: #aaaaaa;" > <svg width="0.9em" height="0.9em" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16" > <path d="M8 2.748l-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333 4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z"/> <span class="ml-1" id="span_like">{{ node.likes.all.count }}</span></svg> </button> {% else %} <button id="comlike" style="color: red;" onclick="addLikeToComment({{ node.id }})" class="remove-default-btn btn btn-dinger p-0 border-0 " type="submit" class="remove-default-btn like-btn{{ request.path }}" style="border: none; color: #aaaaaa;"> <svg width="0.9em" height="0.9em" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-heart" viewBox="0 0 16 16" … -
Working with user type does not work in Django
I'm trying to create a user type in Django with that idea the user have the first type he will be redirected to a template if he is another he will be redirected to another one this is my models.py class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False def is_paitent(self): if self.type_of_user == 'paitent': return True else: return False def is_reception(self): if self.type_of_user == 'reception': return True else: return False def is_temporary(self): if self.type_of_user == 'temporary': return True else: return False and this is my views.py @login_required def dashboard(request): if User.is_doctor: return render(request, 'user/dashboard.html', {'section': 'dashboard'}) else: return render(request, 'user/dashboard2.html', {'section': 'dashboard'}) but it always takes me to the dashboard .html only event if I change the user type -
Django proxy model with dynamic virtual fields
We store our data in a mixture of "real" model fields and fields which are defined and stored in a JSON-Structure. To simplify handling those structures with our model serializer and the DRF, we thought about implementing a proxy model which looks up the structure/data of the dynamic fields and adds those field to the proxy model class Classification(AbstractContent): """ classification model """ name = models.CharField( verbose_name=_('name'), max_length=255, null=False, blank=False, ) # for example we have like that in our structure #{'topEntry': {type:'bool',value:'false'}, 'addName': {type:'string, value: 'test} dynamic = models.JSONSchemaField(content_type=None, null=True) We now want to get a proxy model which consists of those real model fields (name in this example) + two additional fields 'topEntry' and 'addName'. It is no problem for us to add those fields in the proxy model with @property, but trying others ways the serializer would not recognize our fields. -
How to change user password not in a separated view?
I want to let user change his password and edit his profile on the same page. I scrolled through Internet and it turns out, that for some reason, everyone creates separated view for changing password. So, here's my Profile model if that makes sense: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to=user_directory_path_ppic) bio = models.TextField(max_length=255, blank=True, null=True) How do I let user change his password and edit profile on the same page? -
OperationalError at /admin/auctions/listings/ no such column: auctions_listings.category_id
I'm trying to create categories for my listings but it shows the above error. I also tried adding the id column manually but then it shows this error: AssertionError: Model auctions.Category can't have more than one auto-generated field. models.py from django.db import models from django.contrib.auth.models import AbstractUser,BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.conf import settings # Create your models here. class myUserManager(BaseUserManager): """ custom user model manager where email is unique indentifiers for authenticaton instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff= True')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email,password, **extra_fields) class myUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = myUserManager() def __str__(self): return f'{self.email}' class Category(models.Model): category = models.CharField(max_length=50, default="No Category") def __str__(self): return f'{self.category}' class Listings(models.Model): listing_name … -
Django channels: send and receive data from users in list
Hi I am very new to Django channels. I am trying to create a doctor consultation app. I am using drf to get details like speciality,date,patient info etc based on which I filter out the eligible doctors. I am trying to use channels to send request to each doctor in a list one at a time until he accepts/rejects or times out. Here is a flow chart My doubts I have the id list in my views.py how should I pass it to consumers.py? How do i send and get reponse serially? Is there a better way? -
Upload file using jQuery ajax with Django
I am learning ajax and JQuery with Django. I created a basic app to update the text field but now I added the file field. But unable to make it work. The is model class class TextModel(models.Model): text=models.CharField(max_length=200) file=models.FileField(upload_to='files') This is my template <div class='col-8 mt-5'> <form method='POST' id='formCreated' data-url="{% url 'home' %}" enctype="multipart/form-data"> <!-- data-url is used in ajax function --> {% csrf_token %} {{ form.as_p }} <button type="button" id="btn_submit">Upload</button> </form> </div> <div class='col-5 mt-5' id='resultid'> </div> Here is my views function def home(request): if request.method=='POST': form = TextForm(request.POST,request.FILES) if form.is_valid(): out=form.save() return JsonResponse({'text':model_to_dict(out)},status=200) else: return render(request,'home.html',{'form':form}) else: form = TextForm() return render(request,'home.html',{'form':form}) Here is my code in js file $(document).ready(function(){ $('#btn_submit').click(function() { var serializedData=$('#formCreated').serialize(); console.log(serializedData) $.ajax({ url:$("formCreated").data('url'), data:serializedData, type:'POST', success:function(response){ // reponse recieved from views recieved here and sent to div with resultid in home.html console.log(response) $('#resultid').append(response.text.text) // first text is key of response and second text is the text object } }) $('#formCreated')[0].reset(); }); }); This is the error I am getting file.js:16 Uncaught TypeError: Cannot read property 'text' of undefined at Object.success (file.js:16) at c (jquery.min.js:3) at Object.fireWith [as resolveWith] (jquery.min.js:3) at k (jquery.min.js:5) at XMLHttpRequest.r (jquery.min.js:5) -
File csv does not downloaded but instead open inside browser
I have two files that a user can download from my django app. The files have different formats xls and csv. The first one is downloaded as expected, but the problem is with csv, it is not downloaded, but opens inside the browser like a normal html. how can this be fixed? I think I need to change the title from text/html to file/csv. But i don't know how i can do it. -
Fields error messages like "This field is required" are not displayed
I am working on a eCRF using Django and do not use forms and views as usual In few words, forms are displayed using ajax and submit the form using ajax as well. View ajax_form return selected form. I have only one view create_or_update that test for existing form and submit data. All is working quite well. I have followed [this tutorial][1] to sumit forms using ajax but even if not valid forms are not submitted, fields errors messages are not displayed: unvalid field is highlighted in "red" and an help text "Please complete this field" (server-side validation?) is displayed. I use django-crispy for render. view.py # Ajax view to render form in patient view def ajax_form(request): if request.is_ajax() and request.method == "POST": # If form already exist, update form is displayed if already_exist(): form = InclusionForm(patient=patient, data=data or None, instance = obj) # Else, creating form is displayed else: form = InclusionForm(patient=patient) return JsonResponse({'html_inclusion': render_to_string('ecrf/inclusion.html',{'form': form,},request=request),},status=200) @json_view def create_or_update(request,pk): if Inclusion.objects.filter(pat = Patient.objects.get(pat_ide = pk).pat).exists(): obj = get_object_or_404(Inclusion, pat = Patient.objects.get(pat_ide = pk).pat) form = InclusionForm(patient = pk, data=request.POST or None, instance = obj) else: form = InclusionForm(patient = pk, data=request.POST or None) if form.is_valid(): form.save() return { 'success' … -
Django: getting image URL when saving in Models
In my Django app I upload an Image, resize it and save copies to another fileds. Everything works fine. What I want to do is save the URL of the original uploaded file to a CharField (to avoid n+1 lookups from the usual .url image attribute). As the file is not actually saved until "super" I can´t get the file url. Any clues on how can I achieve this? Thanks in advance! The model class ProductosBase(models.Model): foto_1_original = models.ImageField(upload_to='', default="", blank=True, null=True) foto_1 = models.ImageField(upload_to='', default="", blank=True, null=True) foto_1_M = models.ImageField(upload_to='', default="", blank=True, null=True) foto_1_L = models.ImageField(upload_to='', default="", blank=True, null=True) foto_1_url = models.CharField(max_length=750, help_text="max 30 char", blank=True, null=True) def __str__(self): return str(self.producto) def save(self, *args, **kwargs): if self.foto_1_original: pil_image_obj = Image.open(self.foto_1_original) if pil_image_obj.format == 'TIFF': new_name = str(self.foto_1_original.name).replace('.tiff', '.jpg') pil_image_obj = pil_image_obj.convert('RGB') elif pil_image_obj.format == 'PNG': new_name = str(self.foto_1_original.name).replace('.tiff', '.jpg') pil_image_obj = pil_image_obj.convert('RGB') else: new_name = str(self.foto_1_original.name) if pil_image_obj.mode == 'CMYK': pil_image_obj = pil_image_obj.convert('RGB') new_image = resizeimage.resize_width(pil_image_obj, 200) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = new_name.split('.')[0] + '_200.' + new_name.split('.')[1] self.foto_1_L.save(temp_name, content=ContentFile(new_image_io.getvalue()), save=False) new_image = resizeimage.resize_width(pil_image_obj, 400) new_image_io = BytesIO() new_image.save(new_image_io, format='JPEG') temp_name = new_name.split('.')[0] + '_400.' + new_name.split('.')[1] self.foto_1_M.save(temp_name, content=ContentFile(new_image_io.getvalue()), save=False) new_image_d = resizeimage.resize_width(pil_image_obj, 400) new_image_io_d = BytesIO() new_image_d.save(new_image_io_d, … -
Can't insert data, Django primary key doesn't have a default
In Django 3.0, I have a set of Models consisting of an abstract BaseData, a Model Data that extends it, and a Model of underlying data FKData that Data foreign-keys to: # models.py from django.db import models class BaseData(models.Model): class Meta: abstract = True class Data(BaseData): data = models.ForeignKey( FKData, on_delete=models.CASCADE, blank=True, null=True, default=None ) class FKData(models.Model): text = models.CharField( help_text='underlying data' ) The error occurs when I try to INSERT into Data. For example, mysql> INSERT INTO appname_data (data_id) SELECT data_id FROM appname_othertable ERROR 1364 (HY000): Field 'basedata_ptr_id' doesn't have a default value basedata_ptr_id is a primary key field that Data has due to being a subclass of BaseData: mysql> DESCRIBE appname_data; +-----------------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------+---------+------+-----+---------+-------+ | basedata_ptr_id | int(11) | NO | PRI | NULL | | | data_id | int(11) | YES | MUL | NULL | | +-----------------+---------+------+-----+---------+-------+ 2 rows in set (0.00 sec) The error sounds like it isn't being set to AUTO INCREMENT the way normal primary keys are? If I try filling the Data table using the Django shell, I get the same error but with a bigger stack trace that might … -
How to connect Django with Azure Cosmos DB
I want to connect Django with Azure Cosmos DB. Either with Core SQL Or Gremlin. Do we have any existing libraries we can use to achieve it? -
Django dropdown menu/form based on model entries
I have got created a drop down menu where I can show the values of a model data called "Items". However, I trying to change this into a Django form in order to be more flexible. However, I have some problems in understanding how to adapt this? Here is the relevant code: models.py class Items(models.Model): item_name = models.CharField(max_length=200) views.py def details(request): template = loader.get_template('news/details.html') items = Items.objects.all() context = {'items': items} return HttpResponse(template.render(context, request)) details.html <form method="POST" action = ""> {% csrf_token %} <select name = "wwww"> {% for n in prod %} <option value ="{{ n.product_name }}"} name ="val">{{ n.product_name }} </option> {% endfor %} </select> <input type="hidden" name="speichern1" value="1"/> </form> Maybe someone could help me out or point me to a help page for this? Thanks, Andi -
Forward ForeignKey querying in Django
Let's say I have the following two models: class Post(models.Model): ... class Keyword(models.Model): value = models.CharField(...) post = models.ForeignKey('posts.Post', related_name="keywords") Now lets say I want to return a list of all posts for a given keyword.value. I usually do this: keywords = Keyword.object.filter(value="something").values_list(id, flat=True)`. Posts.keywords.filter(id__in=keywords) To return a <QuerySet[]> of Posts. I'm not sure if I am missing something in the documentation, but can I return a QuerySet of Posts in one query and can I do it on the Keyword model? Something similar to a related name set ... ? -
urlshort.models.Linkurl.DoesNotExist: Linkurl matching query does not exist
I found a lot of SO solutions like that answer. But still getting stuck on matching query does not exist. The issue is the line url_details = Linkurl.objects.get(uuid=pk) My model.py is from django.db import models # Create your models here. class Linkurl(models.Model): link = models.CharField(max_length=10000, blank=False) uuid = models.CharField(max_length=10) def __str__(self): return self.link[:40]+" - "+self.uuid Views.py is from django.shortcuts import render, redirect import uuid from .models import Linkurl from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'urlshort/index.html') def create(request): if request.method == 'POST': link = request.POST['link'] uid = str(uuid.uuid4())[:5] new_url = Linkurl(link=link, uuid=uid) new_url.save() return HttpResponse(uid) def go(request, pk): url_details = Linkurl.objects.get(uuid=pk) return redirect(url_details.link) and urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('create', views.create, name='create'), path('<str:pk>', views.go, name='go') ] I found many solutions but didn't work for my issues and saying raise self.model.DoesNotExist( urlshort.models.Linkurl.DoesNotExist: Linkurl matching query does not exist. -
Django Validate Form As Per Database Entry ID
Hello Wonderful people, I have made a form in Django which has some serial numbers stored in Django-admin database. I am now creating another app and similar form, However I want is that the new Form should accept the serial number which is valid and checked as per the serial number got entered in the first form which is in app 1. I am pasting a bit of my code for you to understand it more clearly with some screenshots. <form method="POST" action="/reservation/home/"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Radio Serial Number</label> <input type="text" class="form-control" id="exampleFormControlInput1" name= "sno" placeholder="S/N123ABC123" required > </div> <button type="submit" class="btn btn-primary"> Submit </button> </form> views.py of new app. def reserve(request): if request.method == "POST": sno = request.POST.get('sno') date_req = request.POST.get('date_req') reserve = Reserve( sno=sno, date_req=date_req ) reserve.save() return render(request, 'home.html') models.py of new app. from django.db import models # Create your models here. class Reserve(models.Model): sno = models.CharField(max_length=100) date_req = models.DateField() def __str__(self): return self.sno I want it to accept the serial number which got input by another form and validate it. If the new serial number is not same as the database entry in previous form , It should display some error message that … -
(mismatching_state) CSRF Warning! State not equal in request and response
I know that it's duplicate question. I am getting same error. So please help me. Here my code crd = "path\\client_secret.json" scopes = "https://www.googleapis.com/auth/androidmanagement" current_url = request.get_full_path() parsed = urlparse.urlparse(current_url) state_get = parse_qs(parsed.query)['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(crd, scopes=scopes, state=state_get) flow.redirect_uri = "http://127.0.0.1:8000/google-class/oauth2callback/" print("flow.redirect_uri", flow.redirect_uri) authorization_response = request.get_full_path() print('authorization_response', authorization_response) flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials print("credentials", credentials) androidmanagement = build('androidmanagement', 'v1', credentials=credentials) print(androidmanagement) -
Errors when running Celery: AttributeError: '_thread._local' object has no attribute 'backend'
I'm using Celery with Django and RabbitMQ to scrape a website. Starting a Django project and RabbitMQ goes well, but when trying to start Celery, I get the following message: AttributeError: '_thread._local' object has no attribute 'backend' During handling of the above exception, another exception occurred: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'celery.backends.amqp' Here's my Celery config: from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_api.settings') app = Celery('django_api') app.conf.timezone = 'UTC' app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() and here are Celery variables in settings.py: CELERY_BROKER_URL = 'amqp://localhost:5672' CELERY_RESULT_BACKEND = 'amqp://localhost:5672' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' I'm running celery in pipenv with the following command celery -A django_barcode_api worker -B -l INFO Following this tutorial: https://github.com/mattdood/django_web_scraping_example/ Any ideas how can I resolve this error when running celery? -
The page is not displayed correctly in Django prodject, maybe because of uncorrect views
So, I did a Django project according to the Django textbook. And when I typed python manage.py runserver I saw this page: It's not what I wanted to see. There should be a list of latest questions, because I type it in index file( I think taht the problem is in views or in html files. polls/views.py: from django.http import HttpResponseRedirect from django.template import loader from django.shortcuts import get_object_or_404, render from django.shortcuts import redirect from django.shortcuts import render from django.http import Http404 from django.views import generic from django.utils import timezone from . models import Answer, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_answer = question.answer_set.get(pk=request.POST['answer']) except (KeyError, Answer.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a answer.", }) else: selected_answer.votes += 1 selected_answer.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) polls/index.html {% …