Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF Protection for django session-based auth for Hasura + auth webhook
I have a react app for the frontend, a hasura instance for the graphql engine connected to my database and a django app for their easy session-based authentication, ORM and migrations. Before I introduced the Hasura instance my authentication worked like a charm. I would get the CSRF Token and HTTP-Only cookie from django, in my frontend and when sending POST requests would send the token in the headers along with the cookie that is sent automatically. For Hasura I have to use a webhook to authenticate the graphql requests and I wanted to do this with my already in-place django sessions. Using the apollo client i setup a middleware to get csrf token and cookie from my django app and send it along with every request, where Hasura would then (hopefully) forward them to the django webhook. But now my problem is: Django only does CSRF checks for POST requests, and if I configure Hasura to send a POST request to my webhook it puts all the headers from my client request in the body as JSON, and django CSRF middleware doesn't pass the checks. Is there a way to force django to do CSRF checks for a specific … -
I removed the video download button but it only works for the first post
I have no idea where the problem comes from, a similar problem happens with the like button. I've left my code below, if you want I can post it in more detail {% for post_item in post_items %} doesn't seem to work as it should, but whyyyy? my.html {% for post_item in post_items %} <ul style="padding-inline-start: 10px;" id="dataList_post"> <li class="content hidden"> <div> <div class="post" style="min-height: 174px; border: 1px solid #f0f0f0; border-width: 2px; border-radius: 20px; max-width: 600px; height: auto; margin-right: 100px;"> <div class="posticon"> {% if post_item.user.profile.avatar %} <a style="text-decoration: none; color: black;" href="{% url 'users' post_item.user %}"><img src="{{ post_item.user.profile.avatar.url }}" style="border-radius: 100%; width: 48px; height: 48px;" alt=""></a> {% else %} <a style="text-decoration: none; color: black;" href="{% url 'users' post_item.user %}"><img src="{% static 'img/default.png' %}" style="border-radius: 100%; width: 48px; height: 48px;" alt=""></a> {% endif %} </div> <div class="postname"> <a style="text-decoration: none; color: black;" href="{% url 'users' post_item.user %}"> <h5 class="postname_location" style="font-family: cursive;"><b>{{ post_item.user.username }}</b></h5> </a> </div> <div class="postcomment"> <a style="text-decoration: none; color:black;" href="{{ post_item.get_absolute_url }}"> <span>{{ post_item.caption }}</span> <br> </a> {% for tag in post_item.tags.all %}<a href="{{ tag.get_absolute_url }}"><b>#{{ tag }}</b></a>{% endfor %} <small class="font-italic text-muted" style="float: right;">{{ post_item.posted | naturaltime }}</small> </div> {% if post_item.content.first.file.name|slice:"-3:" == 'jpg' or post_item.content.first.file.name|slice:"-3:" == 'png' … -
How can I reuse a Django view with a post method for my API
I am currently trying to create an API with DRF on my backend for a mobile application. I would like to know if it is possible to reuse some POST methods already implemented by passing them a request as parameter. Thank you, Here is the view in question: The method I am interested in is the POST method. class ShopModuleCategoryCreateView(ShopModuleMixin, BorgiaView): """ """ permission_required_self = 'modules.change_config_selfsalemodule' permission_required_operator = 'modules.change_config_operatorsalemodule' menu_type = 'shops' template_name = 'modules/shop_module_category_create.html' def __init__(self): #logger.error(' __init__') super().__init__() self.shop = None self.module_class = None self.form_class = None def has_permission(self): has_perms = super().has_permission() if not has_perms: return False else: self.form_class = formset_factory(wraps(ModuleCategoryCreateForm)( partial(ModuleCategoryCreateForm, shop=self.shop)), extra=1) return True def get(self, request, *args, **kwargs): """ permet d'afficher la page de vente """ context = self.get_context_data(**kwargs) context['cat_form'] = self.form_class() context['cat_name_form'] = ModuleCategoryCreateNameForm( initial={'order': self.module.categories.all().count()}) return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): """ Permet de publier la creation d'une nouvelle categorie cat_name_form => renvoie une objet Form avec le nom et l'ordre entré self.module => Module de vente en libre service du magasin Pi """ cat_name_form = ModuleCategoryCreateNameForm(request.POST) f = open("myfile.txt", "a") f.write(str(request)) if cat_name_form.is_valid(): category = Category.objects.create( name=cat_name_form.cleaned_data['name'], order=cat_name_form.cleaned_data['order'], module=self.module, shop_id=self.shop.pk, category_image=cat_name_form.cleaned_data['category_image'], ) logger.error(self.shop.id) cat_form = self.form_class(request.POST) for product_form in … -
run telegram bot inside a docker container with django app
I have a Django application and using "python manage.py name_bot_job" i start the bot, but when i add this task to the docker-compose file and make build, my bot just refuses to start, how can i do it with best practices? entrypoint: ["/bin/sh","-c"] command: - | python manage.py collectstatic --no-input --clear python manage.py migrate --noinput python manage.py createsuperuserwithpassword --username $${DJANGO_SUPERUSER_USERNAME} --password $${DJANGO_SUPERUSER_PASSWORD} --email $${DJANGO_SUPERUSER_EMAIL} --preserve gunicorn job_filter_app.wsgi:application --bind 0.0.0.0:8000 python manage.py poolbot -
How to automatically update model field if there are changes to the previous field?
I am trying to find a way to update the latest field in a model if there are changes in the earlier field. for example: say I have a Cash Balance model If I change the sale inv 134 debits to 50. how do I make this change reflect on the other cashbalance coming after it automatically -
how to pass data from a model to the url in django?
I have a customized user model like this: class Utilisateur(models.Model): username = models.CharField(max_length=50) email = models.CharField(max_length=50) password = models.CharField(max_length=50) phone = models.CharField(max_length=80) And i have my view declared this way: def profile(request): return render(request, 'profile.html') So i want my url to appear with username in it, something like this http://127.0.0.1:8000/profile/username1/ How can i pass the username to the url? -
Django-ckeditor: editor-element-conflict
Django-ckeditor in for loop shows correctly only for the first iteration. For the remaining iterations, the default template form appears as shown below. I see element conflict error in the documentation but it doesn't say anything how to solve. ckeditor.js:21 [CKEDITOR] Error code: editor-element-conflict. Thank you in advance! Here is my template code <div class="d-none" id="comment-{{answer.id}}" > {% for comment in answer.comment_set.all %} <div class="card mb-2" > <div class="card-body"> <p>{{comment.comment|safe}}</p> <p> <a href="#">{{comment.user.username}}</a> </p> </div> </div> {% endfor %} </div> <div class="d-none" id="commentForm-{{answer.id}}"> {% if user.is_authenticated %} <div class="commentform"> <form method="post"> <div class="form-group"> {% csrf_token %} {{ commentForm.media }} {{commentForm|crispy}} <input type="hidden" name="answerid" value="{{ answer.id }}"> <input type="submit" name="submit" value="Submit" > </div> </form> </div> {% endif %} -
Celery: Task registered but not fired from django
init.py from .celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tax.settings') app = Celery('tax') app.config_from_object('django.conf:settings') app.autodiscover_tasks() settings.py BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json', 'json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kathmandu' CELERY_IMPORTS = ('tax.tasks',) CELERY_ENABLE_UTC = False Version Python 3.8.10 flower==0.9.7 celery==4.3.0 Pip freeze aioredis==1.3.1 amqp==2.6.1 apns2==0.7.2 arabic-reshaper==2.1.3 asgiref==3.3.1 asn1crypto==1.5.1 async-timeout==3.0.1 attrs==20.3.0 autobahn==21.3.1 Automat==20.2.0 Babel==2.2.0 backcall==0.2.0 backports.zoneinfo==0.2.1 billiard==3.6.4.0 celery==4.3.0 certifi==2020.12.5 cffi==1.14.5 channels==3.0.3 channels-redis==3.2.0 chardet==4.0.0 click==8.1.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 constantly==15.1.0 coverage==6.2 cryptography==3.4.6 cssselect2==0.6.0 daphne==3.0.1 decorator==4.4.2 defusedxml==0.7.1 diff-match-patch==20200713 Django==3.1.7 django-allauth==0.44.0 django-anymail==8.6 django-cachalot==2.3.3 django-cors-headers==3.7.0 django-debug-toolbar==3.2 django-extensions==3.1.1 django-filter==2.4.0 django-grappelli==2.14.3 django-import-export==2.5.0 django-js-asset==1.2.2 django-mptt==0.12.0 django-nested-admin==3.3.3 django-phonenumber-field==5.0.0 django-push-notifications==2.0.0 django-rest-auth==0.9.5 django-rest-framework==0.1.0 django-seed==0.3.1 django-summernote==0.8.11.6 django-webpush==0.3.3 djangorestframework==3.12.2 drf-spectacular==0.22.1 et-xmlfile==1.0.1 factory-boy==3.2.1 Faker==9.9.0 flower==0.9.7 future==0.18.2 gunicorn==20.0.4 h2==2.6.2 hiredis==1.1.0 hpack==3.0.0 html5lib==1.1 http-ece==1.1.0 humanize==4.2.3 hyper==0.7.0 hyperframe==3.2.0 hyperlink==21.0.0 idna==2.10 importlib-resources==5.7.1 incremental==21.3.0 inflection==0.5.1 iniconfig==1.1.1 ipdb==0.13.5 ipython==7.21.0 ipython-genutils==0.2.0 jedi==0.18.0 jsonschema==4.5.1 kombu==4.6.11 lxml==4.8.0 Markdown==3.3.4 MarkupPy==1.14 msgpack==1.0.2 numpy==1.21.4 oauthlib==3.1.0 odfpy==1.4.1 opencv-python==4.5.4.60 openpyxl==3.0.7 oscrypto==1.3.0 packaging==21.3 parso==0.8.1 pdfrw==0.4 pexpect==4.8.0 phonenumbers==8.12.19 pickleshare==0.7.5 Pillow==8.1.1 pluggy==1.0.0 prometheus-client==0.8.0 prompt-toolkit==3.0.16 ptyprocess==0.7.0 py==1.11.0 py-vapid==1.7.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 Pygments==2.8.0 pyHanko==0.13.1 pyhanko-certvalidator==0.19.5 PyJWT==1.7.1 pyOpenSSL==20.0.1 pyparsing==3.0.6 PyPDF2==1.27.12 PyPDF3==1.0.6 pyrsistent==0.18.1 pytest==6.2.5 pytest-cov==3.0.0 pytest-django==4.5.1 pytest-spec==3.2.0 pytest-testdox==2.0.1 … -
Django views.py not rendering and giving error
i have an app called play, inside it i have made a templates folder and hello.html is saved there, in views.py I render hello.html it says hello is not defined Environment: Request Method: GET Request URL: http://127.0.0.1:8000/play/hello/ Django Version: 3.1.1 Python Version: 3.8.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'play'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\My Data\Programing\django\store\play\views.py", line 6, in say_hello return render(request, hello.html) Exception Type: NameError at /play/hello/ Exception Value: name 'hello' is not defined -
Django template tag accessing a queryset
i have a progression models : class Progression(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True ) started_module = models.ForeignKey(Module,on_delete=models.CASCADE,null=True,blank=True,) completedchapters = models.ManyToManyField(Chapter) class Meta: constraints = [ models.UniqueConstraint( fields=["started_module", "user"], name="unique_module_by_user" ) ] in my module view i have : def Module_Detail(request,module_slug): module = get_object_or_404(Module,slug=module_slug) context = { 'module' :module } return render(request,'courses/module-detail.html',context) in the module-detail template I want to do something like: {% if module in request.user.progression_set.all.started_module %} {{ you have already started this module }} {% endif %} but it does not seem to work -
Django filtering with select_related using Custom QuerySet, works in shell, fails in views
I am using Django 3.2 Below is a reduced portion of my code models.py class ItemQuerySet(models.QuerySet): def qualified(self): return self.filter(status=1) def training(self): return self.filter(status=2) def failed(self): return self.filter(status=3) def showable(self): Q1 = Q(status=1) Q2 = (Q(last_fields__isnull=False) & ~Q(last_fields__exact='')) return self.filter(Q1 | Q2) class Foobar(models.Model): # some fields objects_qualifiers = ItemQuerySet().as_manager() class Category(models.Model): pass class Foo(Foobar): title = models.CharField(max_length=16) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = models.TextField() is_done = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title views.py class FooListView(ListView): model = Foo template_name = 'foobar/index.html' context_object_name = 'foos' paginate_by = 5 ordering=['-created_at'] def get_queryset(self): return self.model.objects_qualifiers.showable().filter(is_done=True).all().select_related('author','category') When the view is accessed, it raises the following error: self.RelatedObjectDoesNotExist( foo.models.Foo.author.RelatedObjectDoesNotExist: Foo has no author. This (seems to) makes sense, because I am calling select_related on a QuerySet object - however, the error is a bit misleading, because it does identify and report the correct class (Foo) but then says that it has no author field. It would make sense if the error message said something like ItemQuerySet has no 'author' field. In order to test that my reasoning was correct, I decided to test my hypothesis in the shell: console output from foo.models import Foo foo = Foo.objects.get(id=1) foo.author … -
how to view models with foreign keys with serializers
Hi I am making a crud with serializers and I am having trouble viewing them.An error which I am unable to solve "ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')" models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) functions def insert(request): if request.method == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size ') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') print("insert clothes:",insert_clothes) serializer = POLLSerializer(data = insert_clothes) print('form:',serializer.initial_data) if serializer.is_valid(): serializer.save() messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print("invalid") print("error of serializer:",serializer.errors) return redirect('polls:insert') else: print('GET',id) return render(request,'polls/product_insert.html') def show(request): showall = Products.objects.filter(isactive=True) print("show all data:",showall) serializer = POLLSerializer(showall,many=True) return render(request,'polls/product_list.html',{"data":serializer.data}) can someone please point out to where I am going wrong?Thanks -
Prevent all data from being displayed with Django-filter
I am currently developing a search system using Django-filter. For example, if you search under the following conditions, all the displays will be returned. Data [ { "id": 1, "city": "aaa", }, { "id": 2, "city": "bbb", }, { "id": 3, "city": "ccc", } ] views.py class CitySearchView(APIView): def get(self, request): if not request.GET: raise Http404() queryset = City.objects.all() filterset = FilterCity(request.query_params, queryset=queryset) serializer = CitySerializer(instance=filterset.qs, many=True) return Response(serializer.data) filter.py class FilterCity(filters.FilterSet): city = filters.CharFilter(lookup_expr='icontains') class Meta: model = City fields = [] Request URL there is no value. http://127.0.0.1:8000/api/search/?city= Response [ { "id": 1, "city": "aaa", }, { "id": 2, "city": "bbb", }, { "id": 3, "city": "ccc", } ] My hope is to return the string "Not Found" or empty array[]. In that case, how should I implement it? Thank you. -
Why pagination provided by django rest framework is not consistent?
I am currently using Django-Rest framework to implement the API endpoints. I am following the documentation to implement the pagination, my pagination class is, class Pagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page' I am using this class as follows:- class QuestionList(generics.ListAPIView): queryset = Question.objects.all().prefetch_related('tags').order_by('id') serializer_class = QuestionSerializer pagination_class = Pagination For the first page, i am getting objects from id 1 to 10 which is expected. But from second page onwards, i am only getting 2 objects per page(id 3 and 4 for second page) and i cannot find any reason behind this strange behaviour. What should i do to make the pagination consistent. -
Flutter and Python Full Stack Solution with Cloud
I am interesting in building a solution for a Platform, knowing only Flutter and Python + Some SQL. Currently my thinking is towards having SQL/NoSQL DB (or via Cloud Provider's DB service), driven with Django RestAPI, and Frontend driven by Flutter. I am now sure how it would come together, hence asking advices on how the Stack Solution should be setup and whether there will be other languages I should learn? -
Accessing values in a JSON array and then assigning it to a textfield
My question is very simple. By using the DjangoJSONEncoder, I am able to send a JSON array of Model instances with the fields, product_number(pk) and amount as context to the HTML file. I then access the JSON array obj using some javascript code. The JS code: {{ data|json_script:"hello-data" }} <script type="text/javascript"> const data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(event){ alert(data); document.getElementById('id_line_one_unit_price').value = data[event.target.value].fields.amount }; </script> The array is: [[1, 56000], [2, 55000]] I think it's a string and not an array? I have a dropdown box and when the user selects a title from the dropdown menu, It returns the primary key of that title, and then using that, I want to retrieve the amount of that product from the JSON array and then set the value of a text field with that amount. views.py: def add_invoice(request): form = InvoiceForm(request.POST or None) total_invoices = Invoice.objects.count() queryset = Invoice.objects.order_by('-invoice_date')[:6] dataa = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(dataa), cls=DjangoJSONEncoder) if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/invoice/list_invoice') context = { "form": form, "title": "New Invoice", "total_invoices": total_invoices, "queryset": queryset, "data": data, } return render(request, "entry.html", context) models.py: from django.db import models class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', … -
Django Project in Visual Studio Community 2022 Edition
How to fix the python interpreter within Vs Community 2022 edition for Django project? After creating a project, created an environment. Within the environment, I've updated the Django version to 4.0.6 some days back. But today noticed that runserver shows Django version as 4.0.5 Need to know if the Visual Studio Community 2022 edition picks any other interpreter than the one created. Unable to figure it as google shows details for changing interpreter only with VS Code. Attaching the images for ref, Created Environment Default interpreters DjangoVersion in runserver -
Pass custom request header from views.py to models.py
I am receiving a customer header with the post request on views which I am able to access using request.META. I want to now pass this header to my data model as I need to check if this header is a particular string, then a particular action must not be performed i.e. the post save signal on the data model should be muted. -
How do object-relational databases store their data?
I use Django ORM, which according to objects creates tables in a database. I would like to more accurately understand the transformation process in order to create more effective data storage facilities. Unfortunately, I havn't found such information anywhere. -
Uncaught TypeError: data.find is not a function
I am trying to convert the model instances into a JSON object and then according to the value selected in the dropdown menu, I want to assign its amount to the line_one_unit_price text field in the form. Javascript code: {{ data|json_script:"hello-data" }} <script type="text/javascript"> const data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(event){ let elementInData = data.find(() => item.pk == event.target.value); document.getElementById('id_line_one_unit_price').value = elementInData && elementInData.amount ? elementInData.amount : 0; }; </script> I guess, I am getting the error at data.find because .find is used on an array whereas the constant data is not an array? How do I convert that JSON object into an array? how do I assign the amount of the title selected in the forms to the line_one_unit_price? When I click some title from the dropdown, I want the amount to be displayed in the Unit Price. views.py: def add_invoice(request): form = InvoiceForm(request.POST or None) data = serializers.serialize("json", Inventory.objects.all()) total_invoices = Invoice.objects.count() queryset = Invoice.objects.order_by('-invoice_date')[:6] if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/invoice/list_invoice') context = { "form": form, "title": "New Invoice", "total_invoices": total_invoices, "queryset": queryset, "data": data, } return render(request, "entry.html", context) models.py: class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, … -
Having trouble with this error ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')
I am tasked to do this with serializers and foreign keys and I am new to this concept and doing a CRUD where I am struggling with this error: "ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')" model class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) insert function def insert(request): if request.method == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size ') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') print("insert clothes:",insert_clothes) serializer = POLLSerializer(data = insert_clothes) print('form:',serializer.initial_data) if serializer.is_valid(): serializer.save() messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print("invalid") print("error of serializer:",serializer.errors) return redirect('polls:insert') else: print('GET',id) return render(request,'polls/product_insert.html') Can someone tell me how I am supposed to call thier IDs?thanks -
Running Test Cases in Django, just like testcases in leetcode, codesignal and codewar
Does anybody knows, how we can run test cases on a data(function) sent by the user in Django, (as implemented by leetcode, codesignals and codewar) -
AttributeError at /invoice/add_invoice/ 'int' object has no attribute '_meta' while using in_bulk
I want to convert the model instances into a JSON object and then pass it to the HTML file. However, I get an AttributeError at this line: data = serializers.serialize("json", Inventory.objects.in_bulk()) The full views.py: def add_invoice(request): form = InvoiceForm(request.POST or None) data = serializers.serialize("json", Inventory.objects.in_bulk()) total_invoices = Invoice.objects.count() queryset = Invoice.objects.order_by('-invoice_date')[:6] if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/invoice/list_invoice') context = { "form": form, "title": "New Invoice", "total_invoices": total_invoices, "queryset": queryset, "data": data, } return render(request, "entry.html", context) The Javascript code: {{ data|json_script:"hello-data" }} <script type="text/javascript"> const data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(event){ document.getElementById('id_line_one_unit_price').value = data[event.target.value].fields.amount; }; </script> models.py: class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, default='', blank=True, unique=True) amount = models.IntegerField('Unit Price', default=0, blank=True, null=True) def __str__(self): return self.title How can I pass that JSON object and assign the amount value to the text field according to the object selected in the dropdown? Thanks -
Django nginx staticfiles 404
I am trying to get my head around nginx serving Dockerized Django static files behind a https proxy. I was trying to mostly follow this tutorial: https://testdriven.io/blog/django-lets-encrypt/ This was all working on my local machine so I moved to a remote server running at a real domain behind an https reverse-proxy. I have a docker-compose.yml like this: backend: ... volumes: - ./backend/:/code/ - static_volume:/code/staticfiles - media_volume:/code/mediafiles ... nginx-proxy: ... volumes: - static_volume:/code/staticfiles - media_volume:/code/mediafiles ... depends_on: - backend I have a default file in vhost.d directory with the following directives: location /static/ { alias /code/staticfiles/; add_header Access-Control-Allow-Origin *; } location /media/ { alias /code/mediafiles/; add_header Access-Control-Allow-Origin *; } my nginx docker files is the following: FROM jwilder/nginx-proxy:0.9 COPY vhost.d/default /etc/nginx/vhost.d/default COPY custom.conf /etc/nginx/conf.d/custom.conf my Django settings.py: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' I am collecting the files at backend boot and if I exec to either the backend or nginx-proxy services I can find my files at the correct location: /code/staticfiles/... # all the files are here in the right place... So I "assume" the volumes are correct. /vhosts.d/default is also present and at the correct location when i log into the nginx service. The HTTPS reverse-proxy works … -
Using django and react together
I'm making an SSR website using Django, Gunicorn, and Nginx. As I'm familiar with react and I'd like to use some of its libraries like redux, tailwind with daisyui, etc... it would be great if I could use React for the frontend and Django for the backend. I am aware I can use Django just as a rest framework and then run react separately as a CSR, SSG app, or even ssr using something like nextjs but my goal is to keep most of the react functionality, share the codebase, use Django to render the react pages essentially as a replacement for react-router, and optimize SEO. I was wondering what the best way to integrate them is? I know generally, it's common to separate react and Django but I'd like to use Django as the router/renderer for the react app as I believe it would be more performant to use one server for both the API and the website. I also plan on using django-hosts to render the react templates in two Django apps with different hostnames. Note: I don't need to be able to use the normal django templating