Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTTP 405 Method Not Allowed ( rest framework )
i learn some django code with rest framework and i get a problem i try from model but i'm getting an error : HTTP 405 Method Not Allowed "GET /create-room HTTP/1.1" 405 12243 someone help me . my code : view.py from django.shortcuts import render from rest_framework import generics, status from .serializers import RoomSerializer, CreateRoomSerializer from .models import Room from rest_framework.views import APIView from rest_framework.response import Response # Create your views here. class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST) -
Security for Django api method accessed by frontend and backend
I have few api methods, they get accessed by a frontend application js code, since user is logged in, all requests will be passing a cookie. Same api also needs to be accessed via backend as well. In this case what should be the protection method ? -
Setting up a Postgres DB for Django with Fly.io
I'm a novice trying to spin up my first webapp with a combination of Fly.io, Django, and a postgres DB but I'm having some trouble and can't find an answer in walkthroughs or Q&A. I've set up a simple "Hello world" Django app (models.py is empty so far) and I'm trying to get all the components up and running before I build it out any further. I've successfully deployed my app on Fly.io with no errors I've created a postgres cluster on Fly.io using the instructions here: https://fly.io/docs/postgres/ I've attached the cluster to my app, which generates a DB and sets an environment variable with the appropriate details (username, password, port, host, dbname) I've updated my settings.py file: DATABASES = {} DATABASES["default"] = dj_database_url.config(conn_max_age=600, ssl_require=True) I've added to my fly.toml: [[services]] internal_port = 5432 # Postgres instance protocol = "tcp" # Open port 10000 for plaintext connections. [[services.ports]] handlers = [] port = 10000 I've confirmed I can get into the psql shell with flyctl postgres connect -a MYAPP-pg But unfortunately when I run python manage.py migrate to check that everything is working, I get the following error: File "<my_path>\venv\lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "<my_path>\venv\lib\site-packages\django\utils\asyncio.py", line 26, in … -
How to make case insensetive searcn in Django with Postgres
I have a project with Django, Django REST Framework and PostgreSQL. And my goal to make a search with certain conditions: logical operators (AND, OR, NOT) case insensitive operator like * To search by prefixes. som* -> search for some, somali and so on My first attempt was to use Postgres full search with this type search_type='websearch' It's all good but don't have operator * So I switched to raw type search and my class for search looks like it now class DataSearch(generics.ListAPIView): serializer_class = DataSerializer def get_queryset(self): q = self.request.query_params.get('query') if q: vector = SearchVector('research', 'data', 'research__name') query = SearchQuery(q, search_type='raw') queryset = Data.objects.annotate(search=vector).filter(search=query) else: queryset = Data.objects.none() return queryset Logical operator works, search by prefixes works with :* but I don't know how to make it case insensitive. Is it possible to make this type of search case insensitive? Or maybe there are another option for it? -
comprehension list returns empty list with extracted text
I am using a Django application. And I have a function that returns some extracted text. So this is the method: def total_fruit_cost(self, file_name): self.extract_text_from_image(file_name) fruit_cost_found = [] single_fruit = [fruit for fruit in self.fruit_word] for fruit in single_fruit: if len(re.findall(self.regex_fruit_cost(fruit), file_name)) > 0: fruit_cost_found.append(re.findall( self.regex_fruit_cost(fruit), file_name)) return [item for sublist in fruit_cost_found for item in sublist] and the methhod self.extract_text_from_image(file_name) looks like this: def extract_text_from_image(self, filename): self.text_factuur_verdi = [] pdf_file = wi(filename=filename, resolution=300) all_images = pdf_file.convert('jpeg') for image in all_images.sequence: image = wi(image=image) image = image.make_blob('jpeg') image = Image.open(io.BytesIO(image)) text = pytesseract.image_to_string(image, lang='eng') self.text_factuur_verdi.append(text) return self.text_factuur_verdi the fruit_words: self.fruit_word = ['Appels', 'Ananas', 'Peen Waspeen', 'Tomaten Cherry', 'Sinaasappels', 'Watermeloenen', 'Rettich', 'Peren', 'Peen', 'Mandarijnen', 'Meloenen', 'Grapefruit', 'Rettich'] and the regex: regex_fruit_cost: def regex_fruit_cost(self, substr): return r"(?<=" + substr + r").*?(?P<number>[0-9,.]*)\n" and then I use it in the view like this: if uploadfile.image.path.endswith('.pdf'): content = extract_instance.total_fruit_cost( uploadfile.image.path) print(content) But the result is an empty list:[]. the result has to be: 3.488,16 137,50 500,00 1.000,00 2.000,00 1.000,00 381,25 123,20 2.772,00 46,20 577,50 69,30 I also calling three times: file_name in the method: total_fruit_cost That could be improved. But I am not sure how to do that. My question: So how can I improve … -
How to get required response from DRF
I have database which consists of configuration of application. Application can have various configuration keys and basically I don't have information about how much keys I have and name of keys are not known too. I need to have response as {key: value, }. But I have response {key_field: key, value_field: value}. What should I do basically in this case? Does using MongoDB instead of PostgreSQL or SQlite help me? Or any other ideas? Model looks like: class Service(models.Model): name = models.TextField() version = models.IntegerField() class ServiceKey(models.Model): service = models.ForeignKey( Service, on_delete=models.CASCADE ) service_key = models.TextField() service_value = models.TextField() views: @api_view(['GET', ]) def hello(request): name = request.query_params.get('service') try: service = Service.objects.get(name=name) service_key_instance = ServiceKey.objects.filter(service=service) serializer = KeySerializer(instance=service_key_instance, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) except: Response(data='record not found', status=status.HTTP_400_BAD_REQUEST) -
How to add new elements into my email template (django)
i'm doing a form that will send an e-mail after completing the fields. The email must contains all the information wrote in the form, but in the forms i did a button to add more items, and this will appeart two new fields of "select component" and "quantity". How can i get the data from these fields that will be created after clicking into "add component" and put into my email? my views.py def home(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): type = form.cleaned_data['type'] serialNumber = form.cleaned_data['serialNumber'] itemNumber = form.cleaned_data['itemNumber'] date = form.cleaned_data['date'] phase = form.cleaned_data['phase'] capacity = form.cleaned_data['capacity'] centerQuantity = form.cleaned_data['centerQuantity'] componentQuantity = form.cleaned_data['componentQuantity'] componentSelection = form.cleaned_data['componentSelection'] commentary = form.cleaned_data['commentary'] html = render_to_string('emails/email.html', { 'type': type, 'serialNumber': serialNumber, 'item': itemNumber, 'date': date, 'phase': phase, 'capacity': capacity, 'centerQuantity': centerQuantity, 'componentQuantity': componentQuantity, 'componentSelection': componentSelection, 'commentary': commentary, } ) send_mail('ATENÇÃO', 'Message', 'no-reply@xxx.net', ['test@xxx.net'], html_message=html, fail_silently=False) return redirect('home') else: form = Form() return render(request, 'template.html', { 'form': form }) My html file: <body> <div> <h2> Engine Information</h2> <table> <form action="." method="POST" hx-post="."> {% csrf_token %} <tbody> <tr> <th>Type</th> <td>{{form.type}}</td> </tr> <tr> <th>Serial Number</th> <td>{{form.serialNumber}}</td> <th>or Material Number</th> <td>{{form.itemNumber}}</td> </tr> <tr> <th>Manufactoring Date</th> <td>{{form.date}}</td> <th>Phase</th> <td>{{form.phase}}</td> <th>Capacity</th> <td>{{form.capacity}}</td> <th>Center Quantity</th> <td>{{form.centerQuantity}}</td> … -
Chart.js display no data message using django
I have a pie chart that I want to display no data message when there is no data to be shown I have tried the methods here but it seems to stop displaying the chart all together even when there is data. currently if there is no data it shows NAN% the data it based off the user data from a model. I have also tried to just use the if statement for the part displaying the Nan% but the if statement also just seems to cause it to stop rendering the chart. JS: <script> {% block jquery %} var endpoint = '/api/chart1' var defaultData = [] var labels = [] $.ajax({ methode: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default setChart1() }, error: function(error_data){ console.log("error") console.log(error_data) } }) function setChart1(){ var ctx = document.getElementById('myChart').getContext('2d'); Chart.register(ChartDataLabels); var myChart = new Chart(ctx, { type: 'pie', plugins: [ChartDataLabels], data: { labels: labels, datasets: [{ label: '', data: defaultData, backgroundColor: [ 'rgba(255, 51, 51, 0.2)', 'rgba(255, 255, 0, 0.2)', 'rgba(0, 204, 204, 0.2)', ], borderColor: [ 'rgba(255, 51, 51, 1)', 'rgba(204, 204, 0, 1)', 'rgba(0, 204, 204, 1)', ], borderWidth: 1 }] }, options: { plugins: { tooltip: { enabled: … -
A multipart/form-data with nested serializers and files, DRF raises "The submitted data was not a file. Check the encoding type on the form."
I have this issue with using a multipart/form-data, nested serializers and the upload of images/files. I think my models and serializers are working well, but in some moment during the parse of the form data is when it fails. I've just extended the BaseParser to parse strings to lists and dicts. parsers.py class MultiPartJSONParser(BaseParser): media_type = 'multipart/form-data' def parse(self, stream, media_type=None, parser_context=None): parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META.copy() meta['CONTENT_TYPE'] = media_type upload_handlers = request.upload_handlers try: parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding) data, files = parser.parse() data = data.dict() for key in data: if data[key]: try: data[key] = json.loads(data[key]) except ValueError as e: pass return DataAndFiles(data, files) except MultiPartParserError as exc: raise ParseError('Multipart form parse error - %s' % exc) Why I do this? Because my intention is to pass a form-data like this: key Value user 6 address {"street": "Main St.", "number": "1"} first_name Alice last_name Bob image [file] ...\image_directory language [1,2] If I don't POST or PATCH with the image it works well, but when I send an image: The submitted data was not a file. Check the encoding type on the form. The "crazy" thing about this it is … -
NOT NULL constraint failed: cms_viewcount.session
I am trying to get users ip address for a blog project view counts, and when the user isn't logged in a get this error integrityError at /article/another-post-to-test-things-out/ NOT NULL constraint failed: cms_viewcount.session Here is my views.py # regular blog details def blog_detail(request, slug): template_name = 'cms/single.html' blog = Blog.objects.get(slug=slug) msg = False form = CommentForm() ip=request.META['REMOTE_ADDR'] if not ViewCount.objects.filter(blogview=blog, session=request.session.session_key): view=ViewCount(blogview=blog, ip_address=ip, session=request.session.session_key) view.save() blog_views=ViewCount.objects.filter(blogview=blog).count() if request.user.is_authenticated: user = request.user if blog.likes.filter(id=user.id).exists(): msg = True context = {'blog': blog, 'msg':msg, 'form':form, "view_count":blog_views,} try: if request.method == 'POST': form = CommentForm(request.POST) comment = form.save(commit=False) comment.blog = blog comment.owner = request.user comment.save() messages.success(request, 'Your review was successfully submitted!') return redirect('blog-detail', slug=blog.slug) if not request.user or not request.user.is_authenticated: return render(request, template_name, context) else: return render(request, template_name, context) except: return render(request, "cms/login-prompt.html", context) Here is the error on my browser also view.save() … Local vars Variable Value blog <Blog: Another Post to test things out> form <CommentForm bound=False, valid=Unknown, fields=(body)> msg False request <WSGIRequest: GET '/article/another-post-to-test-things-out/'> slug 'another-post-to-test-things-out' template_name 'cms/single.html' view <ViewCount:> PLease how can I fix this error , note everthing works fine when the user is logged in models.py #views count models class ViewCount(models.Model): blogview=models.ForeignKey(Blog, related_name="view_count", on_delete=models.CASCADE) ip_address=models.CharField(max_length=50) session=models.CharField(max_length=50) def __str__(self): … -
Mantain wagtail category across pages
I've a pagination system on my Wagtail website that works just fine with normal posts. However, I wanted to make pagination of post categories and I wasn't able to do it, it loads the "Posts" URL losing the category. You can see an example here when clicking page 2 https://wizardeo.es/publicaciones/?category=guias This is the code of my template {% if posts.paginator.num_pages > 1 %} {% if not 1 == posts.number and posts.number >= 4 %} {% if posts.paginator.num_pages > 5 %} <a href="?page=1">&lt;&lt;</a> {% endif %} {% endif %} {% for page_num in posts.paginator.page_range %} {% if posts.number == 1 %} {% if page_num > posts.number|add:-3 and page_num < posts.number|add:5 %} <a href="?page={{ page_num }}" class="{% if page_num == posts.number %} active {% endif %}">{{ page_num }}</a> {% endif %} {% elif posts.number == 2 %} {% if page_num > posts.number|add:-2 and page_num < posts.number|add:4 %} <a href="?page={{ page_num }}" class="{% if page_num == posts.number %} active {% endif %}">{{ page_num }}</a> {% endif %} {% elif posts.number == 3 %} {% if page_num > posts.number|add:-3 and page_num < posts.number|add:3 %} <a href="?page={{ page_num }}" class="{% if page_num == posts.number %} active {% endif %}">{{ page_num }}</a> {% endif %} {% … -
How to prevent djagno from updating certain fields?
I have a model that I use in django admin to keep track of action taken on a task. The model includes a user field to show which user added an action. The issue is when a new task update is added, django overwrite the previous user by the new user. As it can be seen bellow, I do not want to change the user (by field) whenever a new action is created. class Action(models.Model): action = models.ForeignKey(TaskAction, models.CASCADE) by = models.ForeignKey('auth.User', models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, editable=False) note = models.TextField(blank=True, null=True) def __str__(self): return str(self.action) class Meta: verbose_name = 'Task Action' verbose_name_plural = 'Task Actions' db_table = 'task_actions' -
How to more efficiently test if data anomalies occur in transaction (Django)
I want to test if data anomalies such as dirty read, non-repeatable read, phantom read, lost update and so on occur in transaction. Actually, I used person table which has id and name as shown below. person table: id name 1 John 2 David Then, I tested non-repeatable read with test view below and one command prompt. *During sleep(10), one command prompt updates "David" to "Tom" and commits: # "store/views.py" from .models import Person from django.http import HttpResponse from django.db import transaction from time import sleep @transaction.atomic def test(request): print(Person.objects.get(pk=2)) # "David" sleep(10) # Update "David" to "Tom" and commit by one command prompt. print(Person.objects.get(pk=2)) # "Tom" return HttpResponse("Test") But, every time I test data anomalies, I manually need to run test view and update and commit with one command prompt which takes much time. So, how can I more efficiently test if data anomalies occur in transaction? -
Unable to raise ValidationError in Django form
I have made a form in which the user is supposed to enter date and time. I want to make sure that the time is in the correct format so I wrote convert_to_time function so that it can raise a ValidationError when the format of time is wrong but it is not working the way I want. I want to display the error in the form itself. I seem that the Exception is not working. I mean the control is never going inside the Exception part. Here is my forms.py file. """Function to convert string to time.""" def convert_to_time(date_time): format = '%H:%M:%S' try: datetime.datetime.strptime(date_time, format).time() except Exception: #print("qkftio") This statement does not get executed even when the time format is wrong raise ValidationError( "Wrong time format entered." ) """class used for booking a time slot.""" class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] """Function to ensure that booking is done for future.""" def clean(self): cleaned_data = super().clean() normal_book_date = cleaned_data.get("check_in_date") normal_check_in = cleaned_data.get("check_in_time") convert_to_time(str(normal_check_in)) Here is my models.py file. """class used when a user books a room slot.""" class Booking(models.Model): check_in_date = models.DateField() check_in_time = models.TimeField() check_out_time = models.TimeField() PERSON = ( (1, '1'), … -
Django-filter package, filtering by date (using calendar)
I am learning Django and have difficulties with django-filter package. I am creating a NewsPortal as my homework. It shows news and i have to make a filter which could list the news by date. Plus i need to use a calendar to choose a proper date for filtering. Not just to write a date in a form but choose it by using the calendar. The problem is that i am using a django-filter package and it creates its own form. Like this: <form action="" method="get" class="filter_news"> {{ filterset.form.as_table }} <input type="submit" value="Search" /></form> I`ve created a FilterSet: class PostFilter(FilterSet): ... time_add = django_filters.DateTimeFilter(lookup_expr='gte', label='Date') class Meta: model = Post fields = ['title', 'post_author_id__author_id__username', 'time_add'] My model: class Post(models.Model): ... time_add = models.DateTimeField(auto_now_add=True) ... Right now filtering is not working at all and i don`t know how to make it by embedding calendar. Please help me if you can. I am completely stuck. -
Django filtering doesn't work with float field
I'm trying to get some records from the MySQL database but it seems that filtering by float field doesn't work. When I filter just by user_id I receive all records but when I add the value clause just got DoesNotExist exception. I have the following models and query: class Record(models.Model): user_id = models.IntegerField() value = models.FloatField() class User(models.Model): value = models.FloatField() Record.objects.get( user_id=user.id, value=user.value ) user.value variable in the python code is 0.4 (float). The value column in the database is type float unsigned and its value is 0.4. I guess it's something because of the nature of float type but what is the right way to filter by float value using Django models? -
textarea offset when two different textareas are possible at the same location using an EventListener
I have an event listener which will show a textarea for writing a message depending on a the subject line selected. The code works but the second textarea is indented for some reason. The HTML code is: <td>Message</td> <td><textarea id="area1" cols="80" rows="6" onfocus="if(this.value==this.defaultValue)this.value='';" name="area1">Please type your message here</textarea> </td> <td><textarea readonly id="area2" cols="80" rows="6" hidden name="area2">Some text here</textarea> </td> The javascript code is then: <script> document.getElementById('subject').addEventListener('change', function () { if (this.value == 'Subject1') { document.getElementById('area1').style.display = 'none'; document.getElementById('area2').style.display = 'block' } else { document.getElementById('area1').style.display = 'block'; document.getElementById('area2').style.display = 'none' } }); </script> Any help would be greatly appreciated, thank you -
Enforce JOIN instead of Subquey when using "__in" filter in Django ORM
Task: I want to get all invoices where the project title matches a given string. The Invoice has a foreign key to Project. The problem: I want to use a function for doing the project search so I can recycle and encapsulate this use-caes. To make this happen I have to use the __in operator instead of project__title__icontains=my_str. This will lead to an inefficient subquery. The later will create an efficient JOIN. Code examples I have two custom queryset methods. One lives in Project: def search_title(self, title: str): """ Searches for projects having the given title or at least parts of it. """ return self.filter(title__icontains=title) The second one lives in Invoice: def search_project_title(self, project_title: str): return self.filter(project__in=Project.objects.search_title(project_title)) Any ideas how I can tell the Django ORM that I prefer JOINs over Subqueries? Thx! -
Django - paragraph <p> is not working with autoescape
It seems like <p> is somehow missinterpreted when using Django template with {% autoescape off %}. It doesn't matter, in which place I define <p> - before autoescape tag, after or even inside the content delivered to that section. All other tags (defined inside autoescaped content string) works perfectly, the problem is only with paragraph. But the result is that paragraph is empty: Of course I have tried also variant with defined after autoescape like this: but the result is always the same empty tag. I cannot see any reason why this is happening, I would appreciate any help. Thanks. -
Django Websocket: Messages are all sent after loop is finished
I am trying to create a application, where i start the game with a countdown. For that I have a loop counting down. The problem is when i am awaiting my send loop, all messsages are sent after the loop is finished. When i am putting the function in a task it is sending instant but thats not what i want because I need to wait for the function to call another after. Thats the the countdown function async def init_starting(self): if not self.lobby.status == "waiting": print("Already Started") return False else: print("Starting Countdown") self.lobby.status = 'starting' await self.save_lobby() await self.send_status_message_with_status(status='starting', data={'has_started': self.lobby.has_started, 'host': self.host.username, 'players': self.players, 'lobby_code': self.lobby_code, 'countdown': 3}) countdown = 3 while countdown >= 0: # here are the messages not sent instant but after the loop is finished (with my current approach they are sent instant but i cant await it countdown_data = { 'countdown': countdown } await self.send_status_message_with_status(status='starting', data=countdown_data) countdown -= 1 await asyncio.sleep(1) self.lobby.status = 'started' await self.save_lobby() await self.send_status_message_with_status(status='started', data={ 'message': "Test" }) return True Here i am currently starting the task if "command" in text_data_json: command = text_data_json['command'] match command: case 'start': loop = asyncio.get_running_loop() start_task1 = loop.create_task(self.init_starting()) # here i would like … -
JQuery with dataTransfer move multiple table datas to input fields
I have below table with 2 rows but can doubled with button (Add another Word media): <tbody> <tr class="form-row dynamic-medias" id="medias-0"> <td class="field-path_to_file"> <div id="medias-0-path_to_file_with_media_recorder"> <div class="py-2"> <input type="file" name="medias-0-path_to_file" class="bg-slate-100 p-2" id="id_medias-0-path_to_file"> </div> <p> Or record an audio </p> <div class="btn-group" role="group"> <button id="medias-0-path_to_file_record_start" type="button" class="px-2 py-1 text-white bg-green-500 disabled:bg-gray-500 rounded-sm" onclick="startRecording(this)"> Record </button> <button id="medias-0-path_to_file_record_stop" type="button" class="px-2 py-1 text-white bg-red-500 disabled:bg-gray-500 disabled:text-gray-200 rounded-sm" onclick="stopRecording(this)" disabled=""> Stop </button> </div> <div class="recording" id="medias-0-path_to_file-record-status"> <span class="text-sm"> Click the "Start Recording" button to start recording </span> </div> </div> <audio controls="" src="blob:http://localhost:8000/79977bf5-155b-4ca1-b5bc-097b8a55a80a"></audio><a download="Recorded-Media" href="blob:http://localhost:8000/79977bf5-155b-4ca1-b5bc-097b8a55a80a">Download it!</a> </td> </tr> <tr class="form-row dynamic-medias" id="medias-1"> <td class="field-path_to_file"> <div id="medias-1-path_to_file_with_media_recorder"> <div class="py-2"> <input type="file" name="medias-1-path_to_file" class="bg-slate-100 p-2" id="id_medias-1-path_to_file"> </div> <p> Or record an audio </p> <div class="btn-group" role="group"> <button id="medias-1-path_to_file_record_start" type="button" class="px-2 py-1 text-white bg-green-500 disabled:bg-gray-500 rounded-sm" onclick="startRecording(this)"> Record </button> <button id="medias-1-path_to_file_record_stop" type="button" class="px-2 py-1 text-white bg-red-500 disabled:bg-gray-500 disabled:text-gray-200 rounded-sm" onclick="stopRecording(this)" disabled=""> Stop </button> </div> <div class="recording" id="medias-1-path_to_file-record-status"> <span class="text-sm"> Click the "Start Recording" button to start recording </span> </div> </div> <audio controls="" src="blob:http://localhost:8000/cd165412-b186-4a11-8fd7-6997750b9bd3"></audio><a download="Recorded-Media" href="blob:http://localhost:8000/cd165412-b186-4a11-8fd7-6997750b9bd3">Download it!</a> </td> </tr> <tr class="add-row"> <td colspan="4"><a href="#">Add another Word media</a></td> </tr> </tbody> Below is JQuery code get the recorded audio from little player for each rows and move it to input … -
Can we have one model serializer for multiple models having the same fields? Django Rest Framework
I have 5 models with same fields inheriting from a base model. Now for all the five models I am having 5 serializers serializing all the fields for their respective models. An example of the setup is as below base model class BaseModel(models.Model): field 1 field 2 ** model 1** class Model1(BaseModel): field 3 = models.Charfield(choices=CHOICES) model 2 class Model 2(BaseModel) field 3 = models.Charfield(choices=CHOICES) So field3 is common in both the models but have different choices in them hence are placed in different models and not in the base model. serializer class SerialModel1(serializers.ModelSerializer): class Meta: model = Model1 fields = "__all__" class SerialModel2(serializers.ModelSerializer): class Meta: model = Model2 fields = "__all__" So as shown even when the models have the same fields I need to use to different model serializers. Question Can I have just one model serializer for both Model1 and Model2 ? If yes, please suggest me the way to do it. -
Get Request in django-plotly-dash
I am trying to pass args in get request to plotly app : but I cannot retrieve the information. my_webpage.html?value=1 views.py: def my_webpage(request): return render(request, 'home/my_webpage.html', {}) my_webpage.html : {% extends 'base.html' %} {% load static %} {% block content %} {% load plotly_dash %} <div class="{% plotly_class name='my_webpage' %} card" style="height: 100%; width: 100%"> {% plotly_app name='my_webpage' ratio=10 %} </div> {% endblock %} my_webpage.py : external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = DjangoDash('my_webpage', external_stylesheets=external_stylesheets ) app.layout = html.Div([ dcc.Location(id='url', refresh=False), html.Div(id='page-content'), ]) @app.callback(Output('page-content', 'children'), Input('url', 'search')) def display_page(params): print("model_view - display_page") parsed = urllib.parse.urlparse(params) parsed_dict = urllib.parse.parse_qs(parsed.query) print(parsed_dict) page_content = params for i in parsed_dict.keys(): page_content += f"{f} {parsed_dict[i]} \n" print(params) return page_content related links : https://github.com/GibbsConsulting/django-plotly-dash/issues/416 -
Displaying from models to a template page in django
I want to display the data of models to my template file but it just can't work it doesn't even show an error message, even when I pass a QuerySet of message objects as context to the render function. App Name is CD Here my code models.py from django.db import models # Create your models here. class Task(models.Model): text = models.CharField(max_length = 200) def __str__(self): return self.text views.py from django.shortcuts import render from .models import * # Create your views here. def index(requets): tasks = Task.objects.all() context = {'tasks': tasks} return render(requets, 'CD/home.html', context) my template home.html {% for task in tasks %} <h1>{{task.texts}}</h1> {% endfor %} -
Display bootstrap element in django-forms
I want to use an element of a bootstrap template in my django-form: It's html code looks like this: What approach should I take to load this element in my form using django? So far I have tried this: 1.- Define field: CHOICES = [('1', 'First'), ('2', 'Second')] selector = forms.ChoiceField( required=False, label= "Select software products", choices=CHOICES, widget = forms.TextInput( attrs= { 'class': 'choices', 'role': 'combobox', 'data-type': 'select-multiple' } ) ) 2.- Add to layout: self.helper.layout = Layout( Row(Div(Div('selector'), css_class='form-group')) ) The result is a regular input field: In other elements I just put the css class and it works perfectly but I can't figure out how to do it in more complex objects. Thank you in advance!!