Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In-page JS search not working in some pages
I'm using a simple JS in-page search on my Django web application. The problem is that it isn't working in some of the views for some reason. It works on the template created by GameListView but it doesn't work on the template created by GameListViewByDist. I'm not sure if it's relevant but both views are rendered on game_list.html which extends from base.html where the navbar search field is. Since both view codes are much alike i'm having a hard time finding the error. I appreciate any help. **HTML** **BASE.HTML** <nav> <input id="searchbox" type="search" placeholder="Search"> </nav> **JS** let type_timer; let type_interval = 300; let search_input = document.getElementById('searchbox'); search_input.addEventListener('keyup', () =>{ clearTimeout(type_timer); type_timer = setTimeout(liveSearch, type_interval); }); function liveSearch(){ let cards = document.querySelectorAll('.game_card'); let search_query = document.getElementById("searchbox").value; // SHOW MATCHES AND HIDE THE REST for (var i = 0; i < cards.length; i++){ if(cards[i].innerText.toLowerCase().includes(search_query.toLowerCase())){ cards[i].classList.remove("is_hidden"); } else{ cards[i].classList.add("is_hidden"); } } } **VIEWS.PY** class GameListView(SortableListMixin, ListView): sort_fields = [('name'), ('purchase_date')] model = models.Game ordering = ['-purchase_date'] def get_context_data(self, **kwargs): context = super(GameListView, self).get_context_data(**kwargs) context.update({ 'tag_list': models.Tag.objects.all(), }) return context class GameListViewByDist(ListView): def get_queryset(self): self.distributor = get_object_or_404(models.Distributor, pk=self.kwargs['distributor']) return models.Game.objects.filter(gamestatus__distributor=self.distributor) def get_context_data(self, **kwargs): context = super(GameListViewByDist, self).get_context_data(**kwargs) context.update({ 'tag_list': models.Tag.objects.all(), }) return context -
Retrieve only the courses that the user has created
I am trying to get only the courses that the user has created to be listed out when the user wanted to create a quiz. So that the user could create a quiz for a particular course that the user has created. However, now I all the courses that are is my database are being listed out. I am not sure how to get only the courses that the user has created to be listed. Please help me out. models.py class Course(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) media = models.ImageField(upload_to = 'media/course') title = models.CharField(max_length=300, null = False) subtitle = models.CharField(max_length=500, null = False) description = models.CharField(max_length=5000, null = False) language = models.CharField(max_length=20, null = False, choices=LANGUAGE) level = models.CharField(max_length=20, null = False, choices=LEVEL) category = models.CharField(max_length=30, null = False, choices=CATEGORY) subcategory = models.CharField(max_length=20, null = False) price = models.FloatField(null = True) roles_responsibilities = models.CharField(max_length=2500, null = False) timeline_budget = models.CharField(max_length=250, null = False) req_prerequisite = models.CharField(max_length=2500, null = False) certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE) slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True) def __str__(self): return self.title @property def sliceLearn(self): subtitle = self.roles_responsibilities return subtitle.split('.')[:-1] class Quiz(models.Model): user = models.ForeignKey(Users, on_delete = models.CASCADE) title = models.CharField(max_length=300, null = False) … -
Changing the default class for Bootstrap Crispy Form
I am using Crispy Forms with Bootstrap4. Currently, all the input fields are rendered with form-control class. I want to add form-control-lg to the input fields. I have tried the following but it is not working forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'first_name', 'last_name'] help_texts = { 'username': None, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['password1'].help_text = None self.fields['password2'].help_text = None self.fields['password2'].label = "Confirm Password" self.helper = FormHelper() self.helper.layout = Layout( Field( 'username', css_class="form-control form-control-lg my-custom-class" ) ) Template <div class="content-section"> <form method="POST" action=""> <h3>Sign Up</h3> <hr> {% csrf_token %} {{ form | crispy }} </br> <button type="submit" class="btn btn-primary">Sign Up</button> </form> </div> Also, can I modify the class globally for all input fields? -
Django REST Framework Token Auth request.user returns empty
I'm trying to create a REST API which inserts an ID inside a favorites many to many model. But when I try to get the request.user it returns empty. Im using the TokenAuth method and I send the key inside the Authentication header. Here you see my Viewset. The ["favorites"] is send inside the body of the POST request. class FavoriteViewSet(view sets.ModelViewSet): queryset = Profile.objects.all() serializer_class = FavoriteSerializer permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] def post(self): data = request.data profile = Profile.objects.get(user=self.request.user) profile.favorites.add(data["favorites"] return Response(status=status.HTTP_201_CREATED) My serializer: class FavoriteSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' depth = 1 My Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Receipt) def __str__(self): return self.id My Error: IntegrityError at /v1/favorites/ (1048, "Column 'user_id' cannot be null") -
Best approach at multiple node types in MPTT model
just looking to get some feedback as I attempt to increase the efficiency of my models. I am using MPTT to build a hieratical content that can support multiple content types within the tree. The initial approach that I took was to create a node model with a Generic relationship and separate models of node types with a Generic relation to the node model. I've seen mixed feelings regarding GenericForeignKey and I am experiencing the added work of these relationships not being natively supported by Django. Such as needing to manually associate the nodes, needing to manually check the content of the node, etc. This manner also results in additional queries to the database. Is there a different approach to this? I been trying to model out creating a Node model, and inherit different Node types however, if each model had a TreeForeignKey, they'd also be able to only reference their own model without a GenericForeignKey My models are currently built as so. class StoryNode(MPTTModel): story = models.ForeignKey(Story, on_delete=models.RESTRICT, null=True, related_name='storynodes') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') ending_node = models.BooleanField(default=False) limit = models.Q(app_label='core', model='storytext') | models.Q(app_label='core', model='storyaction') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to=limit) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey('content_type', … -
How to put Pytesseract OCR on the web
I am using Pytesseract OCR for text detection and I am using a jupyter notebook to run it right now so the output is just popping up as another window. My output for the program is an image and I was wondering if there is a way to use flask or django or something to put my program on a website. I am trying to allow the user to input their own image and then the program will output another image on the website. This is the main code: def pytess(img): hImg,wImg,_ = img.shape boxes = pytesseract.image_to_boxes(img) for b in boxes.splitlines(): print(b[0]) b = b.split(' ') x,y,w,h= int(b[1]),int(b[2]),int(b[3]),int(b[4]) cv2.rectangle(img,(x,hImg-y),(w,hImg-h),(0,0,255), 2) cv2.putText(img,b[0],(x,hImg-y+25), cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2) ##Detecting Words hImg,wImg,_ = img.shape boxes = pytesseract.image_to_data(img) for x,b in enumerate(boxes.splitlines()): if x!=0: b = b.split() if len(b)==12: x,y,w,h= int(b[6]),int(b[7]),int(b[8]),int(b[9]) cv2.rectangle(img,(x,y),(w+x,h+y),(0,0,255), 2) cv2.putText(img,b[11],(x,y), cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2) cv2.imshow("Result",img) cv2.waitKey(0) pytess(img) -
(Django) Primary key is not applied
I set the restaurant_id column as pk as below, but when I try to insert data on the admin page the restaurant_id column in the menu table shows name data in the restaurant table. Why does this happen? class Restaurant(models.Model): restaurant_id = models.AutoField(primary_key=True) photo = models.ImageField(upload_to="images/") name = models.CharField(max_length=50) phone = models.CharField(max_length=15) hours = models.CharField(max_length=100) website = models.URLField(max_length=200) country = models.CharField(max_length=20, default='country') def __str__(self): return self.name class Menu(models.Model): restaurant_id = models.ForeignKey(Restaurant, on_delete=models.CASCADE) item = models.CharField(max_length=100) price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.item -
Does Django have an equivlant to ruby on rails "rails db:create"?
I've been searching on google about this but everyone is saying Django lacks this feature. I should not have to manually create the initial database in PGAdmin or something similar just to start development. What is the django equivalent of rails db:create? -
Page not found at/admin
I'm a very beginner. When I tried to go visit this (http://127.0.0.1:8000/admin), I couldn't. Here have shown page not found. What can be the solution? -
how to edit views.py in django when installed in ubuntu server
I installed Django in ubuntu server ,when I connect t my public server:8080 I got Django installed, now how to edit urls.py file or tests.py in server, should I use WinSCP or is there any graphical option to edit files in server to modify Django website -
please help i dont understand
hi please help me i created a createview class in my app and then i put a post method and then it gives me this error: 'Register' object has no attribute 'object' class Register(CreateView): form_class = RegForm model = Users template_name = 'registro.html' success_url = '/home/' def get_form(self, form_class=RegForm): if form_class is RegForm: form_class = self.get_form_class() return form_class(**self.get_form_kwargs()) def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): name = form.cleaned_data['name'] Flastname = form.cleaned_data['Fatherslname'] Mlastname = form.cleaned_data['Motherslname'] age = form.cleaned_data['age'] return self.form_valid(form) else: return self.form_invalid(form) and this is my forms i dont know why: class RegForm(ModelForm): class Meta: model = Users fields = ['name', 'lname1'] Name = forms.CharField(label="Nombre", max_length=100, required=False) Fatherslname = forms.CharField(max_length=100, required=False) Motherslname = forms.CharField(max_length=100, required=True) age = forms.IntegerField() UserName = forms.CharField(required=True, max_length=80) userType = forms.ChoiceField(label="Eres?", choices=users) birthplace = forms.ChoiceField(label="Pais", choices=Paises) dateOfBirth = forms.DateField(label="Fecha de Nacimiento", initial=datetime.date.today) imagen = forms.ImageField(label="foto") Email = forms.EmailField(required=True) passwd = forms.CharField(label="contraseña", max_length=32, widget=forms.PasswordInput) ConfPasswd = forms.CharField(label="confirmar contraseña", max_length=100, widget=forms.PasswordInput) -
WebSocket not connecting |. Django Channels | WebSocket
I am using the WebsocketConsumer consumer and when I disconnect the websocket connection it gives the below error. Also when I have already one open connection and when I try to create a connection with the same route it gets Disconnected and gives the same Application instance <Task pending name='Task-5' coro=<StaticFilesWrapper.__call__() running at /Volumes/Data/Projects/LocoNav-LM/vt-lm-server/venv/lib/python3.8/site-packages/channels/staticfiles.py:44> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/futures.py:360, <TaskWakeupMethWrapper object at 0x1076a2580>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 54789] path=b'/ws/users/'> took too long to shut down and was killed. My code:- class TestMultipleUsers(WebsocketConsumer): def connect(self): logging.info('connecting....') self.accept() redis_client = RedisClient(host='localhost', port=6379, db=0) redis_client.subscribe_and_listen() redis_client.subscribe_channel('test') for message in redis_client.sub.listen(): if message is not None and isinstance(message, dict): print(message) self.send(text_data="1") def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) def disconnect(self, close_code): logging.info('disconnecting....') logging.info(close_code) However, whenever I disconnect the web socket from Postman the disconnect method never gets called. requirements.txt channels==3.0.4 Django==4.0 celery==5.2.3 -
Django How to find context data in form_valid when it is not part of the form
I have a forms.Form that just displays a ModelMultipleChoiceField and returns the choice. In the template that holds that form I display the patient information. I obtain that information in get_context_data but I cannot access any patient information once I am in form_valid. The form.cleaned_data only includes the choice from the Form. I need the information from the context to create the necessary table rows using the choice data. class OrderTestsView(FormView): """ """ model = Universal_Test_File form_class = TestOrderForm success_url = '/list_tests/' template_name = "lab/order_tests.html" def get_context_data(self, *args, **kwargs): patient = get_object_or_404(Patient, pk=self.kwargs['pk']) context = super(OrderTestsView, self).get_context_data(**kwargs) context['patient'] = patient return context ### I need to build tables using patient inforamtion along with the choice right here ### but that information, which I have in get_context_data can't be accessed from here def form_valid(self, form): choice = form.cleaned_data.get("choice") if choice: for test in choice: print(test.service_id, test.test_name) return super().form_valid(form) class TestOrderForm(forms.Form): choice = forms.ModelMultipleChoiceField( Universal_Test_File.objects.all().order_by('test_name'), to_field_name="service_id") -
Django admin looks fine, untill I open category. Then overlapping
I have a pretty basic django install, with summernote. When I'm in the admin panel, it looks like so. But when I go to any of the category pages, it looks like this. I tried clearing cache, but still looks the same. Any help would be appreciated. EDIT: My models code is from django.db import models from django.contrib.auth.models import User from django.utils import timezone import uuid STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="blog_posts" ) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("post_detail", kwargs={"slug": str(self.slug)}) def get_previous_by_created_on_active(self): return self.get_previous_by_created_on(status=1) def get_next_by_created_on_active(self): return self.get_next_by_created_on(status=1) class Newsletter(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(null=False, blank=True, max_length=200, unique=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" -
Using DRF to update the whole of an object, including nested object
If I have models that look roughly like this:- class Event(models.Model): title = models.CharField(max_length=200) venue = models.ForeignKey(Venue, on_delete=models.PROTECT) class Venue(models.Model): # all of this information comes from the Google Places API place_id = models.CharField(max_length=200) name = models.CharField(max_length=200) address = models.TextField() and I want to be able to update the venue name of an existing event using Django Rest Framework, it looks like I have to write an update() method for my model serializer. I've written it like this:- class EventSerializer(serializers.ModelSerializer): venue = VenueSerializer() class Meta: model = Event fields = ["title", "venue"] def update(self, instance, validated_data): venue_data = validated_data.pop("venue", None) event = super().update(instance, validated_data) if venue_data: venue, _ = Venue.objects.get_or_create( place_id=venue_data["place_id"], defaults={ "name": venue_data["name"], "address": venue_data["address"] }, ) event.venue = venue event.save() return event Does that look like I'm going in the right direction here? I don't want to create a new venue every time someone updates an event - if the place ID is the same as an existing one, I want to reuse it. This code looks a bit cumbersome to me (I've got some very similar looking code in the create() method of the serializer) so I'm just worried that there's an easier, more concise way to … -
Can someone help me with this error (its is from manage.py make migrations):
Click here to see the error it really helps I am new to this, please someone help -
django.db.utils.OperationalError: near "CASCADE": syntax error when making a pull request in Github
I'm trying to deploy a django website with Heroku. When I run python3 manage.py runserver, everything works normally. But when I push it to github and make a pull request, I have an action that tests my code and I run into that error. Using existing test database for alias 'default'... Found 7 test(s). System check identified no issues (0 silenced). ....... Alicia ---------------------------------------------------------------------- Tiffany Barbara Ran 7 tests in 1.319s OK Taylor Dr. Wanda Jacob Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 414, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: near "CASCADE": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/core/management/commands/test.py", line 59, in handle failures = test_runner.run_tests(test_labels) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django/test/runner.py", line 941, in run_tests self.teardown_databases(old_config) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django_on_heroku/core.py", line 33, in teardown_databases self._wipe_tables(connection) File "/opt/hostedtoolcache/Python/3.8.10/x64/lib/python3.8/site-packages/django_on_heroku/core.py", line 27, in … -
Print button in Django Admin
How to add print button into the Django admin panel, which prints only selected items of the model? my model.py class Student(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) class StudentAdmin( SimpleHistoryAdmin): list_display = ('id', 'name', 'lastname') list_filter = ('lastname',) search_fields = ['name', 'lastname'] history_list_display = ('name', 'lastname') def changed_fields(self, obj): fields = '' if obj.prev_record: delta = obj.diff_against(obj.prev_record) for change in delta.changes: fields += str("{} changed from {} to {} >>> ".format(change.field, change.old, change.new)) return fields return None my admin.py from django.contrib import admin from .models import * admin.site.register(Student, StudentAdmin) -
How can I build a user wallet application in Django?
I want users to be able to pay for goods and services on my Django site using site wallet credits -
How to display GeoJSON on Cesium
I've a Django app that lets you run a spatial query and displays the result in the form of a GeoJSON polygon on a Leaflet map. Here's how I did it on Leaflet: I took the geometry that's stored in the geo_json object in the views.py file, then I added that in the Leaflet map in the geometry.html file through L.geoJSON({{ geo_json | safe }}).addTo(map);. views.py def GetGeometry(request, *args, **kwargs): try: x = request.GET.get('x') y = request.GET.get('y') connection = psycopg2.connect(database="xxx",user="xxx", password="xxx", host="xxx") cursor = connection.cursor() cursor.execute("SELECT xxx From xxx WHERE ST_Intersects(ST_PointFromText('POINT({} {})',4326), geom);".format(x, y)) result=cursor.fetchone() geo_json={ "type": "Feature", "geometry": json.loads(result) } return render(request ,'results/geometry.html', {'geo_json': geo_json }) except: return render(request ,'results/geometry.html') geometry.html {% extends "base.html" %} {% block content %} {% load static %} {% load leaflet_tags %} {% leaflet_js %} {% leaflet_css %} <link rel="stylesheet" type="text/css" href="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.css' %}"> <script type="text/javascript" src="{% static 'leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.js' %}" ></script> <style type="text/css"> #gis {width: 100%;height:980px;} </style> <script type="text/javascript"> function our_layers(map,options){ var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{ maxZoom: 20, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }); var baseLayers = { "OSM": osm, }; L.control.groupedLayers(baseLayers).addTo(map); L.geoJSON({{ geo_json | safe }}).addTo(map); map.fitBounds(L.geoJSON({{ geo_json | safe }}).getBounds(), {maxZoom: 19}); } </script> {% leaflet_map "gis" callback="window.our_layers" %} {% endblock content %} … -
How to set `null=True` for a field using `label_from_instance`?
I am trying to set null=True and blank=True for a field using label_from_instance. But it cannot be set by defining a field in the model class. If I try to set it like the code below, I get an error. fk_id = NameChoiceField(queryset=PkModel.objects.all().order_by('pk_name').distinct(), null=True, blank=True) TypeError: init() got an unexpected keyword argument 'null' How could I set null and blank in this case? Here are the codes: forms.py from django import forms from django.forms import ModelChoiceField from .models import * class NameChoiceField(ModelChoiceField): def label_from_instance(self, obj): return f'{obj.pk_name}' class IndexForm(forms.ModelForm): fk_id = NameChoiceField(queryset=PkModel.objects.all().order_by('pk_name').distinct()) class Meta: model = FkModel fields = '__all__' models.py from django.db import models class PkModel(models.Model): pk_id = models.IntegerField(verbose_name='pk_id',primary_key=True) pk_name = models.CharField(max_length=20, verbose_name='pk_name') class Meta: verbose_name_plural = 'PkModel' class FkModel(models.Model): fk_code = models.CharField(max_length=20, verbose_name='fk_code', primary_key=True) fk_id = models.ForeignKey(PkModel, to_field='pk_id', db_column='fk_id', verbose_name='fk_id', on_delete=models.CASCADE, null=True, blank=True) class Meta: verbose_name_plural = 'FkModel' Python 3.8 Django 3.2 -
Python django model object showing None and null in template
I have this table. class MyTable(BaseModel): key = m.CharField(max_length=20,null=False,unique=True) pre_json = m.JSONField(blank=True, null=True) post_json = m.JSONField(blank=True, null=True) And I use this model through ListView/UpdateView in list html template {{obj.pre_json}} in edit html template {% render_field form.pre_json class="form-control" %} Upper one shows None in template Lower one shows null in textarea as placeholder. Why this two are shown? or can I erase these? I want to stop this -
CSV Getting decoded in wrong format in Django
I am trying to read a csv file located in AWS S3 Bucket using DefualtStorage. from django.core.files.storage import DefaultStorage def upload_file_view(request): form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm() print(Csv.objects.all()[1]) obj = Csv.objects.all()[1] with storage.open("{}".format(Csv.objects.all()[1].file_name), 'rb') as f: reader = csv.reader(f.read().decode('utf-8')) for row in reader: print(row) However the row is getting printed with each word on a different line ['U'] ['s'] ['e'] ['r'] ['n'] ['a'] ['m'] ['e'] ['', ''] [' '] ['N'] ['a'] ['m'] ['e'] How am I supposed to fix this? -
Add urls to django rest swagger
I have a django rest swagger In urls.py I have something like this router = routers.DefaultRouter() router.register('', ProductListView, basename='product-list') schema_view = get_swagger_view(title="Star Shop") urlpatterns = [ path('admin/', admin.site.urls), path('api/', schema_view), path('api/', include(router.urls)) ] I'm trying to include in swagger API for products Can someone help me please -
What are the best practices to consume Kafka messages in Django
I am working on an IoT project that uses MQTT protocol to transport the sensor data from embedded devices to an App. For this i have created, A MQTT broker to send the data from the device. A custom bridge that push data from MQTT broker to my Kafka broker Django server to push the messages via websocket to the App Right now, What i need is to consume the Kafka messages from django, save to the DB and then push this data to client via websockets. But i don't have much idea regarding how to consume Kafka messages from Django. So far the solution in my mind is using custom management command, start a kafka consumer, push the data to DB and then to websockets. Is this a good approach? If not, what would be a good solution to solve this?