Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
creates a binary or combination of all attributes
I want to create a query that creates a binary or combination of attributes. For example, I have the following class class foo(models.Model): m_person= models.ForeignKey('Person', on_delete=models.CASCADE) m_rang = models.ForeignKey('Rang', on_delete=models.CASCADE) m_a = models.BooleanField(default=True, name='a') m_b = models.BooleanField(default=False, name='b') m_c = models.BooleanField(default=False, name='c') m_d = models.BooleanField(default=False, name='d') ... I am currently reading this class as follows: obj = foo.objects.all().first() attributes = [i for i in dir(obj) if i.startswith('m_')] for tag in attributes: if hasattr(foo, tag.__name__): t = foo.objects.filter(person_id=aperson.pk, rang=arang).values_list(tag.__name__, flat=True) if True in t: do somthing So I run through all the instances that match the person and the rank to then check the attribute. I bet it's somehow more intelligent in combination. I would actually like to read a combined "or" class from the database in order to process it further. instead of questioning each attribute individually... since I need a or link, you could use first(value = true) somehow. my wish would be something like this: f = foo.objects.filter(person_id=aperson.pk, rang=arang).OR() where the attributes then combine into something like this: f.m_a = foo[0].m_a | foo[1].m_a | foo[2].m_a... f.m_b = foo[0].m_b | foo[1].m_b | foo[2].m_b... f.m_c = foo[0].m_c | foo[1].m_c | foo[2].m_c... f.m_d = foo[0].m_d | foo[1].m_d | foo[2].m_d... ... with: … -
Django & ajax when you click on the span to open select, the page will refresh
I am looking for a solution to send the form when you click on the span to open select, the page will refresh <span id="update-button" data-index="{{product.id}}"> <label for="select{{ product.id }}"></label> <select id="select{{ product.id }}" > <option value="" selected disabled hidden>{{ item.qty }}</option> <option value="">1</option> <option value="">2</option> <option value="">3</option> <option value="">4</option> </select> </span> thanks for helping you guys -
Django: How to add button to the object creation page?
I have the following models: from django.db import models class Teacher(models.Model): name = models.fields.CharField(max_length=255) favorite_student = models.ForeignKey("Student", blank=True, null=True, on_delete=models.RESTRICT, related_name="+") class Student(models.Model): name = models.fields.CharField(max_length=255) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) def set_as_favorite_student(self): self.teacher.favorite_student = self I've also registered both Teacher and Student in the admin page: from .models import Teacher, Student class TeacherAdmin(admin.ModelAdmin): list_display = ( "id", "name", "favorite_student", ) class StudentAdmin(admin.ModelAdmin): list_display = ( "id", "name", "teacher", ) Each teacher must have a favorite student. So when there is a new teacher, I do the following steps: Go to django admin page Create a teacher Create a student Go back to the teacher, and set favorite_student to the created student Question: For step #3, how do I create a button next to existing buttons that is Save and set as favorite so that I can avoid step #4? -
Django 4.0 wildcard subdomain preventing from setting csrf token
I'm having a problem with Django 4.0 backend in debug mode where I use session auth with csrf token. I use wildcard subdomains: CSRF_TRUSTED_ORIGINS = ["http://*.local.lab:8080"] ALLOWED_HOSTS = [".local.lab"] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE = False SESSION_COOKIE_HTTPONLY = True When I'm accessing app on http://local.lab:8080 CSRF token is being sent and set in browser storage, all works as intended. When I'm accessing app with any other URL combination i.e. http://www.local.lab:8080 or http://subdomain.local.lab:8080 CSRF request comes back with the correct cookie but the cookie is never set in a browsers storage and that prevents me from creating x-csrf token and making any post requests. Everything I'm testing on local domain where I mapped my local IP to the domain local.lab with help of the tool dnsmasq. What am I doing wrong in here? -
How to deserialize an array of primary keys with Django Rest Framework PrimaryKeyRelatedField
I followed the docs when setting up my serializer. class PlaylistSerializer(serializers.ModelSerializer): songs = serializers.PrimaryKeyRelatedField(queryset=Song.objects.all(), many=True, allow_empty=True, required=False) class Meta: model = Playlist fields = ['id', 'name', 'songs', 'created_at'] If I add a few songs to the playlist in the django admin and send a get request, I get the result I want. { "id": 4, "name": "teszt3", "songs": [ 351, 350 ], "created_at": "2022-01-14T14:04:36.238350Z" } But I want to create or update a playlist with a similar list of primary keys of songs. If I send a POST request with this body: { "name": "test2", "songs": [350, 351] } I get this error: Incorrect type. Expected pk value, received str If there's only one number (primary key) in the songs field, it works, but I want to create playlists with many songs at once. Is there a way to parse that array, or how could I solve this? -
Django user authentication with case insensitive username
I'm completing my first project in Django, I'm still struggling when I need to find documentation about the problem that I cannot manage to solve, then I thought to post a question here. In my django project I installed the app "users" for the authentication, I have the following views.py in the folder "users": from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import UserCreationForm def register(request): """Register a new user:""" if request.method != 'POST': # Display blank reigistration form. form = UserCreationForm() else: # Process completed form. form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() # Log the user in and then redirect to home page. login(request, new_user) return redirect('learning_journals:index') # Display a blank or invalid form context = {'form':form} return render(request, 'registration/register.html', context) Models.py is empty at the moment. Everything is perfect and everything works well, both the form and the backend. Users can access with no problem. When a user signs in, is obliged to use a case sensitive username. I would like the user to be able to log in with a case insensitive username, but I have no idea how to start and make this possible. Thank you very much in advance for … -
How to serialize a django model and keep new lines?
I am trying to serialize a django model to store any changes made. I have to convert some of the values to a string in order to avoid errors. Here's what I have so far: associated_objects = {"parts":{}} for item_part in item_parts: part = Part.objects.get(id=item_part.part.id) part_name = part.part_name part = part.__dict__ keys_values = part.items() part = {key: str(value) for key, value in keys_values} part = json.dumps(part, indent=4) associated_objects['parts'][f'{part_name}'] = part record = Record.objects.create(associated_objects=associated_objects) record.save() This saves to a model named record that has a TextField() named associated_objects. I have to convert the values to a string in order to avoid errors caused by ImageField() objects in the part model. Here's what I end up getting: {'parts': {'battery': '{\n "id": "37",\n "created_date": "2022-01-12 20:55:44.980636+00:00",\n "created_by_id": "1",\n "part_name": "battery",\n "part_no": "BATTERY",\n "alt_part_no": "None",\n "description": "test_description.",\n "qty": "99",\n "reorder_qty": "5",\n "cost": "45.0",\n "side": "1",\n "row": "1",\n "column": "1",\n "warranty": "None",\n "vendor_id": "4",\n "alt_vendor_id": "None",\n "category_id": "10",\n "img": "images/parts/battery.jpg",\n "barcode": "barcodes/parts/BATTERY_barcode.jpeg",\n "updated_date": "2022-01-13 18:42:30.818788+00:00",\n "updated_by_id": "1",\n }'}} Unfortunately, it turns the dictionary into a string, so the \n are ignored. What I need is: {'parts': {'battery': { "id": "37", "created_date": "2022-01-12 20:55:44.980636+00:00", "created_by_id": "1", "part_name": "battery", ... } } } -
How to pass kwargs from django Fixture to django Signal
I need to pass the extra parameter from Django fixture to Django pre_save signal. I tried couple of ways but unable to do so. Django Fixture: [ { "model": "club_courses.Country", "pk": 1, "is_created": "False", // This is the extra paramter that I need in the django signal "fields": { "code": "PK", "name": "Pakistan" } } ] Django Signal: @receiver(pre_save, sender=Country) def populate_dates(sender, instance, *args, **kwargs): if kwargs['raw']: instance.updated_at = timezone.now() instance.created_at = timezone.now() Any help would be highly appreciated. Thanks. -
adding form attribute to inputfield
I am trying to achieve submitting a form with input fields being outside of the form (see here). Therefore I want to add the form="" attribute to my inputfields, as described here: class TestForm(forms.Form): class Meta: model = Product fields = ["number"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) self.fields["number"].widget.attrs.update({"class": "form-control w-50"}) ## works self.fields["number"].widget.attrs.update({"form": "testformid"}) ## does not work in the template the inputfield renders as: <input type="number" name="number" value="8" class="form-control w-50" required="" id="id_number"> how can I add the form="..." correctly? -
Django redirect to view with kwarg not working
My goal is to redirect the client to the chat session detail view if they are trying to open a new chat session with someone they already have a chat session with. Everything works fine but when I tried to open a duplicate chat session, it didnt get redirected and all what i got is a blank json response //views.py class ChatSessionListView(generics.ListCreateAPIView): serializer_class = ChatSessionSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return ChatSession.objects.filter(Q(initiator=self.request.user) | Q(receiver=self.request.user)) def perform_create(self, serializer): receiver_username = self.request.data['username'] receiver = get_object_or_404(User, username=receiver_username) chat_session = ChatSession.objects.filter(Q(initiator=self.request.user, receiver=receiver) | Q(initiator=receiver, receiver=self.request.user)) if chat_session.exists(): return redirect('v1:chat:chat_session_detail', session_id=chat_session[0].pk) else: serializer.save(initiator=self.request.user, receiver=receiver) // urls.py urlpatterns = [ path('', views.ChatSessionListView.as_view(), name='chat'), path('<str:session_id>/', views.ChatSessionDetailView.as_view(), name='chat_session_detail') ] -
Django cumulative sum in model (sqlite)
My model is: class transaction(models.Model): transactiondate = models.DateField() category = models.ForeignKey(category, on_delete=models.PROTECT, default=0) details = models.CharField(max_length=200, null=True) amount = models.DecimalField(decimal_places=2, max_digits=10) accountid = models.ForeignKey(account, on_delete=models.PROTECT) And I'm getting a cumulative total for each date using a raw SQL query: def cumulativebalance(): query = """SELECT id, transactiondate, SUM("amount") OVER (ORDER BY transactiondate) AS "cumsum" FROM "transactions_transaction" GROUP BY transactiondate ORDER BY transactiondate ASC, "cumsum" ASC """ return balance = transaction.objects.raw(query) This does return the output I'm looking for. My question is whether there's a way in Django that I can incorporate this into my model instead of having it as raw SQL? What I've tried I did find a previous similar question and I've adapted the answer to my own model: test = transaction.objects.annotate( cumsum=Func( Sum('amount'), template='%(expressions)s OVER (ORDER BY %(order_by)s)', order_by="transactiondate" ) ).values('transactiondate', 'cumsum').order_by('transactiondate', 'cumsum') But this gives me an error: OperationalError at /transactions/ near "OVER": syntax error. I don't understand what this is telling me. The SQL which was generated is shown in the traceback. My best guess is that it should be PARTITION BY after OVER instead of ORDER BY, but I don't know how I could change that from my python code. ('SELECT "transactions_transaction"."transactiondate", ' 'CAST(CAST(SUM("transactions_transaction"."amount") AS … -
IndexError: tuple index out of range - Django
I am getting IndexError: tuple index out of range when trying to do a consult to the DB (Heroku postgres): views.py: def get_total_per_month(request, year): user= User.objects.values("id").filter(username=request.user) query = ( f"SELECT to_char(date_trunc('month', \"move_date\"), 'MM') AS month_number," f" sum( CASE WHEN \"move_id\" = 1 THEN \"move_value\" WHEN \"move_id\" = 2 THEN -\"move_value\" END ) as total" f" FROM move_control WHERE \"user_id\" = {user[0]['id']}" f" AND \"move_date\"::text LIKE '{year}%' GROUP BY month_number" ) # Retrieve data for p in Move.objects.raw(query): print(p) When trying to retrieve de data the following error shows: File "C:\Users\LonxfUser\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) IndexError: tuple index out of range I've tried this query directly from the database and it works, so maybe i'm missing something. I have looked at the documentation of Django but what i've tried didn't work. -
Django view function for navbar included
I have my page only for navigation bar and I include it in base page. Now I have a menu in that navigation bar and links I get from database(that links are my categories). But how can I call my function in views without path, because I don't need to have path for navigation bar? And I need that view function to get data from database. models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() info = models.TextField(default="Informacion a Completar") image = models.ImageField(blank=True) views.py def CategoryView(request): context = { 'items' : Item.objects.all() } return render(request, 'categories_bar.html', context=context) categories_bar.html <li class="nav-item"></li> {% for category in items %} <div> {{ items.category }} </div> {% endfor %} </li> base.html {% include "categories_bar.html" %} -
Returning lists from url in Django
Is there a way how to return lists that are passed in to url as parameters? I've noticed that if a list is passed to a view url then when you access the said passed list in the view via self.kwargs['parameter'] and print it then the result will be ['item', 'item2'] which looks like a list, however the type(self.kwargs['parameter']) will actually be of <'str'> not a <'list'>. The example url that has a list passed looks something like this: http://127.0.0.1:8000/%5B'list_item',%20'another_list_item'%5D/%5B'list_item1',%20'another_list_item1'%5D/ Am I correct in stating that self.kwargs['parameter'] only takes the raw string of the url and does not know what type of data was passed? -
how to give path in pipeline config file?
2022-01-13 15:50:40.558948: W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:39] Overriding allow_growth setting because the TF_FORCE_GPU_ALLOW_GROWTH environment variable is set. Original config value was 0. INFO:tensorflow:Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:GPU:0',) I0113 15:50:40.563051 140140612618112 mirrored_strategy.py:376] Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:GPU:0',) INFO:tensorflow:Maybe overwriting train_steps: None I0113 15:50:40.798899 140140612618112 config_util.py:552] Maybe overwriting train_steps: None INFO:tensorflow:Maybe overwriting use_bfloat16: False I0113 15:50:40.799189 140140612618112 config_util.py:552] Maybe overwriting use_bfloat16: False WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/object_detection-0.1-py3.7.egg/object_detection/model_lib_v2.py:526: StrategyBase.experimental_distribute_datasets_from_function (from tensorflow.python.distribute.distribute_lib) is deprecated and will be removed in a future version. Instructions for updating: rename to distribute_datasets_from_function W0113 15:50:40.848803 140140612618112 deprecation.py:347] From /usr/local/lib/python3.7/dist-packages/object_detection-0.1-py3.7.egg/object_detection/model_lib_v2.py:526: StrategyBase.experimental_distribute_datasets_from_function (from tensorflow.python.distribute.distribute_lib) is deprecated and will be removed in a future version. Instructions for updating: rename to distribute_datasets_from_function Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/object_detection-0.1-py3.7.egg/object_detection/utils/label_map_util.py", line 159, in load_labelmap text_format.Merge(label_map_string, label_map) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 735, in Merge allow_unknown_field=allow_unknown_field) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 803, in MergeLines return parser.MergeLines(lines, message) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 828, in MergeLines self._ParseOrMerge(lines, message) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 850, in _ParseOrMerge self._MergeField(tokenizer, message) File "/usr/local/lib/python3.7/dist-packages/google/protobuf/text_format.py", line 947, in _MergeField (message_descriptor.full_name, name)) google.protobuf.text_format.ParseError: 1:1 : Message type "object_detection.protos.StringIntLabelMap" has no field named "Coverall". During handling of the above exception, another exception occurred: Traceback (most recent call last): File "model_main_tf2.py", line 113, in tf.compat.v1.app.run() File "/usr/local/lib/python3.7/dist-packages/tensorflow/python/platform/app.py", line 40, in run _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef) File "/usr/local/lib/python3.7/dist-packages/absl/app.py", line 303, … -
Can I query an ERP in Django app if the ERP database is not in the Django model?
In my company we do machining. I have to build an app in which people can declare tool changes. The machines are listed in the company ERP, so the app has to query the ERP to get the machines list. So, the user can select the machine on which he is working and declare his tool change. The ERP is used only read-only here. I think Django could be a good tool to build this app. But I wonder if it is a good idea to query the ERP without integrating its base to the Django project model. There would be only some direct SQL (pyodbc) queries to the ERP to prepare the HTML forms. I must confess that if I have some experience with Python (including pyodbc), I am starting with Django. -
Why is the html not recognising the view function?
I am trying to build an inventory management with Django. When building delete option, I am encountering an error. The error message is "Reverse for 'delete' not found. 'delete' is not a valid view function or pattern name." I will paste my code below. Delete function code: def delete(request, iid): obj = inventory.objects.get(id=iid) obj.delete() return render(request, 'main/lists.html') HTML Template code: <a class="btn btn-danger bg-gradient" href="{% url 'delete' i.id %}" role="button">Delete</a> Please give me a valid solution. -
Django: Create manualy session cookie and authenticate later with it
I am using Django-Rest-Framework with token authentication. In my Android App I want to open a webview and display some content from a view which needs authentication. Because of this I wrote a rest call to fetch a session id. /rest/getsessionid/ => looks like that: from django.contrib.sessions.backends.db import SessionStore class GetSessionKeyView(APIView): def get(self, request, format=None): if request.user.is_authenticated: s = SessionStore() s.create() return Response({'sessionid': s.session_key}) return Response({'notauthenicated': True}) Unfortunately the returned sessionid is not working. Why? -
how to reshape django queryset and show in template
I wang to reshap my django queryset and this queryset showed in page like this. I want it showed in one row, and the first column mergered and displayed in one one string. This is can be done in python and mysql with group by function. how can I get in django queryset? Thank you very much for any kind suggestions -
Delete unapplied migrations Django
I modified a model field in my local environment and made the migrations. Every thing seemed fine until I pushed it to production. I tried to apply the migrations to my DB and received an error: cannot ALTER TABLE because it has pending trigger events I ended up just reverting to the previous migration, which solved the problem for now. But now I have these unapplied migration files pending and I need to find a way to either delete them or ignore them. What is the best solution moving forward? Local Production -
React app can't reach to backend python application on localhost on same server
i have one peculiar situation as below .......... i have one public cloud VM which has public ip say 160.159.158.157 (this has a domain registered against it) ...... i have one python-django application (backend) which cors-enabled serving data through rest api port 8080 ...... i have one react app running on same vm on different port (3000) which is accessing the python-django app and supposed to produce one report...... Problem is -- when i use http://:8080/api/ or http://:8080/api/ my application is working fine but when i try to fetch data from localhost like http://localhost:8080/api/ or http://127.0.0.1:8080/api/ react app failed to fetch data...... getting error -- Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080/api/. (Reason: CORS request did not succeed). Status code: (null). in developer-tools i tried to use below axios.get(baseURL, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS', } this is too not helping me out .... Any idea to over come it ? when i use localhost my request from react not able to react backend Python app -
Object has no attribute "_set" in djangoe
Can't figure out where my mistake is. Not able to map through to display the list of blog comments. I'm using django and react and have the following blog post and blog comment models class BlogComment(models.Model): post = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, related_name="post_comment", null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="user_comment", null=True) name = models.CharField(max_length=200, null=True, blank=True) comment = models.TextField(null=True, blank=True) dateCreated = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user.username) class BlogPost(models.Model): ... author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) body = models.TextField() dateCreated = models.DateTimeField(auto_now_add=True) And the serializers for both models are: class CommentSerializer(serializers.ModelSerializer): class Meta: model = BlogComment fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField(read_only=True) class Meta: model = BlogPost fields = "__all__" def get_comments(self, obj): comments = obj.comment_set.all() serializer = CommentSerializer(comments, many=True) return serializer.data The endpint of comment is path('posts/<str:pk>/comment/', CreateCommentView, name="create-comment"), The endpoint is working. I'm able to add comment to posts both from the front end. The error comes when I try to map through the comments for each post. get the errorAttributeError: 'BlogPost' object has no attribute 'comment_set' Here is the code I'm using to map through to display all the blogs of a particular post in the blog details page in react <div variant='flush'> {blog.comments.map((comment) => ( <div key={comment.id}> <strong>{comment.name}</strong> … -
OpenCV and MacOS - NSWindow drag regions should only be invalidated on the Main Thread
Background info: I am using python 3.9, Django 4.0.1, OpenCV 4.5.5.62, MacOS Big Sur 11.6 I am creating a face detection/recognition for my DJango application, however when I try to get the camera feed displayed I am recieving the following error: 2022-01-14 13:38:51.299 Python[78727:759513] WARNING: NSWindow drag regions should only be invalidated on the Main Thread! This will throw an exception in the future. Called from ( 0 AppKit 0x00007fff22cdbed1 -[NSWindow(NSWindow_Theme) _postWindowNeedsToResetDragMarginsUnlessPostingDisabled] + 352 1 AppKit 0x00007fff22cc6aa2 -[NSWindow _initContent:styleMask:backing:defer:contentView:] + 1296 2 AppKit 0x00007fff22cc658b -[NSWindow initWithContentRect:styleMask:backing:defer:] + 42 3 AppKit 0x00007fff22fd083c -[NSWindow initWithContentRect:styleMask:backing:defer:screen:] + 52 4 cv2.abi3.so 0x00000001194f5334 cvNamedWindow + 564 5 cv2.abi3.so 0x00000001194f4c8a cvShowImage + 154 6 cv2.abi3.so 0x00000001194f2711 _ZN2cv6imshowERKNSt3__112basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEERKNS_11_InputArrayE + 1329 7 cv2.abi3.so 0x000000011870d999 _ZL18pyopencv_cv_imshowP7_objectS0_S0_ + 601 8 Python 0x0000000105855eab cfunction_call + 59 9 Python 0x0000000105816d5d _PyObject_MakeTpCall + 365 10 Python 0x00000001058ef49c call_function + 876 11 Python 0x00000001058ec933 _PyEval_EvalFrameDefault + 25219 12 Python 0x0000000105817528 function_code_fastcall + 104 13 Python 0x00000001058ef40c call_function + 732 14 Python 0x00000001058ec9cb _PyEval_EvalFrameDefault + 25371 15 Python 0x0000000105817528 function_code_fastcall + 104 16 Python 0x00000001058ed043 _PyEval_EvalFrameDefault + 27027 17 Python 0x00000001058f0103 _PyEval_EvalCode + 2611 18 Python 0x00000001058174b1 _PyFunction_Vectorcall + 289 19 Python 0x00000001058ed043 _PyEval_EvalFrameDefault + 27027 20 Python 0x0000000105817528 function_code_fastcall + 104 21 Python 0x000000010581956a … -
Como utilizar um protocolo modbus com django?
Estou utilizando o django para desenvolver um sistema de monitoramento. Este sistema de monitoramento utilizara o protocolo de comunicação Modbus RTU. Tenho um formulário dinâmico aonde utilizei o inline formset, pois um dispositivo pode ter vários registros, este formulário esta funcionando corretamente. O que acontece que não estou conseguindo pegar alguns dados salvos no banco de dados, pois necessito dos dados de id do escravo e do número do registrador para solicitar uma informação. Estou utilizando a biblioteca mimimalmodbus. Obs: não estou conseguindo pegar o id_escravo e nem o numero_registrado no banco de dados. O meu condigo esta na Views.py no django instrument.serial.stopbits = 1 instrument.serial.timeout = 0.05 # seconds instrument.serial.xonxoff = False instrument.precalculate_read_size = False instrument.mode = minimalmodbus.MODE_RTU # rtu or ascii mode instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) #a =instrument.read(numero_registrador , id_escravo) a = instrument.read_register(289, 1) -
How to change permission based on request.query_params in Django rest frameworks?
I merged together two views that almost does the same thing except the permission, I want to change permission based on: if company id is in the params. If not, it would use a simple IsAuthenticated class and also created a permission for IsCompany. class FilesView(ListAPIView): serializer_class = FileSerializer permission_classes = (IsAuthenticated,) ... def get_queryset(self): if 'company' in self.request.query_params: # In this case I want the IsCompany Permission class return get_company_files(self) # Otherwise the regular one return get_personal_files(self)