Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializing two CharFields into one object
I have serializer like this below. Now I have separated fields for store_photo and store_name. class ProductSerializer(serializers.ModelSerializer): store_photo = serializers.CharField(source='store.photo', read_only=True) store_name = serializers.CharField(source='store.name', read_only=True) class Meta: model = Product fields = ['store_photo', 'store_name', ...] Can I somehow serialize it together in one object? I mean something like this: store = {store_photo, store_name} class Meta: model = Product fields = ['store', ...] -
Where do I store the encryption key when encrypting in Django?
I am creating a website using Django, my website will encrypt uploaded files and another user can then download the files unencrypted. It's pretty straightforward encrypting in python, but where do I store the encryption key? I encrypt the files in case the database or source code has been compromised. Then I can't store the encryption key as a file or in the database. Where can I store the encryption key? Thank you -
Django Framework or Not
Hello guys I'm working on a survey form website with DJango And I want user to generate a code to embed on their website Examples <!-- Start of HubSpot Embed Code --> <script type="text/javascript" id="hs-script-loader" async defer src="//js-na1.hs-scripts.com/22614219.js"></script> <!-- End of HubSpot Embed Co <script src="//code.tidio.co/uqkwgjeoo7leire6zsukpluyum8zqmme.js" async></script> And I don't know how to do it Will I use The Django Framework If yes drop resources to help me work it out (Without Framework) And still if no I don't still know how to do it DJango Drop resources to help me do it normal way in Django with framework -
Access static method variable in Generic APIView Post method
I have a custom static method in my GenericAPIView previously the calls create and complete() were in try and except for each task it tries and except logger.error(called) in post method instead i removed try and except from each task and created new method and catching the exception while calling the method but its not working how can i access task used in my_static_method in my post method in exception class MyAPIView(GenericAPIView): @staticmethod def my_static_method(arg1, arg2, arg3): if arg3 and not arg2.value: task = task1(arg1) task.create() task = task2(arg1) task.complete_task() if arg1.somevalue() or arg1.someotherValue(): task = task3(arg1=arg1) task.complete_task() def post(self, request, *args, **kwargs): try: self.my_static_method(self.arg1, arg2, self.arg3) except Exception: logger.error(f"Error executing the {task.__class__.__name__}", exc_info=True) -
How to get last created item's id by django restframwork in react
def create(self, request): serializer = TodoItemSerializer(data=request.data) if serializer.is_valid(): device = serializer.save() device = device.id return Response(device, status=status.HTTP_201_CREATED) it is working. How can i get this device item in react i have a api call like this, i tried console.log(response.device) but returned "undefined". How can i access the device item ? const response = await fetch("http://localhost:8000/api/todoitems/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: this.state.title, description: this.state.description, due_date: this.state.date, creator: this.state.userId }) }); if (response.status === 201) { console.log(response) toast.success('Success', { toastId: 'success1', position: toast.POSITION.TOP_CENTER }) } else { alert("Something went wrong!"); } -
Django Forms translate standard error message
All my translations work except the error messages generated by forms. This is the start of my form: class MyForm(forms.Form): first_name = forms.CharField(label=_("First name"), min_length=3, required=True) Now the label "First name" translates fine to "Vorname" because I made a .po file and compiled etc.. However when entering only 2 characters the resulting error is in English and not in (this case) German, see screen print below. I have looked in Github Django repository django/conf/locale/de etc. but could not find the string "Please lengthen etc." there. So my question is: how do I get this error message to translate? I assume Django has a standard method and that this string is already in some .po file somewhere within the Django project? -
Why queryset returns value instead of instance in Django Views?
My Problem I have a queryset in Django View. That queryset should return an instance. But instead of that it returns a value Models.py class Author(models.Model): name = models.CharField(max_length=250, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('authors:author_detail', args=[str(self.id)]) class Meta: verbose_name = 'Author' verbose_name_plural = 'Authors' Projects URLS.py urlpatterns = [ path('admin/', admin.site.urls), path('author/', include('authors_app.urls', namespace='authors')), ] authors_app ULRS.py from .views import * app_name = 'authors' urlpatterns = [ path('<int:pk>/', AuthorDetail.as_view(), name='author_detail'), ] Views.py class AuthorDetail(ListView): model = Book context_object_name = 'author_books' template_name = 'author-detail.html' queryset = Book.objects.all().order_by('bookinfo__bestseller') paginate_by = 36 def get_queryset(self, **kwargs): author_id = Author.objects.get(pk = self.kwargs['pk']) print(author_id) qs = super().get_queryset(**kwargs) return qs.filter(author = author_id) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet context['author'] = Author.objects.get(pk = self.kwargs['pk']) # context['image'] = f"/mnt/HDD/wiki/parser/images/photos/10.png" return context When I open authors page - mysite.com/author/51/ I've got an Error: Cannot query "Lawrence Gilman": Must be "Author" instance. Question How can I get an instance in that queryset? -
How edit products without forms.py Django?
I need create and edit products witout forms.py. How i can do this. If u can with example <form method="post"> {% csrf_token %} <input type="text" placeholder="Название"><br> <textarea placeholder="Текст статьи" rows="8" cols="80"></textarea><br> <input type="date"><br> <button type="submit">Добавить статью</button> </form> -
How to create private endpoint for postgres server using azure python sdk
I want to create private endpoint for postgres server using azure python sdk. I need some sample code that i can refer. explored documentation but didn't get relevant information. -
Git repository corrupted and changed files are empty after PC crash
I was working with git bash, rebasing and stashing my changes when suddenly my PC crashed. After the restart, the disk was repairing, but when it loaded the repository no longer worked, git commands returned: fatal: not a git repository (or any of the parent directories): .git All the files that I have not committed are now blank, the changes are gone. HEAD files and stash are also corrupted. I am in a panic mode. What can I do in this situation to recover lost files and restore the repository to the previous state? -
Having issues implementing Stripe in my Django Code
I am implementing a stripe charge in my django ecommerce project. So In my views, I am trying to get the data from an input element in a form, then pass into a variable in the views. Here is the Javascript that creates the input element var form = document.getElementById('stripe-form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit() So in the views.py, I have this: token = form.cleaned_data.get('stripeToken') save = form.cleaned_data.get('save') use_default = form.cleaned_data.get('use_default') print(form.cleaned_data) the print(form.cleaned_data) returned a dictionary {'stripetoken':'', 'save': False, 'as_default': False} stripetoken maps to the token variable, and as you can see its value is empty. The last two variables that maps to the last two keys in the dictionary returned values. The token = form.cleaned_data.get('stripeToken') is supposed to get this hiddenInput.setAttribute('value', token.id); right? When I tried getting the value of token.id, I got a response. I used Javascript alert(token.id) to do that, and I got a value displayed in my browser. So I don't know what exactly is wrong. Can someone help me out on this one? -
Django filter_horizontal - how to connect more fields together
I need to connect more fields to one filter_horizontal parameter in Django Admin. I have three many-to-many variables: class EducationTypeAdmin(admin.ModelAdmin): ... list_filter = ("qualifications", "school_levels", "subject_groups") filter_horizontal = ["qualifications", "subject_groups", "school_levels"] This code will make 3 seperate many-to-many horizontal filters. I need them to be in one. Ex in admin: AS, English, High School --> -
Run python script in Django and produce live output buffer on the web
I am a beginner to Django web framework. I have a bunch of python scripts which runs and produce output on cli at present but I want the same scripts to run from django web and display live buffer output Can anyone shed some light on how to achieve it -
Tried inheriting dispatch in django
Hi I was trying to inherit the dispatch using super store it in a variable and then log the errors: my code looks like def dispatch(self, request, *args, **kwargs): response = super().dispatch(request, *args, **kwargs) if response.status_code == 400: logger.error(response.json) logger.error(request.payload) return super().dispatch(request, *args, **kwargs) and the error is : Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/src/app/api/views/researcher_dashboard/cv.py", line 54, in dispatch logger.error(response.json) and for request.headers it is : Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/src/app/api/views/researcher_dashboard/cv.py", line 54, in dispatch logger.error(response.json) -
Admin administration without ForeignKey
i need to put 2 models in one page on Admin administration without ForeignKey admin.py class MobileAppInline(admin.StackedInline): model = MobileApp class HomeAdmin(admin.ModelAdmin): inlines = [MobileAppInline,] admin.site.register(Home, HomeAdmin) -
Cannot unpack non-iterable SerializerMethodField object in Django DRF
I'm trying to assign the list from SerializerMethodField() return to a set of two fields, as: class PostSerializer(serializers.ModelSerializer): postvotes, postvote = serializers.SerializerMethodField() def get_postvotes(self, obj): qset = PostVote.objects.filter(Q(post=obj)) votes = [PostVoteSerializer(m).data for m in qset] vote = sum(vote['vote'] for vote in votes) return [votes, vote] # votes[], vote: Integer However, this fails with the title-metioned error. How can I solve this? Thanks. -
I am getting an error in the second line of the code showing unexpected token... I have also added bootstrap4 in installed apps
enter image description here {% load bootstrap4 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Learning Log</title> {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} </head> I have aslo added bootstrap4 in installed apps in settings .py INSTALLED_APPS = [ # My apps "learning_logs", "users", # Third party apps. "bootstrap4", -
My Django website is not working with Https on AWS [closed]
Recently i have deployed my django website on Amazon web services Ec2 instance and i am using window Free Tier where i have copied my code and then run on that Remote Desktop that is working fine on my instance ipv4 adress http://3.131.202.237/ but problem is that this is not secure.My website is working as expected.But i want to work it with https ssl certificate.but when i try to open https://fableey.com ,chrome shows me error site cannot be reached.Whats the problem there. Allowed Hosts is set to ['*']. Now i also had installed SSL certificate on Amazon certificate manager and that is active & in use now but still my website is not opening on https://fableey.com ,rather it is opening on http:fableey.com. Now what i want ? I just want to work my website on https also.Please help me !!! Thanks!!! -
Using the http.HTTPStatus class in Python to return the meaning of a HTTP status code
I'm trying to write a block of code to return the meaning (description) of an HTTP status code using the http.HTTPStatus Python class. I read the docs, but it seems I can only do the reverse. Is there way I can do this? try: if resp.status != 200: message = -
Django (Ngninx, Gunicorn) : manage dev, test and prod code of a given application
I have a Django application running with Nginx and Gunicorn on a remote server. We would like to get several versions of the same application: production, test and development, using URLs like: https//:www.domain.com (production) https//:www.domain.com/test/ (test version) https//:www.domain.com/dev/ (development version) I don't have a clue about the best strategy to adopt since people will only work on the application code and not at a higher level (project, server) My first idea was to simply duplicate the application within the same project: a copy for dev, and a copy for test, but according to the templates engine I was not able to execute the correct .html files Maybe, another way would maybe to deploy two new projects dedicated to dev and test? but I'm not sure how to proceed. The last way would be to create a fresh new django instance for each, but i'm lost about the way to setup my Nginx and Gunicorn settings accordingly to make everything working. May you please give me advices about the best way to proceed regarding your experience ? Thank you very much for your help !! :) Regards -
Font Awsome on a django project
Iḿ trying to put a icon on my website but it doesn't appear. Bellow is the html of the Icon that i got from fontawsome icons. <i class="fa-solid fa-chopsticks"></i> -
my problem was about rendering html document in django application [closed]
""" this is my view.py file in which i created in order to make view on my html document from urllib import response from django.shortcuts import render from django.http import HttpRequest def index(request): return response(request,'good/try.html') and also i create the path in urls.py file from django.urls import path from. import views urlpatterns = [ path('',views.index) ] My simple html document: <!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>Document</title> </head> <body> <p> many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). </p> </body> </html> but when I try to render my html page it raise an error which was: TypeError at / 'module' object is not callable in the browser -
Django registered namespace, however, post request returns 404
I have such a structure in my project. *************** Directory Tree *************** dealerpanel/ ├── __init__.py ├── api/ │ ├── serializers/ │ │ ├── customer.py │ ├── urls.py │ └── views/ │ ├── payzee_redirect.py ├── apps.py ├── templates/ │ └── payzee-redirect.html ├── tests/ │ ├── api/ │ │ ├── test_payzee_redirect.py └── validators/ ├── utils.py └── validators.py The view I want to work with is payzee_redirect.py This view looks as follows: import time from django.db import transaction from rest_framework.parsers import FormParser from rest_framework.renderers import TemplateHTMLRenderer from rest_framework.request import Request from rest_framework.response import Response from rest_framework.views import APIView from apps.customer.models import PayzeeOrder from apps.dealerpanel.api.serializers.payzee import PayzeeSerializer from libs.settlement.constants import PaymentStatus class PayzeeRedirectView(APIView): authentication_classes = [] permission_classes = [] parser_classes = (FormParser,) renderer_classes = (TemplateHTMLRenderer,) template_name = "payzee-redirect.html" MAX_TRY = 4 def post(self, request: Request, *args, **kwargs) -> Response: return Response( {"is_error": False, "invoice_id": order.invoice.invoice_id}, template_name=self.template_name ) urls.py as follows: from django.urls import path from .views.payzee_redirect import PayzeeRedirectView app_name = "dealerpanel" urlpatterns = [ path("payzee/redirect/", PayzeeRedirectView.as_view(), name="payzee_redirect"), ] test_payzee_redirect.py class PayzeeRedirectiewTest(APITestCase): @classmethod def setUpTestData(cls): cls.host = TR.api_host baker.make("api.Eshop", scoring_category=baker.make("api.ScoringCategory")) invoice = baker.make("api.Invoice") baker.make("customer.PayzeeOrder", invoice = invoice) def test_payzee_order_does_not_exist(self): # Given data = { "OrderId": uuid4(), "ResponseCode": "00" } # When response = self.make_request(data) # … -
How to work with admin inline forms in Django crispy-forms
I ran into a problem when using crispy-forms. I have fields that I display through crispy layout. class OptionOfProductInline(admin.TabularInline): form = OptionOfProductInlineForm model = OptionOfProduct extra = 1 class ProductForm(forms.ModelForm): class Meta: model = Product fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-exampleForm' self.helper.form_class = 'blueForms' self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.form_tag = False self.helper.layout = Layout( TabHolder( Tab("Основні налаштування", HTML("<div class='tab_name'>Основні налаштування</div>"), Div( Div("article", "price", css_class='two_in_line'), Div(Div(HTML(_("<div>Availability</div>")), "availability", css_class="form-group"), "percent_sale", css_class='two_in_line'), Div("qty", "date_start_sale", css_class='two_in_line'), Div("unit_fk", "date_end_sale", css_class='two_in_line'), Div(Div(HTML(_("<div>Publish</div>")), "publish", css_class="form-group"), "order", css_class='two_in_line'), css_class="left_side"), Div( Div("image"), Div("qty_min_order"), Div("brand_fk"), Div("category_fk"), Div("show_in_categories"), css_class="right_side"), css_class="two_cols"), Tab("SEO", HTML("<div class='tab_name'>SEO</div>"), Div( Div(*name, css_class='column_fields'), Div(*slug, css_class='column_fields'), Div(*h1, css_class='two_in_line'), Div(*title, css_class='row_fields'), Div(*meta_description, css_class='field_description'), Div(*description, css_class='field_description'), css_class='name_slug'), css_class="center_side", ), ), ) @admin.register(Product) class ProductAdmin(TabbedTranslationAdmin): form = ProductForm add_form_template = "admin/my_form.html" change_form_template = "admin/my_form.html" The fields look like on this screenshot: https://i.imgur.com/lLL2G23.jpg. The "Inline" tab should contain formsets that look like this screenshot: https://i.imgur.com/nKOntVV.jpg and I want to output this formset through Layout. I tried to output like this, but it didn't work :( Tab("Inline", OptionOfProductInline, css_class="some_class",) OptionOfProduct and OptionOfProductInlineForm: class OptionOfProduct(models.Model): product_fk = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) option_value_mtm = models.ManyToManyField(OptionValue, null=True, blank=True) article = models.CharField(verbose_name=_('article'), null=True, blank=True, max_length=255) price = … -
How to fetch specific elements using dropdown list django
I am new to django and I am trying to show total employees and employees on each department in a table using a dropdown list. Dropdown code : <label>Depart</label> <select class="custom-select" style="width: 200px" id="depart"> <option value="Total">Total</option> {% for key,value in uv.items %} <option value="{{ value }}">{{ key }}</option> {% endfor %} </select> Table code : <table class="table table-striped"> <tr class="thead-dark "> <th>ID</th> <th>Nom et Prenom</th> <th>Lundi</th> <th>Mardi</th> <th>Mercredi</th> <th>Jeudi</th> <th>Vendredi</th> <th>Samedi</th> <th>Dimanche</th> </tr> {% for i in employe %} <tr> <td>{{ forloop.counter }}</td> <td>{{ i.name }} </td> <td>{{ i.monday }}</td> <td>{{ i.tuesday }}</td> <td>{{ i.wednesday }}</td> <td>{{ i.thursday }}</td> <td>{{ i.friday }}</td> <td>{{ i.saturday }}</td> <td>{{ i.sunday }}</td> </tr> {% endfor %} </table>