Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
allowedhosts=[] using Django and Apache2
I have a Django project and I am using Apache2. My settings.py file looks like this: DEBUG = False ALLOWED_HOSTS = ['localhost', '165.232.125.35', '.meesuis.org', 'www.meesuis.org'] When I type the 165.232.125.35 the site comes up fine. But when I type the actual website name it doesn't work. Can someone please confirm that I have the settings.py file set up correctly so that I will know for sure the problem is somewhere else? Thank you. -
Reverse for 'update_task' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P<update>[^/]+)/$']
I am building a small CRUD project and stuck on a very basic thing which is an update. First I found it on stack overflow, google and Facebook as well but couldn't be able to find the solution so finally posting my problem here will all code. views.py: from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect from .models import Task from .forms import TaskForm def tasks(request): task = Task.objects.all() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = TaskForm() context = { 'forms': form, 'tasks': task } return render(request, 'task/task.html', context) def update_task(request, update): task = Task.objects.get(id=update) form = TaskForm(instance=task) if request.method == 'POST': form = TaskForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') context = { 'form': form } return render(request, 'task/update_task.html', context) urls.py: from django.urls import path from .views import tasks, update_task urlpatterns = [ path('', tasks, name='tasks'), path('update/<str:update>/', update_task, name='update_task'), ] I am facing a problem in this section of update_task.html. my update_task.html: <form action="{% url 'update_task' form.id %}" method="POST"> {% csrf_token %} {{ form }} </form> <input type="submit" value="Update"> tasks.html: <!DOCTYPE HTML> {% load static %} {% load crispy_forms_tags %} <html lang="en"> <head> <meta charset="UTF-8"> <title>ToDo App</title> <link rel="stylesheet" href="{% static 'css/mystyles.css' … -
Django projects fail on Ubuntu 20.04
I just upgraded Ubuntu from 18.04 to 20.04, and ALL my Django projects (tens of them) were not working. One of the problem related to psycopg2 when executing pip: For example, there is "psycopg2==2.7.3.1" in my "requirements.txt" file, and running "pip install -r requirements.txt" resulted in errors when building wheel for psycopg2. Change "psycopg2==2.7.3.1" to ""psycopg2-binary" solved the problem. So, is such change necessary for all projects running on Ubuntu 20.04? Other error examples from various projects when running server: RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? SyntaxError: Generator expression must be parenthesized (widgets.py, line 151) AssertionError: SRE module mismatch ModuleNotFoundError: No module named 'decimal' ... etc. How to I fix these problems? I've been in a headache for weeks. -
How to customize response message in ModelViewSet
I will send the request in post format using ModelViewSet and I will customize its response message. So I turned the response back on the perform_create method as shown in the following code, but it doesn't work as I want. class CreateReadPostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() pagination_class = LargeResultsSetPagination def perform_create (self, serializer) : serializer.save(author=self.request.user) return Response({'success': '게시물이 저장 되었습니다.'}, status=201) # it's not work How can I make this work normally? Thank in advance. -
Is there easier way to use bulk_create() with many query to instance create items
I don't have basic programming at all and just learned python and Django a few months ago, due to an urgent need I decided to create my own program to support my department and team After the program is running, I want to make it easier for the user and after I look around it is recommended to use bulk_create and ajax JavaScript, definitely not using JavaScript. After looking for ways to use bulk_create, I find it inefficient like: instance = get_object_or_404(Audit, id=766) item1 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=1) item2 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=2) item3 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=3) item4 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=4) item5 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=5) item6 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=6) item7 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=7) item8 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=8) item9 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=9) item10 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=10) item11 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=11) item12 = get_object_or_404(Item.objects.filter(aspek=instance.aspek_audit).filter(active=True),id=12) audit_mie = [ AuditItem(audit=instance,item=item1,kategori=item1.kategori.kategori), AuditItem(audit=instance,item=item2,kategori=item2.kategori.kategori), AuditItem(audit=instance,item=item3,kategori=item3.kategori.kategori), AuditItem(audit=instance,item=item4,kategori=item4.kategori.kategori), AuditItem(audit=instance,item=item5,kategori=item5.kategori.kategori), AuditItem(audit=instance,item=item6,kategori=item6.kategori.kategori), AuditItem(audit=instance,item=item7,kategori=item7.kategori.kategori), AuditItem(audit=instance,item=item8,kategori=item8.kategori.kategori), AuditItem(audit=instance,item=item9,kategori=item9.kategori.kategori), AuditItem(audit=instance,item=item10,kategori=item10.kategori.kategori), AuditItem(audit=instance,item=item11,kategori=item11.kategori.kategori), AuditItem(audit=instance,item=item12,kategori=item12.kategori.kategori), ] AuditItem.objects.bulk_create(audit_mie) is there an easier way besides the method above? if not, then I stick with it, by creating objects in each item id which is approximately 130 (currently) and I will group it into 8 (currently) bulk_create() method. I am stuck here, if anyone can help this to make it easier, I am very, very Thank you -
Recommendations for possible feed algorithms?
I am currently tasked with creating an algorithm that delivers a continuous flow of posts to the end user via an endless scrolling mechanism. There are some obvious answers (e.i. display posts via date created and show them chronologically). However, this has some major drawbacks (e.i. depending on the timezone, some posts will get burried while others get all the attention arbitrarily). What are some alternative ways (with coding examples) to implement an algorithmic feed? Any resources/blog posts would be greatly appreciated. -
ModelAdmin - how to inline model to another model view using intermediate relation table using foreign key
I want to make able to edit (add or delete) film work persons (actors, writers, director). I have the following models: class FilmWork(models.Model): id = models.UUIDField(primary_key=True, db_column='id', default=uuid.uuid4) title = models.CharField(_('название'), max_length=255) class Meta: db_table = 'film_work' managed = False class Person(models.Model): id = models.UUIDField(primary_key=True, db_column='id', default=uuid.uuid4) full_name = models.TextField(_('полное имя'), max_length=255) class Meta: db_table = 'person' managed = False class FilmWorkPerson(models.Model): id = models.UUIDField(primary_key=True, db_column='id', default=uuid.uuid4) film_work = models.ForeignKey(FilmWork, models.DO_NOTHING, blank=True, null=True, related_name='film_work_person') person = models.ForeignKey(Person, models.DO_NOTHING, blank=True, null=True, related_name='person') role = models.CharField(_('роль'), max_length=50, choices=PersonRole.choices) class Meta: db_table = 'film_work_person' unique_together = (('film_work', 'person', 'role'),) managed = False Now I don't know how to show 'full_name' and 'role' fields on the FilmWorkAdmin(admin.ModelAdmin) - I found that Inline could help, but since I have intermediate table FilmWorkPerson which has ForeignKey field pointing to FilmWork, I can display 'role', but 'full_name' seems unaccessible in any way. Since it is not ManyToMany but ForeignKey I can not use 'through' I can't use fields lookup like 'person__full_name' since it is available in QuerySets filters only(?) I can not directly inline Person from FilmWorkAdmin since there are no direct connection between FilmWork and Person (did I miss some reverse lookup tool?) I don't believe … -
Tensorflow - ImportError: DLL load failed while importing _pywrap_tensorflow_internal
I have built a website using django and whenever I try to run my manage.py, I get the below error. I don't know what's wrong there and what am I missing Traceback (most recent call last): File "C:\venvs\mazroo3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 64, in <module> from tensorflow.python._pywrap_tensorflow_internal import * ImportError: DLL load failed while importing _pywrap_tensorflow_internal: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\venvs\mazroo3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\venvs\mazroo3\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\venvs\mazroo3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\venvs\mazroo3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\venvs\mazroo3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\khubi\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\khubi\sizeit\products\models.py", line 8, in <module> from predictionAPI.main import mlAPIforProduct File "C:\Users\khubi\sizeit\predictionAPI\main.py", line 3, in <module> import tensorflow as tf File "C:\venvs\mazroo3\lib\site-packages\tensorflow\__init__.py", … -
Exception in thread django-main-thread - error
I ran the server but somehow there happened to be a lot of errors - I can't understand the errors plz help I changed the design and started to use templates - html & css changed url to go to html file error code : Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 399, in check for pattern in self.url_patterns: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) . . . url(r'^', include('main.urls')), #localhost:8000으로 요청이 들어오면 main.urls로 전달 NameError: name 'url' is not … -
How can I serve a stand-alone static app through Django
We're using django for authentication, user management, site content etc, but we have a JS tool that needs to be behind django auth as well. The tool is an html page that pulls in a couple dozen static files through relative paths in the html page (src="./someJSfile.js"). The problem is I can't figure out how to serve the html file through django but keep the relative paths intact. I can create an apache alias to that directory so that the relative paths are intact, but then the html is served through apache and bypasses auth. I would like to be able to have the html file served through a django view so that auth works, and also keep the static files in the same directory. Is there some apache magic where I can have the html served through django but have the static served through apache using an alias, while keeping the html and static in the same directory? Thanks in advance -
django, typeerror: missing 1 required positional argument
models.py: class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(DoctorList): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() testhospital = DoctorList.objects.filter().values('h_code') if not last_doctor_code: return 'd' + '001' d_code = last_doctor_code.d_code doctor_int = int(d_code[3:7]) new_doctor_int = doctor_int + 1 new_d_code = 'd' + str(testhospital) + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) error code: Got a `TypeError` when calling `DoctorList.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `DoctorList.objects.create()`. You may need to make the field read-only, or override the DoctorListSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\rest_framework\serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\query.py", line 445, in create obj = self.model(**kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\base.py", line 475, in __init__ val = field.get_default() File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\fields\__init__.py", line 831, in get_default return self._get_default() TypeError: doctor_code_create() missing 1 required positional argument: 'DoctorList' I want to use h_code that exists in class DoctorList (models.Model) by putting it in doctor_code_create. I think it's right to use it like this, but I don't know what went wrong. Do I … -
Persistent "[Errno 61] Connection refused" error in Django
in my Django project, I am running these commands on shell: >>> from django.core.mail import send_mail >>> send_mail('Django mail', 'This e-mail was sent with Django.', 'my@email.com' ['out@email.com'], fail_silently=False) I keep receiving this error: ConnectionRefusedError: [Errno 61] Connection refused This is my current settings.py: import os import smtpd from pathlib import Path ... EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my@email.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True The strange thing is that I still receive the same error even when I add this code to write emails to console instead: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I have tried all the tips I could find including, activating less secure apps in Gmail, acquiring a Gmail app password, and even tried using Mailjet with django-anymail. Nothing made a difference, still received the same error message when I run that command in shell. I'm running Python 3.6 and Django 3.1.2 -
Deploy Web Application Nuxtjs/Django/PostgreSQL
Right now I'm developing a website base on Nuxt as the Frontend and Django as the backend with a PostgreSQL database, I'm a little new to this field but I'm not sure how exactly to deploy and host my app, I've been looking at AWS Services to do it, like using Lightsail or just deploy everything on an ES2 instance to save money instead of deploying each element on a different server, the problem with the last option is that it wont be able to scale, in case in the future the visits to the site increase. I really appreciate some recommendation or orientation about how I could do it this easy, cheap and scalable. -
How to pass multi optional URL parameters in django?
How to pass multi optional URL parameters? For example I want pass 2 params: my_color and my_year, but they are optional, so may be none of them will be passed, may be both, or may be only one. Currently in urls.py I have : urlpatterns = [ re_path(r'^products/(?P<my_color>.*)/(?P<my_year>.*)$', some_view), ] This obviously is not correct and works only if both of them are passed. What would be correct solution? P.S. I found answers when only one optional parameter needs to be pass, but not figured out how to do same for few parameters. Also it seems "multiple-routes option" is not solution in this case ? -
Passing data from Django views to vue instance as JSON object
I have the following Django view method, being used to send information over to some Vue.js frontend code in details.html. I am basically wondering how do I send over the data to the vue template. How do I do JSON dumps? I think that is what I am messing up here. def works(request): heading_info = Heading.objects.order_by('-name')[:1] welcome_info = Welcome.objects.order_by('-title')[:1] skills_info = Skill.objects.order_by('position')[:5] projects_info = Project.objects.order_by('name')[:10] items = [] items.append({'heading_info':heading_info, 'welcome_info':welcome_info, 'path':path, 'path2':path2, 'skills_info':skills_info,'projects_info':projects_info}) # context = {} # context["items_json"] = json.dumps(items) context = {'heading_info':heading_info, 'welcome_info':welcome_info, 'path':path, 'path2':path2, 'skills_info':skills_info,'projects_info':projects_info} return render(request, 'home/details.html', context) And here is my html where I am trying to access this data. <script type='text/javascript'> var data = {{ projects_info|safe }}; </script> <div id="app"> [[projects_info_vue]] {% comment %} #Passing array as vue data. This gets rendered as QuerySet. How do I access these value in Vue. {% endcomment %} <div class="row"> {% for project in projects_info %} {% comment %} #Here is the array being rednered in Django. This array gets rendered as a QuerySet in Vue. {% endcomment %} <div class="col"> {{project.name}} </div> {% endfor %} </div> </div> <script> var app = new Vue({ delimiters: ["[[", "]]"], el: '#app', data: { projects_info_vue: '{{projects_info}}', }, }); </script> -
In django serializer response, how to get rid of absolute path (media_url prefix) for FileField?
I have used a models.FileField() in my model and I have created a simple ModelSerializer and CreateAPIView for it. As I am using AWS S3, when posting a file, I receive Json response that includes MEDIA_URL as prefix of filename i.e.: { "id": 32, "file": "https://bucket.digitaloceanspaces.com/products/capture_a50407758a6e.png" } What i would like to achieve instead is to either keep only a file name: { "id": 32, "file": "capture_a50407758a6e.png" } or to be able to change the prefix to some other: { "id": 32, "file": "https://google.com/capture_a50407758a6e.png" } The change should only be visible in Json response and and the database entry. The S3 details should be still sourced as they are from settings.py. Hope it makes sense. Let me know if anyone has any idea as I'm only able to find solution for providing full/absolute path. Thanks -
How to add images to individual model boxes?
So the problem am trying solve is how can I add images to separate model boxes? For example if I were to press on the Toyota Tacoma I would only see pictures of Toyota Tacoma and if I pressed on the Ford F-150 I would only see pictures of the Ford F-150. The closest I have gotten was getting the pictures to show up in the bottom of the model box but not in a separate one. function handleShowPopUp(e) { e.preventDefault() console.log(e) setSelectedPopUp(e.target.id) setShowPopUp(true) } const ref = useRef(null); useEffect(() => { function handleClickOutside(event) { if (ref.current && !ref.current.contains(event.target)) { setSelectedPopUp("") setShowPopUp(false); } } // Bind the event listener document.addEventListener("mousedown", handleClickOutside); return () => { // Unbind the event listener on clean up document.removeEventListener("mousedown", handleClickOutside); }; }, [ref]); const popUp = ( <div className="pop-up-wrapper"> <div className="pop-up-body" ref={ref}> <img src ={FordI}className="fordI" /> <img src ={FordI2}className="fordI2" /> <img src ={FordI3}className="fordI3" ></img> </div> </div> ) function chooseImage () { if (selectedPopUp === "toyotaTruck") { return(<img src={"toyota_truck"}></img>) } else if (selectedPopUp === "ford") { return(<img src={"ford"}></img>) } else if (selectedPopUp === "dodge") { return(<img src={"dodge"}></img>) } } const truckMenu = () => { return (<div><h1>Truck list - Ford F-150 Raptor</h1><img onClick={(e)=>handleShowPopUp(e)} id="Ford F-150 Raptor … -
Django: Creating multiple children at once on 1 parent
I'm having an issue passing several children OrderItem, a collection, when creating an Order parent instance. Although there a one to many relationship between Order and OrderItem models, I can't pass a list of children to the parent. What am I missing or doing wrong? Thanks for your responses! Here is an example of the request I try to make on this endpoint /api/orders/: { "bar_id": 2, "order_items":[ { "ref_id": 3 }, { "ref_id": 2 }, { "ref_id": 1 } ] } The error is as: { "order_items": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } } Here is my parent OrderModel: from django.db import models from .model_bar import * class Order(models.Model): bar_id = models.ForeignKey(Bar, null=True, on_delete=models.CASCADE, related_name='orders') Here is my child OrderItemModel: from django.db import models from .model_order import * from .model_reference import * class OrderItem(models.Model): order_id = models.ForeignKey(Order, null=True, on_delete=models.CASCADE, related_name='order_items') ref_id = models.ForeignKey(Reference, null=True, on_delete=models.CASCADE, related_name='order_items') UPDATE: Here is the OrderViewSet: from rest_framework import viewsets from ..models.model_order import Order from ..serializers.serializers_order import * from rest_framework import permissions class OrderViewSet(viewsets.ModelViewSet): """ Order ViewSet calling various serializers depending on request type (GET, PUT etc.) """ queryset = Order.objects.order_by('id').reverse() # mapping serializer into the action … -
What is the better way to impleent sub menu in Django?
I want to make a page with a dynamically added list of children. Each child has its own list of events. An example is attached. I have a list of children and events. How to combine them? I tried to make tabs or a second menu. I mostly focused on the template. But have no idea how to make it work. I feel it should be done through views. Please share any idea in which direction to go. -
Celery - Received unregistered task of type 'core.tasks.scrape_dev_to'
Trying to get a celery-based scraper up and running. The celery worker seems to function on its own, but when I also run the celery beat server, the worker gives me this keyerror. File "c:\users\myusername\.virtualenvs\django-news-scraper-dbqk-dk5\lib\site-packages\celery\worker\consumer\consumer.py", line 555, in on_task_received strategy = strategies[type_] KeyError: 'core.tasks.scrape_dev_to' [2020-10-04 16:51:41,231: ERROR/MainProcess] Received unregistered task of type 'core.tasks.scrape_dev_to'. The message has been ignored and discarded. I've been through many similar answers on stackoverflow, but none solved my problem. I'll list things I tried at the end. Project structure: core -tasks newsscraper -celery.py -settings.py tasks: import time from newsscraper.celery import shared_task, task from .scrapers import scrape @task def scrape_dev_to(): URL = "https://dev.to/search?q=django" scrape(URL) return settings.py: INSTALLED_APPS = [ 'django.contrib.admin', ... 'django_celery_beat', 'core', ] ... # I Added this setting while troubleshooting, got a new ModuleNotFound error for core.tasks #CELERY_IMPORTS = ( # 'core.tasks', #) CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_BEAT_SCHEDULE = { "ScrapeStuff": { 'task': 'core.tasks.scrape_dev_to', 'schedule': 10 # crontab(minute="*/30") } } celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'newsscraper.settings') app = Celery('newsscraper') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() When I run debug for … -
DRF foreign key field is not showing when serializing object
I have a few models to represent a user. A user has a garden, a profile and a gardener_profile. When serialising the user objects, garden and profile are getting showed, but gardener_profile is not. All of them are one to one relations. Here is my user serializer: class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) garden = GardenSerializer(read_only=True) gardener_profile = GardenerProfileSerializer(read_only=True) class Meta: model = CustomUser fields = ['id', 'url', 'username', 'email', 'first_name', 'last_name', 'password', 'groups', 'profile', 'garden', 'gardener_profile'] extra_kwargs = {'password': {'write_only': True}} And here are the models: class CustomUser(AbstractUser): email = models.EmailField(unique=True) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') address = models.CharField(max_length=255) country = models.CharField(max_length=50) city = models.CharField(max_length=50) zip = models.CharField(max_length=5) class Garden(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) grass = models.DecimalField(max_digits=6, decimal_places=2) terrace = models.DecimalField(max_digits=6, decimal_places=2) class GardenerProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) salary = models.DecimalField(max_digits=6, decimal_places=2) contract = models.FileField(null=True, blank=True) class WorkingHours(models.Model): gardener_profile = models.ForeignKey(GardenerProfile, related_name='working_hours', on_delete=models.CASCADE) weekday = models.IntegerField(choices=WEEKDAYS) from_hour = models.TimeField() to_hour = models.TimeField() class Meta: ordering = ('weekday', 'from_hour') unique_together = ('weekday', 'gardener_profile') -
Django expose session id when the site is being embedded inside an iframe
I have two django applications the first one expose a view: def render_demo_site(request: HttpRequest) -> HttpResponse: if not request.session.session_key: request.session.save() session_id = request.session.session_key return render(request, 'index.html', locals()) and the html: <html> <header> <title>DEMO</title> <script> const sessionID = '{{ session_id | safe }}'; console.log("sessionID", sessionID); </script> </header> <body> <h1> DEMO SITE </h1> <p>Session ID: {{ session_id }}</p> </body> </html> in the other Django application I have a site which expose a view where inside it's html I embed the other site inside an iframe: html: <html> <header> <title>DEMO</title> </header> <body> <iframe src="http://localhost:8005"></iframe> </body> </html> my goal is to extract the session id of the Django demo application in the later Django application Thanks -
How do I allow permissions so that i can run my python server?
I was trying to practice using django but when i tried to initially execute ' python3 manage.py runserver ' for some reason I received a permission denied when trying to run it and im not sure what that means, ive seen this before but im not sure how i would be able to allow permissions, i thought i enabled everything in start up but i feel as though i am missing something. I will post a picture here from when i went into the folder i started and tried to run the server. -
Why does Java script Self updating graph is not updating the plot?
I have written a code to plot a self-updating plot using JavaScript and Ajax, I am following this example (https://www.fusioncharts.com/charts/realtime-charts/speedometer-gague) and trying to implement in my project. The code I am using is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://epochjs.github.io/epoch/css/epoch.css" /> <link rel="stylesheet" href="https://epochjs.github.io/epoch/css/epoch.css" /> </head> <body> <div class="container"> <div id="chart-container"></div> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- Latest compiled and minified CSS --> <!-- Latest compiled and minified JavaScript --> <script src="https://cdn.fusioncharts.com/fusioncharts/3.15.2/fusioncharts.js"></script> <script src="https://cdn.fusioncharts.com/fusioncharts/3.15.2/themes/fusioncharts.theme.fusion.js"></script> <script src="https://epochjs.github.io/epoch/js/epoch.js"></script> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> <script> FusionCharts.ready(function() { new FusionCharts({ type: "angulargauge", renderAt: "chart-container", width: "400", height: "300", dataFormat: "json", dataSource: { chart: { caption: "Fly Ash Generation Rate", subCaption: "Belews Creek Power Station<br>In Metric Tonnes", theme: "fusion", showValue: "1" }, colorRange: { color: [ { minValue: "0", maxValue: "0.4", code: "#62B58F" }, { minValue: ".40", maxValue: ".60", code: "#FFC533" }, { minValue: ".60", maxValue: "1", code: "#F2726F" } ] }, dials: { dial: [ { value: "0.6", toolText: "<b>$dataValue metric tonnes</b>" } ] } }, events: { initialized: function(evt, args) { var chartRef = evt.sender; function addLeadingZero(num) { return num <= 0.6 ? "0" + num : num; } function updateData() { $.ajax({ url:"{% url 'fetch_sensor_values_ajax' %}", success: function (response) … -
Django rest-auth How to get specific account user with user Token
the before response was: { key : Token } i want to change it to: { key : Token, username : username } but i have only the User Token and i can't figure out how to get the specific Account details I want to use Account.objects.get() but i have nothing except the Token my Account Model: class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30,primary_key=True, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) My Custom View response: class CustomLoginView(LoginView): def get_response(self): orginal_response = super().get_response() mydata = {"username": "TheUser_username"} orginal_response.data.update(mydata) return orginal_response Url: path('login/', CustomLoginView.as_view()), How do i get pass this? anyone?