Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pd.read_sql() takes about 10 seconds to load a 200k row MS SQL Server table in python
My Django API reads a table (150k rows) and perform some operations using that data every time the API is executed. The table is indexed on Type, Ticker, and Date. Type has 2 Distinct values (varchar), Ticker has 30 Distinct values(varchar) and Date has 5040 Distinct values (Datetime). conn = pyodbc.connect(driver='{Driver name}', server='Server Name', database='Database Name', user='user name', password='password') sql = """ Select [Date],[Close],[Ticker],[Type] from [dbo].[Stocks_data]""" df = pd.read_sql(sql,conn) Is there any way to get the data from database in a few milli-seconds or save the table as cache (I don't know much about cache) in the djago application. We update that table daily (Closing prices of the stocks) -
Javascript won't work inside Django for loop form
I'm trying to refactor this code so with this loop I can avoid repetition and scale the code, but the javascript stops working as I put the django loop <ul class="navbar-nav"> <li class="nav-item"> <!-- class="active" --> <a class="nav-link" href="{% url 'stories' %}">{% trans "Stories" %}</a> </li> </ul> <ul class="nav navbar-nav ml-auto"> <li class="nav-item"> <a class='dropdown-toggle' data-toggle='dropdown' role='button' aria-expanded='false'>{% trans "Lingua" %}<span class='caret'></span></a> <ul class='dropdown-menu' role='menu'> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <li> <form name="languagePt" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="pt-br" /> <a href="javascript:document.languagePt.submit()"> <img width='64' height='64' src="{% static 'img/pt-br.png' %}" alt='pt-br'> </a> </form> </li> <form name="languageEn" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="en-gb" /> <a href="javascript:document.languageEn.submit()"> <img width='64' height='64' src="{% static 'img/en-gb.png' %}" alt='en-gb'> </a> </form> </li> {% endfor %} </ul> the code will be almost like that when done, if it's possible to use javascript inside the loop <ul class="navbar-nav"> <li class="nav-item"> <!-- class="active" --> <a class="nav-link" href="{% url 'stories' %}">{% trans "Stories" %}</a> </li> </ul> <ul class="nav navbar-nav ml-auto"> <li class="nav-item"> <a class='dropdown-toggle' … -
Can you use multithreading with Celery?
I'm trying to build an email scrapper, but the problem is that it is very slow to crawl websites one by one. I've been researching how to speed up this process and I came across multithreading, after looking deeper into it, I found that Django has Celery to do it, but I've been reading the docs and haven't found anything. So I have a couple questions: Is it possible to use Celery for multithreading, multiprocessing? How can it be done? With Celery already installed on Django Thank you! Any help would really appreciate it! -
how can I add multiple images of each student using django rest framework
I want to upload multiple images for each student using django rest framework. currently, Im only able to upload one image for each student, but I want to be able to upload multiple images for each student in uploads folder in a directory of their name. Im building a facial attendance recognition system and I need multiple images of each student. here is my models.py file. class Student(models.Model): Name=models.CharField(max_length=200) Enrollment_No=models.CharField(max_length=200) Registration_No=models.CharField(max_length=200) Semester=models.IntegerField() Year=models.CharField(max_length=200) Course_Name=models.CharField(max_length=200) Course_Code=models.CharField(max_length=200) registered_at= models.DateField(auto_now_add=True) def __str__(self): return self.Name class studentImage(models.Model): Name= models.CharField(max_length=200, default='no-name') Student= models.ForeignKey(Student, on_delete= models.CASCADE) image=models.ImageField(upload_to= 'uploads/') def __str__(self): return self.Name class serializers.py file class StudentSerializer(serializers.ModelSerializer): class Meta: model=Student fields="__all__" class studentImageSerializer(serializers.ModelSerializer): class Meta: model= studentImage fields="__all__" views.py file @api_view(['POST']) def studentCreate(request): serializer = StudentSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() else: print('Hello World') return Response(serializer.data) Please let me know what changes should I make to the code, what I should add in the views file to allow multiple images upload of student in uploads directory in a directory of student name -
Wagtail: How to link a model to an Orderable which links to another model
Lets say I have multiple models which require an address e.g. boxing clubs & boxing events. I have considered making the address an abstract and adding the panels everywhere I needed them but figured that creating its own table/model would be cleaner than the address fields being added to each model that needs them. Now, a boxing club has it's own timetable where it can specify on which day it's in session as well as a location should it be in a different club than usual. So, my attempt at a solution looks something like this. class BoxingClub(models.Model): name = models.CharField(max_length=30) panels = [ FieldPanel('name'), InlinePanel('club_timetable', heading='Timetable Information') ] class ClubTimetable(Orderable): _DAYS_OF_WEEK = ( (0, "Monday"), ... (6, "Sunday") ) attached_to = ParentalKey( 'club.BoxingClub', related_name='club_timetable') linked_location = models.ForeignKey( 'location.Address', on_delete=models.SET_NULL, related_name='location_address', null=True) weekday = models.IntegerField( 'Day of training session', choices=_DAYS_OF_WEEK) panels = [ FieldPanel('weekday'), InlinePanel('linked_location', help_text='Sessions location information.') ] class Address(models.Model): address_line_1 = models.CharField( max_length=30, help_text='First line of address.') address_line_2 = models.CharField( max_length=30, null=True, blank=True, help_text='Second line of address.') map_coord_lat = models.CharField( max_length=25, help_text='Comma separated latitude.' ) map_coord_lon = models.CharField( max_length=25, help_text='Comma separated longitude.' ) panels = [ FieldPanel('address_line_1'), FieldPanel('address_line_2'), FieldPanel('map_coord_lat'), FieldPanel('map_coord_lon'), ] This however, gives me the following error: … -
How to automaticaly get user name, who post comment? (I don't want to type name of user manually)
How to automaticaly get user name, who post comment? (I don't want to type name of user manuely) I don't want to be able to change it or to be seen. I tried to do it the same way I do for making new posts, but I guess it is a little more complicated... Here is the code: Views: from . models import Post, Comment from . forms import PostForm, CommentForm class add_comment(CreateView): model = Comment form_class = CommentForm template_name = 'add_comment.html' success_url = reverse_lazy('home') ordering = ['-id'] def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) urls: from . views import add_comment path('details/<int:pk>/comment/', add_comment.as_view(), name = 'add_comment'), models: from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() image = ResizedImageField(size=[480, 320], quality=100, upload_to='pictures', null=True, blank=True) video = models.FileField(upload_to='videos', null=True, blank=True) date = models.DateTimeField(default=datetime.now) def __str__(self): return f'{self.author}: {self.body}' class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date'] def __str__(self): return '%s - %s' % (self.name, self.post.body) forms: from . models import Post, Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } -
Bootstrap and MD Bootstrap Carousel not working in Django
So I am trying to add a simple MD Bootstrap carousel to a django template, however, it only loads the first image and the controls don't work. I followed this article https://mdbootstrap.com/articles/jquery/how-to-integrate-mdbootstrap-with-django/ on how to integrate MD Bootstrap but I have a feeling that some of the imports aren't quite working. I also made sure that other_banner_images is actually querying the images I want. I also tried replacing the MDB Carousel with a regular BS carousel and had the exact same issue. Any help would be greatly appreciated :) Here is the template in question home.html, which I modified from https://mdbootstrap.com/docs/standard/components/carousel/ <!-- Carousel wrapper --> <div id="carouselBasicExample" class="carousel slide carousel-fade" data-mdb-ride="carousel" > <!-- Indicators --> <ol class="carousel-indicators"> <li data-mdb-target="#carouselBasicExample" data-mdb-slide-to="0" class="active"></li> <li data-mdb-target="#carouselBasicExample" data-mdb-slide-to="1"></li> <li data-mdb-target="#carouselBasicExample" data-mdb-slide-to="2"></li> </ol> <!-- Inner --> <div class="carousel-inner"> <!-- Single item --> <div class="carousel-item active"> <img src="{{ default_banner_image.image.url }}" class="d-block w-100" alt="..." /> <div class="carousel-caption d-none d-md-block"> <h5>{{ default_banner_image.text }}</h5> <p>{{ default_banner_image.sub_text }}</p> </div> </div> {% for image in other_banner_images %} <!-- Single item --> <div class="carousel-item"> <img src="{{ image.image.url }}" class="d-block w-100" alt="..." /> <div class="carousel-caption d-none d-md-block"> <h5>{{ image.text }}</h5> <p>{{ image.sub_text }}</p> </div> </div> {% endfor %} </div> <!-- Inner --> <!-- … -
Django create form instance with two relations keys
First of all, I want to make it clear that I start with Django. I've searched a lot on this subject here, but I haven't found the right answer. Here is my problem, I want to create a form (not in the admin) where users of the site can fill in their profiles and addresses What I'm trying to do is fill out two templates with one submission for the user. So far I have managed to save the profile but I can't fill in the address and link it to the profile. Here is my code, hoping you can help me. Thanks in advance my userprofile model class UserProfile(models.Model): user = models.OneToOneField(CoreUser, on_delete=models.CASCADE, verbose_name="Email") address = models.ForeignKey(Address, on_delete=models.PROTECT,related_name='useraddress') first_name = models.CharField(max_length=50, verbose_name="First name user", null=True) last_name = models.CharField(max_length=50, verbose_name="Last name", null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) birthdate = models.CharField(max_length=200, null=True) profile_picture = models.ImageField(default='default.jpg', upload_to=get_path) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) CoreUser.userprofile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) UserProfile.address = property(lambda u: Address.objects.get_or_create(useraddress=u)[0]) I think I must have made a big mistake in my lamda. UserProfile.address = property(lambda u: Address.objects.get_or_create(useraddress=u)[0]) my address model class Address(models.Model): street_number = models.FloatField(max_length=5, blank=True, null=True) street_line_1 = models.CharField(max_length=150, blank=True, null=True) street_line_2 = models.CharField(max_length=150, blank=True, … -
Sending canvas object with restfull api in django
I am using django as my backend and I am using restful api to communicate with react js frontend. I have created a pdf invoice with canvas and I was able to send it via mail system of django. But I also want to show the pdf on web page. So I need to send it to front end via api url. I tried to send it as response but I got the error: Object of type Canvas is not JSON serializable The code that I wrote to send pdf: return Response(c, status=status.HTTP_200_OK) c stands for the canvas object which is a pdf Is there a solution of this? Or how do I send the pdf to the front end. Thank you -
Can django channels communicate with Python web sockets instead of browsers? (Client is not html or javascript)
The server is configured as a channel on django. Will this server be able to connect to client.py implemented as Python's websockets Package or websocket-client Package? When I test it, there is an error as below. test python websocket-client source image error image -
How can I differentiate between two url requests from different HTML pages but with the same namespace in views.py?
I am creating a simple eBay like e-commerce website to get introduced with django. For removing an item from the watchlist, I placed two same links in two different HTML files, that is, I can either remove the item from the watchlist.html page or either from the item's page which was saved as listing.html. The url for both the pages look like this: <a href="{% url 'removeFromWatchlist' item.id %}"> Remove from watchlist </a> Now, in my views.py, I want to render different pages on the basis of the request. For example, if someone clicked Remove from watchlist from listing.html then the link should redirect again to listing.html and same goes for the watchlist.html. I tried using request.resolver_match.view_name but this gave me 'removeFromWatchlist' as the url namespace for both of these request is same. Is there any way I can render two different HTML pages based on the origin of the url request? Also, this is my second question here so apologies for incorrect or bad formatting. -
VSCode + remote dev + django: avoiding forwarding ports
I'm using VSCode remote development to run and debug a django project inside a Docker container. In my devcontainer.json I forwarded the port 8000 "forwardPorts": [8000], and this is my launch.json { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/myapp/manage.py", "args": [ "runserver", "0.0.0.0:8000" ], "django": true } ] } When I start the debug with such a configuration, I see 4 ports forwarded: port 8000 and other 3 rendom high ports 8000 -> localhost:8000 (the only one I'd expect to see) 34075 -> 127.0.0.1:34075 37301 -> 127.0.0.1:37301 42129 -> 127.0.0.1:42129 I'm wondering the reason why those three ports are forwarded and how I can avoid it. -
Add link on a web page to export tables2 data in Django
I'm trying to include a link on a webpage to download a tables2 table to csv. I got the commented out piece below from the documentation, and I think it might just need a simple tweak to get it to work with my code. Any thoughts? views.py class PlatListView(SingleTableMixin, FilterView): model = Plat template_name = 'blog/filtertable.html' filter_class = PlatFilter def get_context_data(self, **kwargs): context = super(PlatListView, self).get_context_data(**kwargs) query = Phase.objects.all().select_related('plat','plat__community') f = PlatFilter(self.request.GET, queryset=query) t = PlatTable(data = f.qs) RequestConfig(self.request, paginate=False).configure(t) context['filter'] = f context['table'] = t ''' export_format = self.request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, query) return exporter.response("query.{}".format(export_format)) ''' return context filtertable.html {% extends "blog/base.html" %} {% block content %} {% load querystring from django_tables2 %} <div style = 'padding-top: 24px'> <a href="{% querystring '_export'='csv' %}">Download CSV</a> </div> {% load render_table from django_tables2 %} {% load bootstrap4 %} {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% render_table table 'django_tables2/bootstrap4.html' %} {% endblock content %} -
Highcharts range selector buttons and input filter not working
I've created a chart using Highcharts in Django but the range selector buttons do not work and input range starts from 1970 instead of my first date. I guess it's something to do with dates formatting but I can't figure it out ... I'm reading a JSON file content with dates entry formatted in milliseconds, ex: 1527465600000. The chart is displayed just fine, the range selector at the bottom of the chart works just fine as well, and dates on the X-axis are nicely formatted as expected. What I want is for the range selector buttons to work, and for the range selector input filter to start from my first date instead of starting from the 1st of Jan 1970. Here's my highcharts code: {% block javascripts %} {% load static %} <script src="https://code.highcharts.com/stock/highstock.js"></script> <script> fetch("{% static 'highcharts_1.json' %}") .then(response => response.json()) .then(mydata => { console.log(mydata.sample1,mydata.dates) Highcharts.chart('mychart_1', { chart: { zoomType: 'x', type: 'spline', }, xAxis: { type: 'category', categories: mydata.dates, labels:{ formatter: function() { return Highcharts.dateFormat('%d %b %Y', this.value); }, align: 'right', rotation: -90, }, }, yAxis: { min: 0, max: 1, tickInterval: 0.1, title: { text: 'Score' } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, … -
How do I get a perticular subcategory that has the same name under the other category in Django?
I have a shop-application and theres categories and subcategories, I have 3 categories and under each one of those there's a subcategory called Other and when I click on the url for it I get this error: MultipleObjectsReturned at /categories/subcategory/Other, get() returned more than one SubCategory -- it returned 3! I do realise that using filter is not an option since it would return 3 values and a url cant accept a queryset as an argument, could I perhaps somehow also use the subcategorys category title` to filter the query or do you have any other ideas? Here is the code: urls.py path('subcategory/<str:title>/', views.subcategory, name='subcategory'), views.py def subcategory(request, title): subcategory = SubCategory.objects.get(title=title) products = Product.objects.filter(subcategory=subcategory) return render(request, 'subcategory.html', {'subcategory': subcategory, 'products': products}) -
Separating Django REST back from Front end
This is a bit of a different question. I've tried researching the information for a few hours now and I can't seem to find what I am looking for. I have a Django REST backend that I set up. Its very simple REST API that has one Model Model.py from django.db import models # Create your models here. class Hero(models.Model): name = models.CharField(max_length=60) alias = models.CharField(max_length=60) def __str__(self): return self.name I'm able to post to via the REST api interface see image below I'd like to have the Django server running in the background while I create a front end whose files (index.html, main.css, app.js ect....) are separate from the django project. I would then use Axios to GET, POST data to the database using the following url http://127.0.0.1:8000/api/heroes/ Below is the code from my front end import axios from "axios"; export default class SuperHero { constructor() { this.superHeroForm = document.querySelector("#superHeroForm"); this.events(); } events() { this.superHeroForm.addEventListener("submit", e => this.onSubmit(e)); } onSubmit(e) { e.preventDefault(); console.log("onSubmit ran"); this.name = document.querySelector("#name").value; this.alias = document.querySelector("#alias").value; axios .post("http://127.0.0.1:8000/api/heroes/", { name: this.name, alias: this.alias }) .then(res => { console.log(res); }) .catch(e => { console.log(e); }); } } However I am getting a CROS error Access to … -
How to index into a django model's attribute?
I am making a blog and have a model for an article: class Article(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=120) content = models.TextField(db_index=True) committee = models.CharField(max_length=50) likes = models.IntegerField(default=0) I am working on a method of truncating posts and need to access the first few characters of the content attribute. I tried {{article.content[40]}} (article has been passed in as context in my view function) but that threw this error: Could not parse the remainder: '[0:40]' from 'article.content[0:40]' Does anyone know how to index into an attribute like this? Thanks! -
Copied and modified Django project stills show old templates
I copied and pasted a project developed with Django to modify it. However, after modifying one of the templates a little (the home.html), no modification appears. Is it because this project is not original? Do I have to recreate it from the beginning? For example, I changed the name of the template "home.html" to "homes.html". Then the first one should not be called and all that should result in an error. But as you can see there is no error and the home.html continues to be called Even after following this answer about renaming a Django project, I can't see my modifications being taken into account. -
Starting a django project with pipenv
I was trying to make a django project so I changed the directory to the specific folder and installed django there, but after running 'pipenv shell' someting weird happened. instead of lunching the virtual environment in the directory it jumped to other directory. how can I fix it? here is the picture -
django retrieving all objects from one to many model relationship in shell
how can I get all tasks that are inside one board? (every user can create a board and inside that board the user can create tasks) I've tried "Board.objects.get(pk=1).title.title" but that doesn't seem to work. (code: https://pastebin.pl/view/a479e227) -
Django Form Not Adding to SQLite3 Database
I have the following Django form that is purposed to create a new item in my database. It is returning a 'false-positive' in that it shows a green 'Done' after I hit submit but the record is not actually added to the database. Any ideas what is causing this? html <form method="POST"> {% csrf_token %} {{form}} <div style="color:green">{{info}}</div> <div style="color:red">{{error}}</div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> views.py def creator(request): if request.method == "POST": form = CommunicationsForm(request.POST) if form.is_valid(): form.save() return render(request,'polls/creation.html',{"form":CommunicationsForm,"info":"Done"}) else: return render(request,'polls/creation.html',{"form":CommunicationsForm}) forms.py class CommunicationsForm(forms.ModelForm): class Meta: model = Communications fields = "__all__" widgets = { 'project':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter your Project Name'}), 'title':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter a short Title'}), 'intent':forms.Textarea(attrs={'class': 'form-control','placeholder':'Describe the intent and desired outcome of the communication'}), 'date':forms.TextInput(attrs={'class': 'form-control','placeholder':'Select a Date'}), 'channel':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Channel'}), 'content_type':forms.Select(attrs={'class': 'form-control','placeholder':'Select a Content Type'}), 'audience':forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter the Audience(s)'}), 'status':forms.Select(attrs={'class': 'form-control','placeholder':'Select the Status'}), } models.py class Communications(models.Model): project = models.CharField(max_length=200) title = models.CharField(max_length=200) intent = models.CharField(max_length=200) date = models.CharField(max_length=200) channel = models.CharField(max_length=200) content_type = models.CharField(max_length=200) audience = models.CharField(max_length=200) status = models.CharField(max_length=200) def __str__(self): return self.communication -
Django - Create User with Additional Profile Fields
I've got a view where I collect user data and save it to the backend. def register(request): if request.method == 'POST': form = UserSignUpForm(request.POST) if form.is_valid(): form.save() return redirect('additional_info') else: form = UserSignUpForm() return render(request, 'users/signup.html', {'form': form}) Once this is complete, I redirect the user to another page where they can provide additional info in another form for their profile like their dob, profile pic etc. This uses the following code for the view: def additionalInfo(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.save() return redirect('app-home') else: form = ProfileForm() return render(request, 'users/addInfo.html', {'form': form}) The problem is when I try to save the second form I get the exception: NOT NULL constraint failed: users_profile.user_id I'm guessing this is because I have this defined in my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) meaning I need to supply the user for which I want to create this profile. How do I obtain the info of the user who was just registered using the register view and make it available in the additionalInfo view? -
django single app multiple dbs: same tables get created in all dbs
I am test-developing a django project with a single app (app_name) where I want to have 2 models (say: model_A and model_B), with their instances stored in separate DBs (say: DB_A.sqlite3, DB_B.sqlite3). I also have third DB (DB_users.sqlite3) for storing anything related to auth, sessions etc. I am trying to implement multiple dbs as per django documentation, with database routing etc., but I noticed at migrations that in each of those 3 DBs irrelevant tables get created for both models. For example, DB_A would have my_app_model_A as well as my_app_model_B table created. But the thing is my_app_model_B should only be stored in DB_B. What can be the reason for this / how to ensure that only relevant tables get created in correct DBs? -
AttributeError: type object 'EmailCrawler' has no attribute '__annotations__' in Celery
A very quick question. I'm trying to install Celery. The installation proceeded correctly, because when I run the Celery event, it runs correctly, although I'm trying to put the @shared_task method in a Email Crawler so that it can go faster. But the following error jumps out whenever I try to set the @shared_task: Error: C:\Users\user\Desktop\leadfinder>celery -A leadfinder worker -l info -P eventlet Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\user\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\user\AppData\Local\Programs\Python\Python39\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\__main__.py", line 15, in main sys.exit(_main()) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\bin\celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 829, in __call__ return self.main(*args, **kwargs) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 782, in main rv = self.invoke(ctx) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\core.py", line 610, in invoke return callback(*args, **kwargs) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\click\decorators.py", line 21, in new_func return f(get_current_context(), *args, **kwargs) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\bin\base.py", line 132, in caller return f(ctx, *args, **kwargs) File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\bin\worker.py", line 320, in worker worker = app.Worker( File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\worker\worker.py", line 94, in __init__ self.app.loader.init_worker() File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\loaders\base.py", line 111, in init_worker self.import_default_modules() File "c:\users\user\appdata\local\programs\python\python39\lib\site-packages\celery\loaders\base.py", line 105, in import_default_modules … -
How to send email and get model object in celery task?
If I remove the line object = MyModel.objects.get(pk=pk) it works as I excepted. But After trying to get the object in my task I got this error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I want to get the model object in my celery task while sending email for the purpose of context. tasks.py @shared_task def send_email(subject, body, from_email, to_email, pk): print(pk, subject, from_email) object = MyModel.objects.get(pk=pk) if object: context = {'object':object} else: context = {} email = EmailMultiAlternatives(subject, body, from_email, [to_email]) email.content_subtype = 'html' email.mixed_subtype = 'related' pdf = render_to_pdf( 'invoice.html', context=context ) email.attach('invoice.pdf',pdf) email.send() views send_email.delay(sub, body, from_email, user.email, obj.pk)