Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combine the huge amount of model in Django Rest
I have 2 models and an abstract class of model. models.py class TimeStampedModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField( verbose_name='Created At', auto_now_add=True ) is_deleted = models.BooleanField(default=False) modified = models.DateTimeField(auto_now=True) deleted = models.DateTimeField(null=True, blank=True) objects = NoDeleteManager() objects_with_deleted = models.Manager() class Meta: abstract = True ordering = ['created_at'] class ScentData(TimeStampedModel): name = models.CharField( max_length=64, blank=False, null=False, # unique=True, default='' ) class RawData(TimeStampedModel): scent = models.ForeignKey( 'ScentData', on_delete=models.CASCADE, related_name='rawdata_scent' ) # sensorvalue store as dicttionary # Example: {"s1":1, "s2":2, "s3":3} sensorvalue = JSONField() But now I want to combine the sensorvalue that has the same scent of RawData and delete the RawData that already combined. """ Example: after combine the value of sensorvalue will be store as list [{"s1":1, "s2":2, "s3":3}, {"s1":1, "s2":2, "s3":3}, {"s1":1, "s2":2, "s3":3}, ...] """ sensorvalue = JSONField() I have written the ViewSet to combine the RawData. Because I have 10M of rows, so my server can not handle the big times to execute. views.py class ScentDataViewSet(viewsets.ModelViewSet): queryset = ScentData.objects.all() @action(detail=False, methods=['GET'], url_path="combine_rawdata") def combine_rawdata(self, request, pk=None, **kwargs): scent_data = ScentData.objects.all() list_rawdata = list() for scent in scent_data: # call rawdata that has same scent using related_name all_rawdata = scent.rawdata_scent.all() # put all sensorvalue in list … -
Django getting related objects maintaining parent's order in a queryset
I have the following structure in a django application class Course(models.Model): name = models.CharField(_("Course Name"), max_length=50) class Module(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(_("Module Name"), max_length=50) number = models.IntegerField(_("Module Number")) class Chapter(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE) name = models.CharField(_("Chapter Name"), max_length=50) number = models.IntegerField(_("Chapter Number")) I wanted to fetch all Chapters that is contained in a course, with the order of the module (based on module number) and the order of chapter ( based on chapter number ) for example the hierarchy can be like this Course 1 has Module 1 -- Chapter number=1 (1.1) -- Chapter number=2 (1.2) -- Chapter number=3 (1.3) Module 2 -- Chapter number=1 (2.1) -- Chapter number=2 (2.2) -- Chapter number=3 (2.3) Course 2 has, Module 1 -- Chapter 1 -- Chapter 2 -- Chapter 3 Module 2 -- Chapter 1 -- Chapter 2 -- Chapter 3 I would like to fetch All chapters in Course 1 such in the order [ (1.1), (1.2), (1.3), (2.1), (2.2), (2.3) ] and so on... When i fetch all chapters with the query Chapter.objects.filter(module__in=Course1.module_set.all()) I'm getting the chapters ordered by [ (1.1), (2.1), (1.2), (2.2), (3.1), (3.2) ]... As the chapter number is 1 2 3 etc... … -
Filtering Characters in HTML - Python - Django
So I am building a website and needed to be able to filter by a prefix on a model field I have in Django on my website. Now when I display this I need the prefix to be gone. The simplest way to do this seems to be in the HTML itself with something that says to not include the first 4 characters or before such as [4:]. This seems simple but I can't get it to work and I can get this to work |truncatechars:"10" which was a recommended solution. I need something in either my views or in my HTML that says when you print don't display the first 4 characters but display everything beyond that. Thanks for any help! HTML: {{ form.title }} Models: class DocPost(models.Model): user = models.ForeignKey(User, default=True, related_name="Doc", on_delete=models.PROTECT) title = models.CharField(max_length=100) content = HTMLField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-pk'] def __str__(self): return self.title def get_absolute_url(self): return reverse('doc-post-list') Django Views: def docpostnewview(request, pk): obj = get_object_or_404(DocPost, id=pk) form = DocPostForm(request.POST or None, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect("/" + id) context = {"form":form} #context['title'] = DocPost.objects.all().filter(title='title') return render(request, "my_app/use_template.html", context) -
Can a custom manage.py command know the server domain?
I'm writing a custom manage.py command, and I need the base URL of the site. Is it possible to dynamically determine it, or do I have to hardcode it somewhere? I tried using django.contrib.sites.shortcuts.get_current_site, but it needs a request. I found this example to "get site without request": from django.contrib.sites.models import Site current_site = Site.objects.get_current() but I get this error: RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS I'm not sure what I should put in INSTALLED_APPS to make this work. Should I do something completely different? Or it this not even possible? -
How to set db model fields to just read-only even a superuser should be able to edit it
I tried this way like we do with primary keys But it's not working they as I want. I want Some fields to not editable from Django Admin We can manage it with permissions but I want it for all even superuser shouldn't be able to change values I tried this way #models.py class Payments(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name="Payment Made By",) paymentForOrderID = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Payment For Order ID") paymentMethodUsed = models.CharField(max_length=200, null=True, blank=True, verbose_name="Method Used") aproxTimeAndDateOfPayment = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Approx Date/Time Of Payment") totalAmountPaid = models.CharField(max_length=200, null=True, blank=True,editable=False, verbose_name="Amount Paid") paymentDetails = models.TextField(null=True, blank=True,editable=False,verbose_name="Details") createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True,editable=False, verbose_name="Entry ID") def __str__(self): return str(self.createdAt) Doing this when I open it it only shows editable fields but not the others. -
Retrieving None as an entry_set django
profile class SeekerProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) current_salary = models.IntegerField() currency = models.CharField(max_length=25) photo = models.ImageField(upload_to='applicants') resume = models.FileField(upload_to='applicants/documents') def __str__(self): return self.user.first_name Skillset model class Seekerskillset(models.Model): skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE) seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE) skill_level = models.CharField(max_length=25) class Meta: verbose_name = 'Seeker skill set' But when i am trying to get the entry set i am receiving None even though i am clearly having entries for amir >> from seekerbuilder.models import SeekerProfile >>> obj = SeekerProfile.objects.get(id=1) >>> print(obj) amir >>> print(obj.seekerskillset_set) seekerbuilder.Seekerskillset.None >>> for val in obj.seekerskillset_set: ... print(val) ... Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: 'RelatedManager' object is not iterable >>> -
What is the correct settings for static files in django
I just started using django and I got confused over the static files. As per this post correct static files setting I understand that STATIC_URL is just like the name. STATICFILES_DIRS is the place where django will look for static files and STATIC_ROOT where the static files will be collected to. For my project I had the following file sys rest |__ rest |__ settings.py pages static |__admin |__images |__vendor |__bootstrap templates manage.py I decided to go for a project based approach when having my folders instead of a per app one. Some stuff was not working with the website landing page I had and I saw that I needed to collectstatic and so I did but I set the path to my already existing static file which did not let me at first but somehow ended up working. Out of nowhere my static folder had admin on it which I assume is from the admin app that comes with django, and my project finally started to work properly which is the confusing part. I decided to follow the post and included in my settings the following STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') … -
URL loading the wrong view - Django
Really struggling with this one. For some reason I can't get my URL to load the correct view. The site loads the home page correctly but then when I add on the extesion to acess another one of my apps, it just reloads the home page. It doesnt throw any errors or anything, it just wond direct to the correct page. This is my base URL file: path('admin/', admin.site.urls), path('', blog_views.home), path('<username>/', include('blog.urls')), path('community/', include('community.urls')), Start of the Blog URL file: path('', LogListView.as_view(), name='log'), This is the Blog views file: @login_required def home(request): user_name = request.user.username return HttpResponseRedirect(f'{user_name}/') class LogListView(LoginRequiredMixin, ListView): model = Post template_name = 'blog/log-main.html' login_url = 'login/' context_object_name = 'posts' ordering = ['-date_added'] def get_context_data(self, **kwargs): context = super(LogListView, self).get_context_data(**kwargs) context['posts'] = Post.objects.filter(user = self.request.user) return context The home function above sutomatically directs each user to thier specific home page by placing thier username at the start of the URL path. Then here is my Community app URL file: path('', CommunityListView.as_view(), name='community'), And the Community view file: class CommunityListView(LoginRequiredMixin, ListView): model = Post template_name = 'community/community.html' context_object_name = 'postss' ordering = ['-date_added'] def get_queryset(self): qs = super().get_queryset() active_user = self.request.user active_user_following = active_user.following.values_list('user_id', flat=True) following_user_objects = [] … -
Not allowed to load local resource error when trying to add custom CSS stylesheet to HTML document
I am writing a project with Django, Bootstrap, HTML and CSS. The code I found provided a bootstrap stylesheet. When I run the program on developer server 127.0.0.1:8000 the bootstrap styles are applied. I am trying to add a stylesheet to my HTML file with custom styles. I am receiving a "Not allowed to load local resource: file:///C:/Users/Keith/OneDrive/DjangoProjects/django_forms/myapp/templates/formstyles.css" in the Chrome console when I try to run the project. form.html \\ {% load crispy_forms_tags %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"> <!-- <link rel="stylesheet" href="C:/Users/Keith/OneDrive/DjangoProjects/bootstrap-5.0.2-dist/bootstrap-5.0.2-dist/css/bootstrap.min.css"> --> <link rel="stylesheet" type="text/css" href="C:\Users\Keith\OneDrive\DjangoProjects\django_forms\myapp\templates\formstyles.css"> </head> <body style="padding: 20px;"> {% crispy form form.helper %} </body> </html> \\ Custom CSS style sheet formstyles.css \\ input { `color: #683aa4 !important; `margin-top: 100px !important; `} \\ the HTML file and CSS file are in the same directory thank you, -
python script load file via post on django
I'm testing this script to load a document to a webpage in django The GET and POST request return 200 but the file is not loaded. If the answers are 200 why don't load the file I'm doing wrong? code: import requests url='http://localhost:8000/' files = {"docfile": open('test.txt', "rb")} s = requests.Session() resp1 = s.get(url) print(resp1.text) csrf_token = resp1.cookies['csrftoken'] resp2 = s.post(url, data={'csrfmiddlewaretoken': csrf_token,"file":files}) print(resp2.text) resp POST: This is the message from the POST request. <ul class="errorlist"><li>This field is required.</li></ul> -
Can't change font-family in main.css
Currently using Django with bootstrap 4. For whatever reason, I cannot get the font-family to change through my main.css file. I can change other attributes, but font does not seem to work. If I change the font-family in my other files, it works. I just cannot change it through my main.css. What am I doing wrong? base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> ... main.css body { font-family: "Times New Roman", Georgia, serif !important; } -
Django: Find which object a BaseManager or QuerySet comes from
I'm passing BaseManager and QuerySet to a function to perform exclude statements. Can I find out which class the BaseManager comes from? This is to properly give keyword arguments to exclude. The current method only works when called on something from Fragment. class Sampler: @staticmethod def exclude_one(query: BaseManager, element: Union[Fragment, Model]): if isinstance(element, Fragment): return query.exclude(kind=element.kind, number=element.number) elif isinstance(element, Model): return query.exclude(model__name=element.name) Here is models.py. class Fragment(models.Model): kind = models.CharField(max_length=50) number = models.IntegerField(blank=True, null=True) model = models.ForeignKey('Model', models.DO_NOTHING, db_column='model', blank=True, null=True) unique_id = models.AutoField(primary_key=True, blank=True, null=False, default=0) def __str__(self): return f"{self.model}_{self.kind}{self.number}" class Model(models.Model): name = models.CharField(primary_key=True, blank=True, null=False, max_length=50) classes = models.IntegerField(blank=True, null=True) relations = models.IntegerField(blank=True, null=True) def __str__(self): return self.name -
deploy django + channels to heroku
I'm using python 3.9.1 , django 3.2.5 , redis 5.0.7 and channels 3.0.4 this is my first time using channels so forgive me if this was an easy question for you I'm building a chat app so my app is running locally with no problems at all (windows 10 and wsl 2 with ubuntu 20.04 ) trying to upload to heroku gives me app crached for multiple different reasons after each doc I read and tutorial I tried to follow this is my procfile release: python3 manage.py migrate web: daphne online_chat.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python3 manage.py runworker channel_layer --settings=online_chat.settings -v2 asgi.py import os import django from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from main.routing import websocket_urlpatterns from .wsgi import * os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'online_chat.settings') django.setup() django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ) }) also tried different mixes between # application = get_default_application() django_asgi_app = get_asgi_application() # ASGI_APPLICATION = get_asgi_application() setting.py WSGI_APPLICATION = 'online_chat.wsgi.application' ASGI_APPLICATION = 'online_chat.asgi.application' REDIS_URL = os.environ.get('REDIS_URL', ('127.0.0.1', 6379)) CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [REDIS_URL], } }, } also tried to use asgi_redis but this caused more problems as it … -
TypeError: orderTimelocation() got an unexpected keyword argument 'order'
I have the models order and orderTimelocation. Order has a one to many relationship with orderTimelocation: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField() date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) class orderTimelocation(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='ordertimelocation'), longitude = models.DecimalField(decimal_places=8, max_digits=12) latitude = models.DecimalField(decimal_places=8, max_digits=12) And trying to serialize the order model, that should receive ordertimelocation's. For that I'm using Writable nested serializers, as described on DRF documentation class OrderSerializer(serializers.ModelSerializer): ordertimelocation = orderTimelocationSerializer(many=True) class Meta: model = Order fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation'] def create(self, validated_data): timelocations_data = validated_data.pop('ordertimelocation') order = Order.objects.create(**validated_data) for timelocation_data in timelocations_data: orderTimelocation.objects.create(order=order, **timelocation_data) return order I think my code is similar to the one on the documentation but the following erro happens: Traceback (most recent call last): File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 506, … -
Is there a faster way to use django-taggit?
I am attempting to use django-taggit to tag client images. I didn't notice the problem at first, but things have started to slow way down, now that there are more images to load. Is there a better way to handle this so that it isn't making as many calls to the db? TIA manage_images.html {% for tag in image.tags.all|dictsort:"name" %} <label class="label label-purple" style="font-size: 14px;">{{ tag }}</label> {% endfor %} models.py class Image(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True) image = models.ImageField(null=True, blank=True, upload_to=get_image_upload_path) thumbnail = models.ImageField(null=True, blank=True, upload_to=get_thumbnail_upload_path) filename = models.CharField(max_length=100, null=True, blank=True) width = models.IntegerField(null=True, blank=True) height = models.IntegerField(null=True, blank=True) size = models.IntegerField(null=True, blank=True) active = models.BooleanField(default=0) tags = TaggableManager() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) -
Django Translate Templates String Filter
I have read the documentation and a created a tag <div>{{ site_name|default:_("It works!") }}</div>. In order to translate the "It works!" string, I just configured the django.po file as shown bellow and the translation was successful: msgid "It works!" msgstr "Funciona!" However, trying to translate the "No" string in the index.html, I configured the django.po file as shown bellow and I got no translation: msgid "No" msgstr "Sem" Would anyone point me if I missing any configuration for translating the "No" string in the index.html file. -
Trying to Deploy Django App Through Elastic Beanstalk, Module not found error
I'm trying to deploy a Django application AWS Elastic Beanstalk. I followed this guide: https://medium.com/@justaboutcloud/how-to-deploy-a-django3-application-on-elastic-beanstalk-python3-7-and-amazon-linux-2-bd9b8447b55 but when I attempt to deploy I have a 502 error when I go to the site page, and when I look through the logs the error I have is ModuleNotFoundError: No module named 'django3.wsgi' My code is stored like this: django3 |--- manage.py |--- requirements.txt |--- .ebextensions |--- 01_python.config |--- django3 |--- __init__.py |--- asgi.py |--- settings.py |--- urls.py |--- wsgi.py And my 01_python.config file has: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "django3.settings" "PYTHONPATH": "/var/app/current:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: django3.wsgi:application NumProcesses: 3 NumThreads: 20 My requirements.txt file is asgiref==3.4.1 Django==3.2.5 gunicorn==20.1.0 pytz==2021.1 sqlparse==0.4.1 I'm not sure what I have that is wrong, if someone could help me out that would be great. I've tried messing around with the formatting of the 01_python.config file but nothing is helping fix the issue. -
Assigning a Class for a label in the Django forms
I am trying to add a class for label in a custom django form. I am able to add class to the input but for the labels I have been struggling for a while: Here is the form: class infoForm(ModelForm): class Meta: model = Info fields = ['businessName'] widgets={ 'businessName':forms.TextInput(attrs={"class": 'form-control'}), } labels = { 'businessName': 'Business Name', } Here is the model class Info(models.Model): businessName = models.CharField(max_length=100) My question: How to add the class form-label inside the label of every input? Thank you -
raise validation error if there is two president for the same club?
in my model, I don't want two presidents for the same club. I have 6 clubs so I will have 6 presidents too no more. I'm new to validation I tried to use the clean method but the error won't get raised. my model: class MyUser(AbstractUser): STUDENT = 1 INSTRUCTOR = 2 ADMIN = 3 ROLE_CHOICES = ( (STUDENT, 'student'), (INSTRUCTOR, 'instructor'), (ADMIN, 'admin'), ) club_name = ( (0, 'ISOM'), (1, 'Accounting'), (2, 'PA'), (3, 'Finance'), (4, 'Management & Marketing'), (5, 'Economics'), ) is_president = models.BooleanField(default=False) club_name = models.IntegerField(choices=club_name, default=0, verbose_name='Club/Department') roles = models.PositiveSmallIntegerField(choices=ROLE_CHOICES) the validation I used: def clean(self): club = MyUser.objects.all() president = MyUser.objects.all() try: club.objects.get(club_name__iexact=club_name) president.objects.get(is_president__iexact=is_president) except club.DoesNotExist: return club_name, is_president raise ValidationError(_("A president for this club already existed.")) -
How do fix OperationalError: no such column: "something" in django?
I have a model in models.py called location with a field named "something" and whenever I use the manage.py migrate command after the makemigrations command I get the "django.db.utils.OperationalError: no such column: "something"" error. I've seen other people ask questions like this but none of the answers help me, can someone heko me out -
Running into Redis Connection error when adding a second queue to django-RQ
This issue is most likely because of my misunderstanding of how django-RQ/redis works. I've been using django-rq with great results to run/cache long running processes. However, we're now in a position where we need to split up some of these processes into different queues. The docs make this seem easy enough. However, I get the following error when trying to send a task to the pro queue: Could not resolve a Redis connection I was thinking it was possibly because I'm using the same connection info for both queues, but I've seen other examples that do the same thing (https://newbedev.com/how-to-create-multiple-workers-in-python-rq). Where did I go wrong? (I included the local and heroku settings as the same issue exists in both). if(on_heroku): RQ_QUEUES = { 'default': { 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku 'DEFAULT_TIMEOUT': 500, }, 'pro': { 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku 'DEFAULT_TIMEOUT': 500, } } else: RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'DEFAULT_TIMEOUT': 500, }, 'pro': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'DEFAULT_TIMEOUT': 500, } } -
Listen to mqtt topics with django channels and celery
I would like a way to integrate django with mqtt and for that the first thing that came in my mind was using django-channels and an mqtt broker that supports mqtt over web sockets, so I could communicate directly between the broker and django-channels. However, I did not found a way to start a websocket client from django, and acording to this link it's not possible. Since I'm also starting to study task queues I wonder if it would be a good practice to start an mqtt client using paho-mqtt and then run that in a separate process using celery. This process would then forward the messages receives by the broker to django channels through websockets, this way I could also communicate with the client process, to publish data or stop the mqtt client when needed, and all that directly from django. I'm a little skeptical about this idea since I also read that process run in celery should not take too long to complete, and in this case that's exactly what I want to do. So my question is, how much of a bad idea that is? Is there any other option to directly integrate django with mqtt? *Note: … -
Add a download functionality in django change view
I already added a button alongside the save buttons for my django change view: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block submit_buttons_bottom %} <div class="submit-row"> <input type="submit" value="Download" id="download_profile" name="_continue"> <input type="submit" value="{% trans 'Save' %}" class="default" name="_save"> <input type="submit" value="{% trans 'Save and add another' %}" name="_addanother"> <input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue"> <!-- inmport script --> <script src="{% static '/js/downloadData.js' %}"></script> <script src="{% static '/js/collapsibleSection.js' %}"></script> <script src="{% static '/js/investmentAdminScript.js' %}"></script> {% endblock %} and I already started adding the script to retrieve individual data per row to download them. 'use strict'; window.addEventListener('load', () => { const downloadButton = document.querySelector('#download_profile'); downloadButton.addEventListener('click', e => { if (!confirm('Data will be saved before downloading. Are you sure you want to continue?')) { e.preventDefault(); return; } // get module const fieldsets = document.querySelectorAll('fieldset'); fieldsets.forEach(thisFieldset => { const dataRows = thisFieldset.querySelectorAll('.form-row'); dataRows.forEach(dataRow => { // retrieve each input field and add a download to .xlsx function }); }); }); }); However, it gets complicated very fast. Is there a better way to do this? -
Django Rest Framework Serializing Custom Field
I am trying to serialize a custom field that is not on my model. The queryset code groups the model on the item1 field and generates a count column. There is no count field on my Data model. views.py class GetDataGroups(generics.ListAPIView): serializer_class = DataSerializer def get_queryset(self): queryset = ( Data.objects.values("item1") .annotate(count=Count("item1")) .order_by() ) return queryset serializers.py class DataSerializer(serializers.ModelSerializer): count = serializers.CharField(write_only=True) class Meta: model = Data fields = ["item1", "count"] How do I also get the count field to show up in my rest api? -
django restrict value to a foreign key of a foreign key
I have three models Address: Representing an address Itinerary: Representing a set of addresses. It has ManyToManyField relation with Address Appointment: Representing Address within the itinerary. It has a Foreign key to Itinerary and a Foreign Key to Address. What I am trying to understand is what's the best way to establish a relationship between Appointments and Itinerary/Address so that when selecting an address for an appointment, users can only chose among the addresses associated with the Itinerary to which the appointment is associated. Basically I am trying to limit the choices of the field app_location within the Appointment model to only have as selection-able options Address present in the location field of Itinerary model (associated with appointment) class Address(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) address1 = models.CharField("Address line 1", max_length=1024,) zip_code = models.CharField("ZIP / Postal code", max_length=12, blank=True, null=True) class Itinerary(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=40) location=models.ManyToManyField(Address, related_name='location') class Appointment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) app_location=models.CharField(max_length=20) contact=models.ForeignKey(Contact, on_delete=models.CASCADE, blank=True, null=True) itinerary=models.ForeignKey(Itinerary, on_delete=models.CASCADE, blank=True, null=True)