Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - API links shown as serializers instead
My API looks something liks this { "id": 7, "url": "http://127.0.0.1:8000/workers/7/", "first_name": "ellie", "last_name": "hodjayev", "email": "zenmyx@gmail.com", "phone_number": 502461700, "hire_date": "2022-06-18", "job": 1, "speciality": 5, "salary": 17000, "commission_pct": 0, "manager_id": 0, "department_id": 0 } 'job' and 'speciality' should be shown as links since they're configured to be serializers.hyperlinkedmodeserializers but instead we're seeing a serial number.. from here it looks everything is configured correctly. serialize.py from rest_framework import serializers from .models import Worker, Speciality, Job class WorkerSerializer(serializers.ModelSerializer): class Meta: model = Worker fields = ['id', 'url', 'first_name', 'last_name', 'email', 'phone_number', 'hire_date', 'job', 'speciality', 'salary', 'commission_pct', 'manager_id', 'department_id'] class SpecialitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Speciality fields = ['id', 'url', 'speciality'] class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Job fields = ['id', 'url', 'job'] -
Como puedo poner mi moneda local en Django?
Tengo un problema con un proyecto , con un amigo sacamos codigo de otros proyectos y resulta que el formato de moneda es el de la india , alguien sabe como cambiar el tipo de moneda por otra? el problema -
Problem with permutations function in Django, how to make it work?
Hi i have problem with large amount of data while doing permutations teamA = [tournament.p1, tournament.p2, tournament.p3] teamB = [player.op1, player.op2, player.op3] for perm in permutations(teamA): result.append(list(zip(perm, teamB))) for pairing in result: score = [] total = 0 for i in pairing: if i == (tournament.p1, player.op1): i = player.p11 elif i == (tournament.p1, player.op2): i = player.p12 elif i == (tournament.p1, player.op3): i = player.p13 elif i == (tournament.p2, player.op1): i = player.p21 elif i == (tournament.p2, player.op2): i = player.p22 elif i == (tournament.p2, player.op3): i = player.p23 elif i == (tournament.p3, player.op1): i = player.p31 elif i == (tournament.p3, player.op2): i = player.p32 elif i == (tournament.p3, player.op3): i = player.p33 points.append(i) for s in points: if s == -3: mp = 1 elif s == -2: mp = 4 elif s == -1: mp = 7 elif s == 1: mp = 13 elif s == 2: mp = 16 elif s == 3: mp = 19 else: mp = 10 score.append(mp) total += mp data_list.append([pairing, score, total]) This is code i run for sets od pairs in teams of 3, but if i want to do teams of 8, and permutations of 8 where teamA … -
Django search returning Exception Value: object of type 'method' has no len()
Pretty new to Django Rest Framework and I'm not quite sure how to debug this error at the moment. When I set a breakpoint in the view search view. I see all my products in results <bound method QuerySet.distinct of <ProductQuerySet [<Product: Product object (4)>, <Product: Product object (8)>, <Product: Product object (9)>, <Product: Product object (10)>]>> Pagination is set in settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "api.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticatedOrReadOnly", # GET for everyone, all other calls need to be authenticated ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10, } Search view from rest_framework import generics from products.models import Product from products.serializers import ProductSerializer class SearchListView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) q = self.request.GET.get("q") results = Product.objects.none() if q is not None: user = None if self.request.user.is_authenticated: user = self.request.user results = qs.search(q, user=user) return results Products view from rest_framework import generics, mixins from django.shortcuts import get_object_or_404 from api.mixins import StaffEditorPermissionMixin, UserQuerySetMixin from .models import Product from .serializers import ProductSerializer class ProductListCreateAPIView( UserQuerySetMixin, StaffEditorPermissionMixin, generics.ListCreateAPIView ): queryset = Product.objects.all() serializer_class = ProductSerializer def perform_create(self, serializer): title = serializer.validated_data.get("title") content = serializer.validated_data.get("content") or None if content is None: content = title serializer.save(user=self.request.user, … -
How can I create the associated OneToOne Field in Django automatically?
I have tried Django Annoying as mentioned in this answer Create OneToOne instance on model creation But I still get NOT NULL CONSTRAINT FAILED on the OneToOne Field when creating my object, which I suppose means that the associated object is not created, hence NULL If I use A signal Handler, that will be activated every time the Model's save method will be called. I will end up creating a new Object even when updating the Parent object. My Profile structure is as follows: { "id": 3, "password": "pbkdf2_sha256$320000$5TQCdD5wIelYpO4ktpuuAk$oBC9xUT+8RjOxZHvE8C+eowS4PvdCT8vUAuS4Y2n7sM=", "last_login": null, "is_superuser": false, "username": "hamad", "first_name": "", "last_name": "alahmed", "email": "", "is_staff": false, "is_active": true, "date_joined": "2022-06-17T13:04:51.927199Z", "height": null, "weight": null, "createddate": "2022-06-17T13:04:52.362396Z", "date": null, "hobbies": null, "dailyRoutine": { "id": 8, "steps": 0, "diet": "No Specified Diet", "maintained": 0 }, "groups": [], "user_permissions": [], "friends": [ { "id": 1, "password": "pbkdf2_sha256$320000$YRcHWSjLi1CMbfrolZ0W7W$9LgjH2m5c8emE66pjdExmgep47BAdKTrCJ7MBiJx74w=", "last_login": "2022-06-17T17:50:48.410366Z", "is_superuser": true, "username": "super", "first_name": "Super1", "last_name": "Admin1", "email": "super@gmail.com", "is_staff": true, "is_active": true, "date_joined": "2022-06-17T12:27:37.575631Z", "height": 160, "weight": 75, "createddate": "2022-06-17T12:27:37.789754Z", "date": null, "hobbies": "Football", "dailyRoutine": 10, "groups": [], "user_permissions": [], "friends": [ 2, 3 ] } ] } The Object that I want to create automatically is DailyRoutine The Routine code: class Routine(models.Model): steps = … -
AttributeError: module 'colorama' has no attribute 'init'
i have python version 3.8 and trying to deploy django model to Apache2 server and getting this error. anybody can help me to resolve this? -
no such column: Blog_post.category_id
I’m trying to create a category for each post. I made another class with the same models.py and in the same class Post I made a category = models.ForeignKey But it keeps showing me this error when I run the server: (no such column: Blog_post.category_id) Ps: I did run the makemigrations and the migrate command. The tutorial I followed just added the model as it is in models.py but should I also make a function for the views.py or its just a model problem ? models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, default="Some random thing") -
Django : change the id with another field in the views page
my question is: How do I tell to Django to replace the Column type_id to the name field in the views (html page). and here I have foreignkey, it gave me id (type_id), and this screentshot of fabrication class: the column type_id is comming from the composant_type class, models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from CentreCout.models import CentreCoutDB class fiche(models.Model): centre_cout = models.CharField(max_length=150) number = models.CharField(max_length=100) name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class unite(models.Model): name = models.CharField(max_length= 150, unique=True) def __str__(self): return self.name class composant_type(models.Model): name = models.CharField(max_length=150, unique=True ) def __str__(self): return f"({self.name})" class composant_fab(models.Model): type = models.ForeignKey(composant_type, to_field='name', on_delete=models.CASCADE) name = models.CharField(max_length=150, unique=True) def __str__(self): return f"({self.name})" class fabrication(models.Model): grade = models.ForeignKey(fiche, to_field='name',on_delete=models.CASCADE) type = models.ForeignKey(composant_type, on_delete=models.CASCADE, blank=True, null=True) composant = models.ForeignKey(composant_fab , to_field='name', on_delete=models.CASCADE, null=True, blank=True) unite = models.ForeignKey(unite, to_field='name',on_delete=models.CASCADE) composant_value = models.FloatField(blank=True, null=True) def __str__(self): return f"({self.grade}-{self.composant}-{self.composant_value}-{self.unite})" views.py from django.shortcuts import render from django import views from django.http import HttpResponse from .models import * import pandas as pd def fabrications(request): lesfichestab = fiche.objects.all() fabricationtab = fabrication.objects.all().values() df = pd.DataFrame(fabricationtab) context = { 'lesfichestab':lesfichestab, 'fabricationtab':df.to_html() } return render(request,'fabrications/fabricationpage.html', context) note : I use Pandas method, because i have … -
showcasing one attribut of multiple instances from a model django/python
i basically have 2 models with multiple attributes, i would like to showcase a specific attribute which has multiple instances, in another model basically : class Carnet(models.Model): ....multiple attributes class Consultation(models.Model): .... date_cons = models.DateTimeField(default=datetime.now, blank=True) There are multiple instances of date_cons, i would like to showcase the latest one added in an html code the view method i used was this ( probably here is the problem ) def consultation(request, carnet_id): consultation = Consultation.objects.all() context = { 'consultation' : consultation } return render(request, 'carnets/carnet.html',context) tried showcasing that attribute in an html code using this syntaxe {{consultation.date_cons}} but it doesn't showcase anything my question is probably all over the place i'm not very good at computer science nor english, i ask for your help -
Django: pass request and response as view parameters
I have a view which takes two parameters (request, response). But when this view is called i get an error which saying - "figure() missing 1 required positional argument: 'response' " views.py: def figure(request, response): print("request ->", request) figures = add_data_to_class(request) figures_dict = [] for figure in figures: figures_dict.append({ "date":figure.date, "price_new":figure.price_new, "price_used":figure.price_used, }) print(figures_dict) context = {"figures":figures_dict} return render(response, "app1/figure_data_page.html", context, RequestContext(request)) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.figure, name="figure") ] figure_data.html <form action="main\app1\views.py" method="post" id="figure_choice_form"> <label for="id">Enter ID</label> <input type="text" id="id"> </form> -
How to make a select field using Django model forms (using set values)?
I recently switched from using simple forms in Django to model forms. I am now trying to use a select field in my form that has set field names (eg:Europe,North America,South America...) I thought I would just add a select input type to the for fields but it shows up as just a regular text input. The select field is supposed to be "continent". Does anyone know how to to d this?? class TripForm(forms.ModelForm): # city = forms.TextInput() # country = forms.TimeField() # description = forms.Textarea() # photo = forms.ImageField() class Meta: model = Trip fields = ('city', 'country', 'continent', 'description', 'photo') widget = { 'city': forms.TextInput(attrs={'class': 'form-control'}), 'country': forms.TextInput(attrs ={'class': 'form-control'}), 'continent': forms.SelectMultiple(attrs= {'class':'form-control'}), 'description': forms.TextInput(attrs = {'class': 'form-control'}), # 'photo': forms.ImageField(attrs = {'class': 'form-control'}), } [![enter image description here][1]][1] This is the form continent should show as a select. -
How to do Simple Arithmetic validation in template part - django
I want to check total price and receiving price of user input which receiving price shouldn't be more than total price. say example, I do have 3 input box. box a getting value of total price, box b getting value of receiving payment through card and box c getting value of receiving payment by cash. box b + box c should not greater than box a. I need to validate it and stop submitting it. It may very simple, since I am new to django I posting it here. -
How can I query all products with their variation attributes?
I have following database schema: Django models: class Product(models.Model): name = models.CharField(max_length=150) # price and so on class Size(models.Model): value = models.CharField(max_length=20) class Color(models.Model): value = models.CharField(max_length=20) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variations") size = models.ForeignKey(Size, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE, null=True, blank=True) So I can write: product.variations But I also want to be able to write product.sizes product.colors to get all sizes or colors that this product has in variation table The problem that I'm trying to solve: I have product card list. And each card has options of sizes and colors to choose and to add to their cart. I want to show the user sizes and colors that this particular product has in database to not list all the sizes and colors from database. But variations can have duplicates, for example, consider these combinations: size - 40, color - red size - 42, color - green size - 44, color - red (again) size - 42 (again), - color gray I want to show the user sizes: 40, 42, 44 colors: red, green, gray Now I can show all of them with duplicates like sizes: 40, 42, 44, 42 colors: red, green, red, gray It is … -
Getting OperationalError: (2000, 'Unknown MySQL error') when accessing mysql database using celery and django
I am using celery with my django application. My application works fine with mysql database, but I am getting (2000, 'Unknown MySQL error') when celery tries to access the database. This happens only when I run celery in a container, when I run it in my ubuntu machine, it works fine. This is the error that I am getting: [2022-06-18 13:39:33,717: ERROR/ForkPoolWorker-1] Task taskMonitor.tasks.monitor[7e6696aa-d602-4336-a582-4c719f8d72df] raised unexpected: OperationalError(2000, 'Unknown MySQL error') Traceback (most recent call last): File "/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/.venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File "/.venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/.venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/.venv/lib/python3.9/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (2000, 'Unknown MySQL error') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/app/taskMonitor/tasks.py", line 18, in monitor for obj in objs.iterator(): File "/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 401, in _iterator yield from self._iterable_class( File "/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql( File "/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1361, in execute_sql cursor.execute(sql, params) File "/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in … -
ModuleNotFoundError: No module named 'rest_framework.simplejwt'
I'm trying to use simplejwt, but am getting a ModuleNotFoundError. Can you see what I'm doing wrong? requirements.txt algoliasearch-django>=2.0,<3.0 django>=4.0.0,<4.1.0 djangorestframework djangorestframework-simplejwt pyyaml requests django-cors-headers black isort settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # third party api services "algoliasearch_django", # third-party packages "rest_framework", "rest_framework.authtoken", "rest_framework.simplejwt", # internal apps "api", "products", "search", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", "api.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticatedOrReadOnly" ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10} SIMPLE_JWT = { "AUTH_HEADER_TYPES": ["Bearer"], "ACCESS_TOKEN_LIFETIME": datetime.timedelta(seconds=30), "REFRESH_TOKEN_LIFETIME": datetime.timedelta(minutes=1), } Full traceback: python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
How do I get the value of a field of a model instance using the instance's pk?
The following line of code correctly prints the id number of the specific model instance that I'm interested in: views.py print(self.kwargs['pk']) Great. But how do I get the value of a field in that model instance? The following is not working, because I think it's returning the default value listed in the model class and not the value in the model instance: instance_fieldname = self.kwargs.get(ModelName.fieldname) Hoping this is a simple fix. Thank you. -
Where is the Django Migrations model?
I wish to make a custom model, which has a foreign key relationship to the django_migrations table. Can this be done? if so, exactly how do I import the django migrations model? -
UndefinedTable: relation "user" does not exist
I am deploying a fresh new Django app on the server. The problem is when I migrate all the apps in the project. I'm getting UndefinedTable: relation "user" does not exist. Things I have done already: removed all the migrations from all the apps created a new database and new migrations and still getting that error. Weird scenarios: After deployment when I run the Django app locally on the server and hit API locally on the server using curl everything is working fine. like user sign up, but when I try to see in the database it is just empty (refer to the screenshot below). it doesn't even show columns for this user table, but for other tables, I can see columns as well. after migrations I am able to create super user but when I tried to login getting 500 error. and Undefined table relation user does not exit. Expection: AUTH_USER_MODEL = 'registration.User' models.py from django.db import models # Create your models here. import uuid from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils import timezone from .managers import CustomUserManager from rest_framework_simplejwt.tokens import RefreshToken AUTH_PROVIDERS = {'facebook': 'facebook', 'google': 'google', 'twitter': 'twitter', 'email': 'email'} … -
Resolving A Django Error on Form: Object has no attribute
Hi I'm trying to create a form that will when used update one model (Command_Node), and at the same time create an instance of another model (EC_NODE) that has a many to one relationship with the Command_Nodes. However when I go onto the update view and submit the form I'm getting the following error any ideas on how I can resolve this error? Thanks for any help you can offer. AttributeError at /website/update/1 'Beacon' object has no attribute 'EC_Node_set' Request Method: POST Request URL: http://127.0.0.1:8000/website/update/1 Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'Beacon' object has no attribute 'EC_Node_set' This on traceback points to command_form.EC_Node_set.all() # <- not sure with all _ and Maj here Which I can understand. I think my intention here should be clear enough. I want to set an instance of EC_Node to hold the command just put in via the form, and I understand the error. I just don't know how to get around it so that the view/form does what I want. Relevant views.py def update(request, host_id): host_id = Command_Node.objects.get(pk=host_id) form = Command_Form(request.POST or None, instance=host_id) if form.is_valid(): # Original suggestion was command_form = Command_Form.objects.first() command_form = form.cleaned_data['host_id'] command_form.EC_Node_set.all() # <- not sure with … -
While converting html to pdf using xhtml2pdf with django, the page is stuck in loading while I try to return a Http Response, how do I fix it?
While trying to return a named response with the below code so as to generate a pdf file, the browser is stuck loading, any suggestions on how to fix it def GeneratePdf(request): job = Job.objects.get(pk=id) products = Product.objects.all() supplies = job.jobItem.all() template_path = "company/jobDetails.html" context = { "job": job, "status": status, "supplies": supplies, } template = get_template(template_path) html = template.render(context) result = io.BytesIO() #Creating the pdf output = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') #output = pisa.CreatePDF(html, dest=response) if not output.err: pdf = HttpResponse(result.getvalue(), content_type='application/pdf') pdf['Content-Disposition'] = 'filename="products_report.pdf"' return pdf But when removing the part of pdf['Content-Disposition'] = 'filename="products_report.pdf"' as the code below the code works and I get a numbered file. def GeneratePdf(request): job = Job.objects.get(pk=id) products = Product.objects.all() supplies = job.jobItem.all() template_path = "company/jobDetails.html" context = { "job": job, "status": status, "supplies": supplies, } template = get_template(template_path) html = template.render(context) result = io.BytesIO() #Creating the pdf output = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') #output = pisa.CreatePDF(html, dest=response) if not output.err: pdf = HttpResponse(result.getvalue(), content_type='application/pdf') return pdf Any suggestions? -
django authenticate returns none but works fine in shell
def login_page(request): if request.method=='POST': user_name = request.POST.get('username') user_password = request.POST.get('password') user =authenticate(request,username=user_name,password=user_password) print(user) if user is not None: login(request,user) return redirect('/') else: messages.info(request,'Invalid user name or password') return redirect('/login_page') else: return render(request,'account/login_page.html') This is the code I'm using the authenticate function is returning none even for a valid input. I have tried authenticate in shell for same input and it is returning value as expected, so I don't understand ehy it is not working for values from HTML form. this is how i saved the user user = User.objects.create_user(email=email,first_name = firstname,last_name=lastname, username=username,password=password1) user.save() shell command i used (i have saved this user and using same credentials for authenticate) user_name = 'issue' user_password = '1234a' user =authenticate(request,username=user_name,password=user_password) this returns True on user is not None -
Media Streaming Servers for Django
I and my team are starting a project where in we are building a scalable live streaming platform just like Youtube. We are using Django as the backend framework. Which is the best media streaming library/server that can be used to achieve the result(It should work along the django project)? Previous Attempts : We researched about various media streaming servers and shortlisted the following three(based on our requirements that it should be able to scale up to a commercial level): Ngnix RTMP module https://github.com/arut/nginx-rtmp-module/ Node Media Server https://github.com/illuspas/Node-Media-Server Django Channels https://channels.readthedocs.io/en/stable/ We are struggling to decide which one to use for our project. I have seen a lot of people use Django channels with django to deal with such projects. But one of my teammates had a bad experience with django channels while working on a similar project hence he is advising us not to go with it. Ngnix module is attractive and a really good reputation on github but I didn't understand it well. We are very doubtful of Node Media server, no positive reviews nor negative reviews. Can you please suggest a better option maybe among them or a different one? Thank you! Any suggestions are welcome. -
Why python3 manage.py runserver built-in command also runs my custom commands?
app_name is added INSTALLED_APPS = [] and in my path /app_name/management/commands/custom.py from django.core.management.base import BaseCommand import server class Command(BaseCommand): def handle(self, *args, **kwargs): server.start() i runned python3 manage.py custom.py it runned the code in my server file fine but now when i run : python3 manage.py runserver on the console activity i can see that python3 manage.py custom.py is automatically called within runserver command -
How to update the user profile of a different user if you are logged in as the owner?
Currently, I am logged in as an owner and I want to update the fields of customers in the database. But the form does not update or show the details as a placeholder because the user model has extended the customer model and hence, the customer model does not have its own fields. How do I get the instance of the User of the Customer in the UpdateView?/How do I update the customer? views.py class CustomerUpdateView(OwnerAndLoginRequiredMixin, generic.UpdateView): template_name = "customer_update.html" form_class = CustomerModelForm queryset = Customer.objects.all() def get_success_url(self): return "/customers" models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class User(AbstractUser): is_owner = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) forms.py class CustomerModelForm(forms.ModelForm): class Meta: model = User fields = ( 'email', 'username', 'first_name', 'last_name', ) -
Django: Accessing full User information via ManyToMany field
everyone- I'm new to Django and working on my first big project and I'm having trouble with accessing default Django User model information via a ManyToMany relationship. I've spent a great deal of time searching and can't crack it. models.py class Event(models.Model): event_name = models.CharField(max_length=200, null=True, unique=True) #etc... class School(models.Model): user = models.ManyToManyField(User) event = models.ForeignKey(Event, null=True, on_delete=models.PROTECT) #etc... My url contains the id of the Event, so... views.py def schools(request, pk): event = Event.objects.get(id=pk) school = School.objects.filter(event=event) return render(request, 'accounts/schools.html', {'event':event, 'school':school}) template {% for school in school %} <tr> <td>{{school.name}}</td> <td>{{school.user.all}}</td> {% endfor %} On my template, I'm able to use {{school.user.all}} to get me a Queryset displayed with the username of each User, but I want the first_name and last_name and can't see to figure out how to get that.. Thank you for any suggestions. I greatly appreciate your time!