Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM - INNER JOIN to a GROUP BY subquery on the same table
I've got a table that looks something like this (I've omitted some columns): ID Key_ID Project_ID other columns 1 1 123456 a 2 1 123456 b 3 2 123456 c 4 2 123456 d 5 3 654321 e 6 3 654321 f 7 4 654321 g 8 4 654321 h Using Django ORM, I would need to get the equivalent of this query: SELECT * FROM table AS t INNER JOIN ( SELECT MAX(ID) AS max_ID FROM table GROUP BY Key_ID WHERE Proeject_ID = 123456 ) AS sub_query ON t.ID = sub_query.max_ID I've tried some aggregate and annotate combinations but I don't seem to be able to achieve the GROUP BY in the subquery. If I could do that I could then try to use a .filter(id__in=<subuery_result> so effectively use a SELECT ... WHERE ID IN <subquery_result although the INNER JOIN would be ideal as the subquery result could be quite large. -
Is it possible to use lambda layers with zappa?
I want to deploy my wagtail (which is a CMS based on django) project onto an AWS lambda function. The best option seems to be using zappa. Wagtail needs opencv installed to support all the features. As you might know, just running pip install opencv-python is not enough because opencv needs some os level packages to be installed. So before running pip install opencv-python one has to install some packages on the Amazon Linux in which the lambda environment is running. (yum install ...) The only solution that came to my mind is using lambda layers to properly install opencv. But I'm not sure whether it's possible to use lambda layers with projects deployed by zappa. Any kind of help and sharing experiences would be really appreciated! -
After running the server in django, I am getting the KeyError: 'django'
I am not fluent in Django,been doing for over 3 months now, BUT I have never seen such error. Please if someone can help me out of this situation. I am doing the short_url module, bt befoe that i have pip installed shorturls , then i created an app shorturls. Again , i have to delte the app shorturls. And after that i have been facing this issue. Following is my full traceback of the error: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\backends\django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\shorturls\templatetags\shorturl.py", line 5, in <module> from django.core import urlresolvers ImportError: cannot import name 'urlresolvers' from 'django.core' (C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\__init__.py) The above exception was the direct cause of the following exception: Traceback (most recent call last): … -
Download page as JSON in Django
I have a view which returns a formatted JSON object. It takes a list of words (labeled "forms" and "lemmas" for this project), formats them into a nice dictionary object and outputs a json page which can then be saved by the user. views.py def search_view(request): """ The app revolves around this view, which is also the homepage. """ context = {} if request.method == 'GET': return render(request, 'search.html', context) if request.method == 'POST': checked_A = {} checked_B = {} # All lemma keys are of the form {lemma}@{group}. # All form keys are of the form {lemma}@{group}@{form}. # The "@" symbol will not appear in any other key. # Split the key_data into two parts, the lemma/group part # and the form part. The form part is either [] or [form] for key in request.POST: if "@" not in key: continue key_data = key.split("@") (lemma, group), form = key_data[:2], key_data[2:] if group == "A": if checked_A.get(lemma): checked_A[lemma].extend(form) else: checked_A[lemma] = list(form) if group == "B": if checked_B.get(lemma): checked_B[lemma].extend(form) else: checked_B[lemma] = list(form) context['query_A'] = checked_A context['query_B'] = checked_B return JsonResponse(context, status=200) # <-- the only important part Is there a way to create a button which will download this … -
TypeError at / can only concatenate str (not "builtin_function_or_method") to str
Thank you for your time. I was working on django rest framework documentation, and only with Localhost "http://127.0.0.1:8000/" URL I get this error. TypeError at / can only concatenate str (not "builtin_function_or_method") to str I have attached Views.py, snippets/url.py and snippets/serializers.py views.py from snippets.permissions import IsOwnerOrReadOnly from snippets.models import Snippet from snippets.serializers import SnippetSerializer, UserSerializer from rest_framework import generics, permissions from django.contrib.auth.models import User from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import renderers from rest_framework.reverse import reverse @api_view(['GET'] def api_root(request, fromat=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'snippets': reverse('snippet-list', request=request, format=format) }) class SnippetHighlight(generics.GenericAPIView): queryset = Snippet.objects.all() renderer_classes = [renderers.StaticHTMLRenderer] def get(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(owner=self.request.user) class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer snippets/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = format_suffix_patterns([ path('', views.api_root), path('snippets/', views.SnippetList.as_view(), name='snippet-list'), path('snippets/<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'), path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet- highlight'), path('users/', views.UserList.as_view(), name='user-list'), path('users/<int:pk>/', views.UserDetail.as_view(), name='user-detail') ]) serializer.py from rest_framework import serializer from snippets.models import Snippet, … -
Radio buttons written with Django templates are not displayed
I am learning Django from documentation. I'm on part 4. There is a code like this (detail.html): <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} </fieldset> <input type="submit" value="Vote"> </form> Here are views.py: from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.shortcuts import render, get_object_or_404 from django.http import Http404 from django.urls import reverse from .models import Question, Choice def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) Everything is displayed except for the radiobutton. How to fix it? Python 3.6.3 Django 3.2.4 -
Django file upload : TypeError: a bytes-like object is required, not 'TemporaryUploadedFile'
I want to make a post create view. There are various functions to write an article, and there is a file upload function in particular. So, I use Multipartparser and override create function in serializer. like below: create instance first. save the file on the created instance. but when I save, the error occur: TypeError: a bytes-like object is required, not 'TemporaryUploadedFile' but don't know how to convert 'TemporaryUploadedFile' to 'a bytes-like object'. api_view> class PostCreate(generics.CreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer parser_classes = (MultiPartParser,) def post(self, request, *args, **kwargs): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer> class PostSerializer(serializers.ModelSerializer): post_files = serializers.FileField(required=False) def create(self, request): print("@@@@@request") print(request) post_files = request.pop("post_files") print("@@@ post_files.path : " + post_files.temporary_file_path()) print("@@@ post_files.name : " + str(post_files)) instance = Post.objects.create(**request) instance.post_files.save(str(post_files), ContentFile(files), save=True) return instance -
How to format date and time in Django?
I am trying to record the creation time, date of input data into a sqllite in Django in the format Jan 1, 2021, 8:21 a.m. So far I can get the time to work doing the following in models.py: class Listing(models.Model): time = models.TimeField(auto_now_add=True) def __str__(self): return f"({ ({self.time}))" with my html: {% block body %} <div> <p> Started: {{listing.time}}</p> </div> {% endblock %} I've tried to add this to the models.py date = models.DateField() But then I get an error when I try to migrate: listing without a default; we can't do that (the datatabase needs something to populate existing rows). I've tried to populate the datefield with a number, and now anytime I migrate I get stuck with this error: TypeError: expected string or bytes-like object Thanks for your help -
Django - CSS not styling HTML page
I am creating a simple dashboard page for my Django web application. I have a simple HTML file, but it is not getting styled by my CSS file. I have {% load static %} at the top of my HTML file and link the 2 files with this code: <link rel="stylesheet" href="{% static 'dashboardstyles.css' %}"> Can someone please help me resolve this problem? I have included the HTML and CSS code below. Thank you! HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GoodDeed - Dashboard</title> <link rel="stylesheet" href="{% static 'dashboardstyles.css' %}"> </head> <body> <!-- end row --> <div class="frame"> <div class="center"> <div class="profile"> <div class="image"> <div class="circle-1"></div> <div class="circle-2"></div> <img src="https://images-na.ssl-images-amazon.com/images/I/51e6kpkyuIL._AC_SL1200_.jpg" width="70" height="70" alt="Image"> </div> <div class="name">{{ user.get_full_name }}</div> <div class="job"> {{ user.get_username }}</div> <div class="actions"> <button class="btn">Events</button> <button class="btn">News</button> </div> </div> <!--Add points and stuff later--> <div class="stats"> <div class="box"> <span class="value">0</span> <span class="parameter">Points</span> </div> <div class="box"> <span class="value">0</span> <span class="parameter">Donations</span> </div> <div class="box"> <span class="value">0</span> <span class="parameter">People Helped</span> </div> </div> </div> </div> </body> </html> CSS: @import url(https://fonts.googleapis.com/css?family=Open+Sans:600,300); body{ background:#DCDCDC; } .frame { position: absolute; top: 50%; left: 50%; width: 400px; height: 400px; margin-top: -200px; margin-left: -200px; border-radius: … -
Migrating content down a level in wagtail streamfield
I've got a wagtail page model with an existing streamfield. The streamfield has now changed format and I'd like the text content to migrated down a level into a streamblock. The initial model (simplified): class ProjectPage(Page): description = StreamField( [ ("text", blocks.RichTextBlock()), ("image", ImageBlock()), ] ) The new model (also simplified): class ProjectPage(Page): description = StreamField( [ ( "section", blocks.StreamBlock( [ ("text", blocks.RichTextBlock()), ("image", ImageBlock()), ] ), ) ], ) Currently, the image blocks are empty, so only the text item needs migrating. I tried looping through pages and doing old_data = page.description.raw_data then using that to make the new content [{'type': 'section', 'value': old_data}]. If I page.save() and get the value for page.description.raw_data, I see the new content, but the admin still shows the old values. I'm guessing this is linked to revisions vs published versions but I can't figure out how to fix this. Any pointers would be welcome! -
Saving a Base64 string representing an image on Django database
I'm fairly new to Django and I'm looking for the best way to store Base64 images on my Dajango db/server. My goal is to be able to send batches of images through http request, therefore it would make sense to send them as encoded Base64 images, I may end up rendering them on a webpage but they will primarily be sent to a desktop application in batches. After looking through several other posts it looks like there are three approaches and I'm not sure what best fits my needs. Store Base64 string in model TextField Store Base64 string in FileField Store an image in an image field and convert it to Base64 when needed My concern with option 1 is that storing large textfields in the db will hinder performance, however like I said I'm new so I really don't have any idea. Option 2 seems to make sense to me as this is similar to how django handles images, by storing them else and just referencing the location in the db. However, I'm not sure if this is simply because sqlite does not support fields of this type. I also see the potential for additional overhead, having to open … -
django model many to many not working with charfield as primary key
I'm trying to accomplish a many to many relationship between my models where one table has a charfield as a primary key. The manage.py makemigrations works just fine, but running manage.py migrate crashes with: django.db.utils.OperationalError: (3780, "Referencing column 'articleCategory_id' and referenced column 'ArticleCategory_id' in foreign key constraint 'item_overview_articl_articleCategory_id_da76142b_fk_item_over' are incompatible.") Here is model 1: class Advertisement(models.Model): advertisement_id = models.IntegerField(primary_key=True) advertisement_startDate = models.DateTimeField() advertisement_endDate = models.DateTimeField() advertisement_isDefault = models.BooleanField() advertisement_image = models.ImageField(upload_to='banners/') advertisement_categories = models.ManyToManyField(ArticleCategory, related_name='ArticleAdvertisements') and model 2 class ArticleCategory(models.Model): ArticleCategory_id = models.CharField(primary_key=True, max_length=10) ArticleCategory_value = models.CharField(max_length=50) ArticleCategory_parent = models.ForeignKey("self", on_delete=models.PROTECT, null=True) ArticleCategory_type = models.ForeignKey(ArticleType, on_delete=models.PROTECT, null=False) Thanks in advance for the help! I've been stuck in this for way to long now :) -
Django listing matching query does not exist, but the page renders correctly and error displays only in terminal
I'm having a problem with Django models. I'm trying to compare value(price) stored in a listing model, but I can't because it is recognized as None, but it clearly displays on webpage with no errors. models.py: class listing(models.Model): Title = models.CharField(max_length=50) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) Description = models.CharField(max_length=300) price = models.DecimalField(max_digits=6, null=True, decimal_places=2) category = models.ForeignKey(category, on_delete=models.CASCADE, related_name="categories") def __str__(self): return f"{self.Title}" views.py: def listing_page(request, listing_id): item=listing.objects.get(Title=listing_id) (Here terminal throws error: auctions.models.listing.DoesNotExist) price=item.price bids=bid.objects.filter(listing=item) form=bidForm(request.POST or None) if request.method == "POST": if form.is_valid(): if price < form: instance = form.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect(reverse('index')) return render(request, "auctions/listing.html", {"listing":item, "form":form, "bids":bids}) Full error Traceback: Internal Server Error: /favicon.ico Traceback (most recent call last): File "C:\Users\levan\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\levan\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\levan\Downloads\commerce (2)\commerce\auctions\views.py", line 39, in listing_page item=listing.objects.get(Title=listing_id) File "C:\Users\levan\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\levan\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( auctions.models.listing.DoesNotExist: listing matching query does not exist. Help would be greatly appreciated :) -
Django exporting datetime to cvs file
I am rendering a queryset to a template and csv. models.One2OneInfoLog.objects.filter(one_2_one_info=pk).values_list(Lower('name'), 'location', 'created').order_by('created') in the template view I get a created value: 16-06-2021, 10:58 in cvs file I get: 2021-06-16 08:58:27.780570+00:00 It seems its writing the timestamp in the csv file by deducting 2 hours. Is their some way to correct it? And can I change the formatting to match the template view. -
django using ajax to call backend has problem
I'm new to Django. There is a heart icon in my html file, and I want when I click it, it turns to red and then call a function in backend to change a number in database and send back the new number to the template, all using Ajax. What should I do, and where is the problem? In html file: <i class="fas fa-heart"></i> <b>{{ note.like }}</b> The script part: <script> $(document).ready(function() { $('.fa-heart').click(function(e){ this.style.color = this.style.color == 'red' ? 'white' : 'red'; e.preventDefault(); $.ajax({ type:'POST', url:"vote/like/", data:{ num:"niloofar", csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(data){ alert(data); }, error : function() { console.log("Error"); } }); }); }); </script> In views: def like(request): if request.method == 'POST': print(request.POST) return HttpResponse('done') And the error is: Internal Server Error: /notes/1/vote/like/ Traceback (most recent call last): File "/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: like() got an unexpected keyword argument 'id' -
Facing problem with 'request.POST.get()' method it is not fetching the right data
I have just started learning Django. But, I couldn't resolve one problem I am facing, any kind of help will be appreciated here is my views.py from django.shortcuts import render def homeGrade(request): print(request.method) if request.method == "POST": num = float(request.POST.get("marks")) # here print(num) if num >= 80: grade = "Grade A" elif num >=60: grade = "Grade B" else: grade = "Grade C" msg = "Your marks are " + str(num) + " and your grades are " + grade return render(request, 'findgrade/home.html', {"msg":msg}) else: return render(request, 'findgrade/home.html', {}) And here is my template home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Find Grade</title> <script> function validate() { var m = document.getElementById("marks"); var e = document.getElementById("err"); var a = document.getElementById("ans"); if( m.value = "" | m.value < 0 | m.value > 100) { alert("Invalid Marks"); e.style.visibility = "visible"; m.value = ""; m.focus(); a.textContent = ""; return false; } else { return true; } } </script> </head> <body> <center> <h2> Find grade app </h2> <form method="POST" onsubmit="return validate()"> {% csrf_token %} <input type="number" name="marks" placeholder="Enter the marks" id="marks"> <label id="err" style="color:red; visibility: hidden"> Invalid Input </label> <br><br> <input type="submit" name="Find"> </form> <h2 id="ans"> {{ msg }}</h2> </center> </body> </html> for some reason, … -
Django chat how to store logged user data
I'm creating simple django chat. I need to fetch the "checkuser" from first function and use it into another function "def chat()" in "USERHERE" field def home_view(request): if request.method == "POST": form = LoginForm() global username username = request.POST['username'] password = request.POST['password'] try: global checkuser checkuser = chat_user.objects.get(username=username, password=password) except: form = LoginForm() return render(request, 'incorrect/incorrect.html', {'form': form}) return render(request, 'login.html', {'form': form}) def chat(request): chatform = ModelChatFormSave() if request.method == "POST": chatform = ModelChatFormSave(request.POST) if chatform.is_valid(): cdata= chatform.cleaned_data['message'] chat_message.objects.create(message=cdata, sender="USERHERE", chatuser=chat_user.objects.get(name="USERHERE)) chatform = ModelChatFormSave() return render(request, 'grats/grats.html', {'chatform': chatform}) -
what is the right way to test django channels?
I tried this , but got error TypeError: object.__init__() takes exactly one argument (the instance to initialize) class MyTests(TestCase): async def test_my_consumer(self): communicator = HttpCommunicator(Alerts, "GET", "/alerts/") res = await communicator.get_response() print(res) also i treid this, but the res always null class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Chrome('./chromedriver') except: super().tearDownClass() raise @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self): res = self.driver.get(self.live_server_url + '/alerts/') print(res) -
'Post' object has no attribute 'get_absolute_url' Django
I am trying to create a sitemap in Django but I am getting an error 'Post' object has no attribute 'get_absolute_url' Here is my anotherfile/sitemap.py from django.contrib.sitemaps import Sitemap from somefile.models import Post class site_map(Sitemap): changefreq = "daily" priority = 0.8 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.time_stamp and here is my somefile/models.py class Post(models.Model): number=models.AutoField(primary_key=True) slug=models.CharField(max_length=130) time_stamp=models.DateTimeField(blank=True) def __str__(self): return self.number -
django form no errors
I am trying to create a custom login form, when I validate the form there are no errors and it is not valid Is there a better way to implement what I want? At least I want just to get the values from the form fields. class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': '', } )) def login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): print(True) else: print(False) print(username) print(password) # authUrl = "" # authData = {'usname': request.POST['username'], # 'psword': request.POST['password'], # } # s = requests.Session() # rAuth = s.post(authUrl, data=authData).json() # if rAuth["status"] == 200: # pass else: form = LoginForm() return render(request, 'users/login.html', {'form': form}) -
How to deploy React and Django REST framework on kubernetes using minikube?
In minikube, my Django app is properly working but now I want to use my backend API in React frontend but I'm not able to do this can anyone help me ? Here my backend deployment.yml file, apiVersion: apps/v1 kind: Deployment metadata: name: movie-deployment spec: replicas: 1 selector: matchLabels: app: movie-backend template: metadata: labels: app: movie-backend spec: containers: - name: movie-backend image: javiercode/movie-backend env: - name: SECRET_KEY valueFrom: configMapKeyRef: name: movie-env key: SECRET-KEY - name: DEBUG valueFrom: configMapKeyRef: name: movie-env key: DEBUG --- apiVersion: apps/v1 kind: Deployment metadata: name: postgres-deployment spec: replicas: 1 selector: matchLabels: app: postgres-container template: metadata: labels: app: postgres-container spec: containers: - name: postgres-container image: postgres:12.0-alpine volumeMounts: - name: postgres-volume-mount mountPath: /var/lib/postgresql/data volumes: - name: postgres-volume-mount persistentVolumeClaim: claimName: postgres-pvc --- apiVersion: batch/v1 kind: Job metadata: name: django-migrations spec: template: spec: containers: - name: django image: javiercode/movie-backend command: ["/bin/sh","-c"] args: ["python3 manage.py makemigrations;python3 manage.py migrate"] env: - name: SECRET_KEY valueFrom: configMapKeyRef: name: movie-env key: SECRET-KEY - name: DEBUG valueFrom: configMapKeyRef: name: movie-env key: DEBUG restartPolicy: Never backoffLimit: 5 backend service.yml apiVersion: v1 kind: Service metadata: name: movie-backend-service spec: selector: app: movie-backend ports: - protocol: TCP port: 8000 targetPort: 8000 type: LoadBalancer --- apiVersion: v1 kind: Service metadata: name: … -
Are fixtures supported in Djongo?
I'd like to create fixtures and use them in tests. But when I try to load them e.g. by running ./manage.py loaddata test.json, I get DeserializationError. Traceback: django.core.serializers.base.DeserializationError: Problem installing fixture '/app/test.json': Value: OrderedDict() stored in DB must be of type dict/listDid you miss any Migrations?: (template.template:pk=5) field_value was 'OrderedDict()' This is just one example, but, basically, it complains about any JSON string it encounters. So it looks as though test.json is deserialized once and values for JSONFields are left as JSON strings. So it throws an error here: # from Djongo's JSONField class def to_python(self, value): if not isinstance(value, (dict, list)): raise ValueError( f'Value: {value} stored in DB must be of type dict/list' 'Did you miss any Migrations?' ) return value There is a kinda similar issue on Github that is abandoned. So I am not sure if fixtures are even supposed to work with Djongo at this point. Thanks in advance for any clarifications. -
How can I render all data to invoice page?
How can I render all data to the invoice page? data line product quality, cost, total price, etc. whenever I click on the make bill button it is redirected to the invoice page but data is not showing. views.py def makebill(request): if request.method == "POST": cart = request.POST.get('cart') price = request.POST.get('price') n = request.POST.get('name') phone = request.POST.get('phone') data = json.loads(cart) for c in data: name = c['name'] qty = c['qty'] prod = Product.objects.get(name=name) prod.qty = prod.qty - int(qty) if prod.qty <= 0: messages.warning(request, f'{prod.name} has finished') prod.delete() else: prod.save() p = Sales(items_json=cart, amount=price, name=n, phone=phone) p.save() return redirect('home:invoice') total = price else: product = Product.objects.all().order_by('name') product_list = list(product.values('name', 'cost')) context = {} context["product"] = json.dumps(product_list) try: context["total"] = total except: pass return render(request, 'makebill.html', context) How can I do? Thanks in Advance! -
DRF filtering with `fieldset_filters` using multiple queries for the same queryparam
I'm using Django and DRF, with DjangoFilterBackend for filtering the queryset results. How do you pass multiple queries to the same queryparam? For example if I had 'id' set in filterset_fields=['id'], to enable filtering Users by their ID. To filter for id 99, the url would look like this: api/user/?id=99. How would you filter for multiple ID's in one request? Is it even possible? I would like to be able to do something like this: api/user/?id=99,133,234 or maybe api/user/?id=99&id=133&id=234. This is currently NOT working for me, it just returns the first param. Thanks! -
Hide few fields in django view
I want to dynamically show/hide fields of django forms in views. Currently i am able to disable fields from views and able to dynamically render fields but cannot hide (without consuming field space in html). For example i have address field in django form and i am disabling like below in view registration_form.initial['address'] = register[0]['address'] registration_form.fields['address'].disabled = True To hide field i have tried below but it occupies space of field in html registration_form.initial['address'] = register[0]['address'] registration_form.fields['address'].widget = HiddenInput() How can i hide field from django form?