Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display number of objects in the account model
I am currently creating a rest api. I have an account and book model. The book model has a foreign key to the account. I want to add a number_of_books field in the account model which has an int representing how many books the user has. What is the best way to implement this? Do I need to calculate from the client side? Should I create a middleware that does this? Any help is appreciated. -
How to create ViewComponent in Django?
I want to create an html containing the Menu model, and when used, only needs {% include 'menu.html'%}, no need to pass the menu variable = Menu.object.all (). It is similar to ViewComponent in ASP.NET Core -
Django Model Inheritance - Instance attributes not set properly
Alas, my code was working perfect until I decided to "fix" it and use inheritance for some linked classes. I have a UserProgram class that inherits from MyUser and Program. When I changed the class definition to UserProgram(Program, MyUser), I started getting strange behavior with my UserProgram.objects.get() function, which gets the values from a stored procedure call via get_data_pk: raw('select 1 as id, * from SP_GetUserProgram(%s,%s,%s)', params) After adding the inheritance, I see the new objects have all the inherited fields, which is fine. But their attributes are not being assigned the correct values now. For instance, maxbudget and availablebudget should both be 400000, but that is incorrectly assigned to uploaddirectoryid. Creating the UserProgram objects manually, like UserProgram(...) works fine. I'm not sure what to do here. Any ideas? Below is a simplified version of my code. models class UserProgramManager(models.Manager): def get(self, userid, programname, schoolyear): return get_data_pk(self, 'SP_DCPGetUserProgram(%s,%s,%s)', (userid, programname, schoolyear) ) class MyModel(models.Model): class Meta: managed = False abstract = True class MyUser(AbstractBaseUser): userid = models.IntegerField(primary_key=True) objects = MyUserManager() class Program(MyModel): schoolyear = models.SmallIntegerField(primary_key=True) programname = models.CharField() def __init__(self,schoolyear=None,programname=None,*args,**kwargs): super(Program, self).__init__(*args,**kwargs) self.schoolyear = schoolyear self.programname = programname class UserProgram(Program, MyUser): uploaddirectoryid = models.CharField() objects = UserProgramManager() test.py # Works … -
How to create schedule in Django
So, I want to create a schedule of training in Django. My DB models looks models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Coach(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Пользователь", related_name="coach") name = models.CharField(max_length=200) phone = models.CharField(max_length=200) desc = models.CharField(max_length=500) avatar = models.ImageField(upload_to="coach_avatars/", blank=True) def __str__(self): return self.user.get_full_name() class TypeOfTraining(models.Model): coach = models.ForeignKey(Coach, on_delete=models.CASCADE, related_name="training_type") name = models.CharField(max_length=100) desc = models.CharField(max_length=500) price = models.FloatField(default=0) def __str__(self): return self.name class TrainingSchedule(models.Model): coach = models.ForeignKey(Coach, on_delete=models.CASCADE) training_type = models.ForeignKey(TypeOfTraining, on_delete=models.CASCADE) start_at = models.DateTimeField() def __str__(self): return str(self.id) how do I display data from the database in html form that looks like an image? example: how looks schedule on HTML page I have done HTML template. but I haven't how to show data from DB in my template. P.S. Sorry for my English. -
django call .annotate context processors in DetailView
My project depending on giving users points for any thing they do (post, comment, like, favourite, ....) i created context processor to use some calculations inside several templates. My problem is i cannot call these context processors inside template without for loop Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') favourite = models.ManyToManyField(User, related_name='favourite', blank=True) class Comment(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='commenter') post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') class Profile(models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') views.py class UserDetailView(DetailView): template_name = 'user/user-details.html' queryset = User.objects.all() def get_object(self): return get_object_or_404( User, username__iexact=self.kwargs.get("username") ) settings.py 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'common.context_processors.user_counters', ], templates.html <ul class="dynamic-tabs-list"> <li class="active" data-content=".content-posts">Posts <span class="badge badge-light">{{ user.posts.count }}</span></li> <li data-content=".content-comments">Comments <span class="badge badge-light">{{user.commenter.count}}</span></li> <li data-content=".content-favourites">Favourites <span class="badge badge-light">{{ user.favourite.count }}</span></li> <li data-content=".content-points">Points <span class="badge badge-light">{{ user.total_score }}</span></li> </ul> context_processors.py def user_counters(request): user_qs = User.objects\ .annotate( user_posts_count=Count('posts', distinct=True), user_posts_score=F('user_posts_count') * 10,)\ .annotate( user_comments_count=Count('commenter', distinct=True), user_comments_score=F('user_comments_count') * 10,)\ .annotate( user_favourites_count=Count('favourite', distinct=True), user_favourite_score=F('user_favourites_count') * 10,) \ .annotate( user_likes_count=Count('likes', distinct=True), user_likes_score=F('user_likes_count') * 10, ) \ .annotate( total_score=F('user_posts_score')+F('user_comments_score')+F('user_favourite_score')+F('user_likes_score') ) context = { 'user_qs': user_qs, } return context urls.py path('profile/<username>/', UserDetailView.as_view(), name='user-detail'), Any help please ? Thanks in-advance -
In a Django migration, how can I create an object and use it as default in another field?
I already have a model Area. I want to add a new model City, like: class City(models.Model): pass class Area(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT) # new field. How to create a migration which sets the existing areas to a city (called 'Mumbai')? I know I can do migrations.RunPython but how do I get the new city's id to pass to models.ForeignKey's default param? migrations.AddField( model_name='area', name='city', field=models.ForeignKey(default=???, to='location.City'), preserve_default=False, ), -
DJANGO - Extract filtred data to excel
I have a view with a django-filter that generate a filtred table. I would like to export this filtred table. For now, I success to export the non filtred data using xlwt 2 questions : - How to extract the filtred data ? - How to apply format date and hour in excel column ? I have a model Order with the fields 'Date','Hour','Category','Item', OrderFilter is a django-filter Views.py def data(request): orders= Order.objects.all() filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date','-Hour') return render(request, 'template.html',{'orders':orders,'filter': filter}) def export_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Hour', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Order.values_list('Date', 'Hour', 'Category', 'Item__Item') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response url.py path('data/',views.data, name='data'), url(r'^export/xls/$', views.export_data, name='export_data') template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <a class="btn btn-primary" href="{% url 'export_data' %}">Export</a> <table> display the filtred table ...</table> -
Where to find all models field type in Django?
class Products(models.Model): p_name = models.TextField() sku = models.TextField() price = models.TextField() desc = models.TextField() Also please suggest me an IDE that auto suggest models fields type. currently i am using sublime text. Thanks. :) -
Using django-environ; Django admin css not found
I removed the BASE_DIR and the os import because I am using django-environ. However when I entered the admin dashboard of Django, the css is not read so I only see plain html elements. Here is how part of my settings.py looks like. import environ root = environ.Path(__file__) - 3 # get root of the project env = environ.Env() environ.Env.read_env() # reading .env file SITE_ROOT = root() DEBUG = env.bool('DEBUG', default=False) TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = tuple(env.str('ALLOWED_HOSTS', default=[])) DATABASES = { 'default': env.db('DATABASE_URL') } SECRET_KEY = env.str('SECRET_KEY') # Static and Media Config public_root = root.path('public/') MEDIA_ROOT = public_root('media') # MEDIA_ROOT = root.path('media/') MEDIA_URL = env.str('MEDIA_URL', default='media/') STATIC_ROOT = public_root('static') STATIC_URL = env.str('STATIC_URL', default='static/') ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [root.path('templates/'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] So I also put in root.path('templates') into the DIRS of TEMPLATES. What should be written instead? -
Celery - No result backend is configured while using gunicorn
Im unsing gunicorn like many others to run my python app. I just wanted to try things out in production mode and discoverd that I'm not able to trigger a celery @shared_task while im running in production mode which basically just means hide all output errors and use gunicorn instead of the development runserver. Celery always returns the error "No result backend is configured" which makes absolut no sense to me as everything else works as expected when using the development runserver I don't know where I could start to debug this behaviour as CELERY_RESULT_BACKEND = 'django-db' simply seems to get ignored. This is how I start gunicorn: gunicorn App.wsgi:application \ --workers $GUNICORN_WORKERS \ --bind=127.0.0.1:8000 \ --log-level info celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery import environ from django.conf import settings env = environ.Env() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "App.settings") app = Celery(str(settings.SITE_NAME), broker=str("redis://") + str(':') + env.str('REDIS_PASSWORD') + str('@') + env.str('REDIS_HOST') + str(":") + env.str('REDIS_PORT') + str("/")) app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) init.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task … -
Deploying django channel project for free [closed]
I have a django channels project. I am looking to deploy it on a free server. I don't know much about free servers that will host my project. Anyone that can help me with some info. Thanks. -
Django - Custom handler500 not working despite following docs
I followed the docs step-by-step and searched for a solution everywhere but my custom handler500 won't work. I use Django 2.2 with Python 3.8. Here's my urls.py: urlpatterns = [ # some urls ] handler500 = "path.to.my.handler" my handler: def handler500(request, exception=None, *_, **_k): print("yeah I got called") return render(request, "my_template.html", { "exception": exception }) my view: def example_view(request): # I tried all of these return HttpResponseServerError() return HttpResponse(status=500) raise Exception("There was an error") # This just shows: "A server error occurred. Please contact the administrator." in the browser. raise HttpResponseServerError() # This shows the same message as above. a_typo # This typo also shows the same message as above. Why doesn't ANY of these errors show my template? The handler didn't get executed at any time. The print() function never got called. -
Python: Selenium no such element: Unable to locate element: {"method":"xpath","selector":"//button[@data-id=1]"}
Why I got this error no such element: Unable to locate element: {"method":"xpath","selector":"//button[@data-id=1]"} test.py zone = Zone.objects.last() self.browser.refresh() time.sleep(2) self.browser.find_element_by_xpath("//button[@data-id="+str(zone.id)+"]").click() # zone.id = 1 I have also tried with self.browser.find_element_by_id('update_id_'+str(zone.id)) but not working :( what's wrong going on ? html <button type="button" id="updateButton update_id_2" class="btn btn-xs btn-primary updateButton" data-id="2"> <i class="fa fa-edit"></i> </button> -
Complex Database Query in Django Graph-Structure
I have a django-project with the following model structure. At first I have a graph-structure with nodes and (directed and weighted) edges in the following way: class Node(models.Model): name = models.TextField() class Edge(models.Model): from_node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, related_name='edge_from_node') to_node = models.ForeignKey(Node, on_delete=models.DO_NOTHING, related_name='edge_to_node') costs = models.IntegerField() There also do exists token, whereby a node can be related to multiple tokens but a token can only be related to one node: class Token(models.Model): node = models.ForeignKey(Node, on_delete=models.DO_NOTHING) Additional I have a User object that can own multiple tokens: class MyUser(models.Model): tokens = models.ManyToManyField(Token) I now want to make a database query that for a given TargetNode and MyUser gives the edge with the minimal costs connecting any node, for which MyUser owns a token, with the TargetNode. Let me make a simple example: # we create 4 nodes ... n1 = Node(name="node 1") n2 = Node(name="node 2") n3 = Node(name="node 3") n4 = Node(name="node 4") n1.save() n2.save() n3.save() n4.save() # -.. and create 3 edges e1 = Edge(from_node=n2, to_node=n1, costs=3) e2 = Edge(from_node=n3, to_node=n1, costs=2) e3 = Edge(from_node=n4, to_node=n1, costs=1) e1.save() e2.save() e3.save() # create a user user = MyUser() user.save() # create 2 tokens for the given user to node2 … -
Django error: Instance of 'OneToOneField' has no 'username' member pylint(no-member)
I'm new to Django and I'm learning it throw a youtube tutorial. I'm trying to build a simple Blog but I have some problem that I think could be related to python or django version. I'm using python3.7.5 and django2.1.5. I've created the following model which represent the user's profile which overrides the save method to enable a resize of the uploaded profile picture. from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) From this I get a few errors, for example in str method from this line: return f'{self.user.username} Profile' I get this error: Instance of 'OneToOneField' has no 'username' memberpylint(no-member) And I get similar error every time I use the self. Can anyone help me? -
"TypeError: stat: path should be string, bytes, os.PathLike or integer, not NoneType" when installing Django via pipenv on Windows 10:
I am trying to install Django on my Windows 10 System. Python 3.7.7 and pipenv 2018.11.26 are propoerly installed. When I try to run pipenv install django==2.2.5 i get the following error message, for which I just can't figure out the reason: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts\pipenv.exe\__main__.py", line 9, in <module> File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 717, in main rv = self.invoke(ctx) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\vendor\click\decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\cli\command.py", line 254, in install editable_packages=state.installstate.editables, File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1927, in do_install pypi_mirror=pypi_mirror, File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1386, in pip_install pip_command = [which_pip(allow_global=allow_global), "install"] File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 1459, in which_pip return which("pip") File "C:\Users\AMCSPSRICHTERDaniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\pipenv\core.py", line 117, in which if not os.path.exists(p): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.2032.0_x64__qbz5n2kfra8p0\lib\genericpath.py", line 19, in exists os.stat(path) TypeError: stat: path should be string, … -
How can i get image from Profile model into my Post model
There are two model profile and post..i want to get image from profile model..into my post model..how can I get? -
How to install nginx on hosting django
I have nginx code.conf want to show statics, to position it on the hosting(jino) and what actions to make at the command line(via ssh)? Everywhere write about using uwsgi but I don't have it and the site loaded all the same url, but without the statics don't know if it is pre-installed on your hosting Since location is not my project as I don't know any way to register nginx.conf upstream caparol_center_spb_decision { server unix:///tmp/educa.sock; } server { listen 80; server_name www.caparolcenterspb.ru caparolcenterspb.ru; location / { include /etc/nginx/uwsgi_params; uwsgi_pass educa; } location /static/ { alias /home/projects/educa/static/; } location /media/ { alias /home/projects/educa/media/; } } -
No reverse match in Django when passing in a query argument
I am trying to pass a query argument into a Django view through the URL, like so: 127.0.0.1:8000/vysledky/?a_id=1 However, whenever I try to go to that URL, it gives me a NoReverseMatch error. The full error report is listed below: Request Method: GET Request URL: http://127.0.0.1:8000/vysledky/?a_id=1 Django Version: 3.0.5 Python Version: 3.8.0 Installed Applications: ['analysis.apps.AnalysisConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /Users/vojtamazur/Documents/CS_IA/mysite/analysis/templates/analysis/base.html, error at line 0 Reverse for '' not found. '' is not a valid view function or pattern name. 1 : <!DOCTYPE html> 2 : <html> 3 : <head> 4 : {% if title %} 5 : <title> Analýza - {{ title }} </title> 6 : {% else %} 7 : <title> Analýza </title> 8 : {% endif %} 9 : </head> 10 : <body> Traceback (most recent call last): File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/vojtamazur/Documents/CS_IA/env/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in … -
How do I automatically inherit a foreignkey model's field in django rest?
Models.py, From django admin what I do is I can add a product to Featured but the problem is when I select a product in admin to make featured I want to automatically inherit that product's image url which was uploaded when that product was created. class Product(models.Model): seller = models.ForeignKey(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=120, primary_key=True) image = models.FileField() def __str__(self): return self.title class FeaturedProduct(models.Model): db_identification = models.CharField(max_length=120) featured = models.ForeignKey(Product, on_delete=models.CASCADE) photograph = How do I inherit it automatically from foreignkey product selected? timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.db_identification -
How can i connect a Javascript client to a Python-SocketIO server?
I'm just getting started to Python-SocketIO, i created an example server, it looks like this: import eventlet import socketio sio = socketio.Server() app = socketio.WSGIApp(sio, static_files={ '/': {'content_type': 'text/html', 'filename': 'index.html'} }) @sio.on('connect') def connect(sid, environ): print('connect ', sid) @sio.on('msg') def message(sid, data): print('message ', data) @sio.on('disconnect') def disconnect(sid): print('disconnect ', sid) if __name__ == '__main__': eventlet.wsgi.server(eventlet.listen(('', 5000)), app) Then, i have an HTML file which is running on a Django application, i would like to connect that client to my Python-SocketIO server: <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> <script> socket = io.connect(''); socket.on('connect',function() { console.log('Client has connected to the server!'); }); socket.on('msg',function(data) { console.log('Received a message from the server!',data); }); socket.on('disconnect',function() { console.log('The client has disconnected!'); }); // Sends a message to the server via sockets function send(message) { socket.send('msg',message); }; </script> The problem is that, on my client side, i keep getting the following errors: Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=N5eSEa2' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. localhost:5000/socket.io/?EIO=3&transport=polling&t=N5eSEa2:1 Failed to load resource: net::ERR_FAILED My Django server is running on http://127.0.0.1:8000/. Can anyone help me find what i'm doing wrong? -
get latest object from databse regardless of user in django
I am learning python and django and I am coding a project similar to IMDB. I am using python 3.8.2 64 bit and django 3 I want to display the latest review a movie received regardless of the user that wrote it. Now it shows the user's own latest review and after logging the user out the review remains without displaying the user that wrote it. I have tried to clear cache and history, didn't help. this is the model: from django.db import models from django.contrib.auth.models import User class Movie(models.Model): movie_title = models.CharField(max_length=250) movie_poster = models.ImageField(default='default.png', blank=True) movie_short_description = models.TextField() director = models.CharField(max_length=250) actor1 = models.CharField(max_length=250) actor2 = models.CharField(max_length=250) actor3 = models.CharField(max_length=250) actor4 = models.CharField(max_length=250) year = models.IntegerField() def __str__(self): return self.movie_title + ' - ' + str(self.year) class Review(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, default = None, on_delete=models.DO_NOTHING) score = models.IntegerField() review_title = models.CharField(max_length=250, default="") movie_review = models.TextField() date = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'date' def __str__(self): return self.review_title views.py def movie_detail(request, pk): try: movie = Movie.objects.get(pk=pk) review = Review.objects.all().latest() except Exception as e: print(e) return render (request, 'movies/movie_detail.html', {'movie': movie, 'review': review}) html code: </table> </p> <p>User Reviews</p> <h3>Score: {{review.score}} {{review.review_title}}</h3> <h6>{{review.date}}, by {{ user.get_username … -
Optimize file opening in Django (clean and attributes method)
In my forms.py I have a clean() method. The clean method does a lot of things. It opens the file, validates the headers, validates the content etc etc. It works fine. forms.py class BatchFileUploadForm(forms.Form): csv_file = FileField(label='CSV File', required=False) def __init__(self, *args, **kwargs): super(BatchFileUploadForm, self).__init__(*args, **kwargs) self.fields['csv_file'].widget = CustomButtonFileWidget() self.fields['csv_file'].help_text = 'Upload a CSV file which contains the results' def clean(self): uploaded_csv_file = self.cleaned_data['csv_file'] allowed_headers = {'id','name','approve','reject'} validation_errors = [] if not uploaded_csv_file.name.endswith(settings.FILE_UPLOAD_TYPE): raise forms.ValidationError("Please upload .csv extension files only") csvin = csv.DictReader(StringIO(uploaded_csv_file.read().decode('utf-8'))) # lowercase all fieldnames before doing anything else csvin.fieldnames = [name.lower() for name in csvin.fieldnames] After the file is clean, I want to save the contents of the file. So in view.py I have to reopen the file again view.py def upload_batch(request): fileList= [] approved_count = 0 rejected_count = 0 form = BatchFileUploadForm( data=(request.POST or None), files=(request.FILES or None) ) if(form.is_valid()): uploaded_csv_file = request.FILES['csv_file'] csvin = csv.DictReader(StringIO(uploaded_csv_file.read().decode('utf-8'))) # lowercase all fieldnames before doing anything else csvin.fieldnames = [name.lower() for name in csvin.fieldnames] for row in csvin: fileList.append(row) if row['approve'] == 'x': approved_count+=1 if row['reject'] =='x': rejected_count+=1 # putting fileList in session so it can be accessed in the second method save() return render(request, "file/confirm_save.html", {'form': form, 'fileList':fileList, … -
Django: Take the data from database and display on the page in a modified form
Please tell me how to correctly solve the following problem There is a phone number in the database. On the site it is displayed in the same form in which it is recorded in the database +1234567890 And I need this number to look like this, on the site page without modification in the database +(123) 456-7890 views.py def Data(request): card = Cards.objects.filter(is_published=True) context = {'card': card} return render(request, 'templates/cards.html', context) models.py phone = models.CharField(max_length=12, null=True) cards.html {{ card.phone }} Thanks! -
Django Celery - No result backend is configured while running in prod
I use ASGI aka uvicorn to run my django application in production and i'm also using celery to call specific tasks at my app. Now I configured a result backend so that I can see all my tasks results at the Django admin which is working fine if I use the Django development server. But if I switch to production mode and using uvicorn I get back the following error: Exception Value: No result backend is configured. Please see the documentation for more information. while waiting on a celery task I call like that at my views.py: my_task = gen_new.apply_async(kwargs={"user_pk": user.pk}) my_task.get(timeout=30, interval=1) my asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'App.settings') application = get_asgi_application() starting the ASGI server like so: gunicorn App.asgi:application \ --workers $UVICORN_WORKERS \ --bind=127.0.0.1:8000 \ --log-level info settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": [ str("redis://") + str(':') + env.str('REDIS_PASSWORD') + str('@') + env.str('REDIS_HOST') + ":" + env.str('REDIS_PORT') + str("/") + env.str('REDIS_CACHE_DB') ], "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "SOCKET_CONNECT_TIMEOUT": 30, # in seconds "SOCKET_TIMEOUT": 30, # in seconds "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", "CONNECTION_POOL_KWARGS": {"max_connections": env.int('REDIS_MAX_CONN'), "retry_on_timeout": True} } } } BROKER_URL = str("redis://") + str(':') + env.str('REDIS_PASSWORD') + str('@') + env.str('REDIS_HOST') + str(":") + env.str('REDIS_PORT') CELERY_RESULT_BACKEND …