Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe Webhook In production Error 500 - Python
I am getting an error 500 on my webhook when I try to test it in production, however it worked fine when testing using the CLI. Here is my webhook view: @csrf_exempt def stripe_webhook(request): # You can find your endpoint's secret in your webhook settings endpoint_secret = 'secret12345' payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] fulfull_order(session) return HttpResponse(status=200) The above view returns error 500. Here is the request data from stripe: { "created": 1326853478, "livemode": false, "id": "evt_00000000000000", "type": "checkout.session.completed", "object": "event", "request": null, "pending_webhooks": 1, "api_version": "2020-08-27", "data": { "object": { "id": "cs_00000000000000", "object": "checkout.session", "allow_promotion_codes": null, "amount_subtotal": null, "amount_total": null, "billing_address_collection": null, "cancel_url": "https://example.com/cancel", "client_reference_id": null, "currency": null, "customer": null, "customer_details": null, "customer_email": null, "livemode": false, "locale": null, "metadata": { }, "mode": "payment", "payment_intent": "pi_00000000000000", "payment_method_options": { }, "payment_method_types": [ "card" ], "payment_status": "unpaid", "setup_intent": null, "shipping": null, "shipping_address_collection": null, "submit_type": null, "subscription": null, "success_url": "https://example.com/success", "total_details": null } } } I am trying to set up the … -
How to override Django's default response code?
I have two classes in my views.py to handle GET all users, GET one user and POST a new user. If I try to post a user with an id that already exists, Django throws the default 400 - bad request -error. What I'd like to do is send a 409 conflict error instead. How could I achieve this? I tried and succeeded to get the request when posting new object, but I don't know how to get the response. These are my classes: class UserListView(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] class UserView(generics.RetrieveUpdateDestroyAPIView): permission_classes = (permissions.AllowAny) queryset = User.objects.all() serializer_class = UserSerializer -
Django template filter count
How can i count in template in view {% for subject in subjects %} {% if subject.course.id == courses.0.id %} <li> <a href="p/teacher_list/?lessonFilter={{ subject.id }}">{{ subject.subject_name }} {% for tp in t_price %} {% if tp.subject_id.id == subject.id %} {{tp.count}} {% endif %} {% endfor %} </a> </li> {% endif %} {% endfor %} I want to show how many teachers chose this subject. Is there possible way to count in template. tp Model class Teacher_lesson_price(models.Model): id = models.AutoField(primary_key=True) teacher_id = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=False) subject_id = models.ForeignKey(Subject, related_name='subject_name_rel', on_delete=models.CASCADE, null=False) course_id = models.ForeignKey(Course, on_delete=models.CASCADE , null=False, default=None) price = models.CharField(max_length=250) created_at = models.DateTimeField(default=timezone.now) -
Django Rest Framework - reduce queries and increase performance for SerializerMethodField()
I have a model like this with relationship Booking -- Payment (one to may) (one Booking can have many Payments) My problem is that I calling too many expensive queries because of SerializerFieldModel(). class Booking(AbstractItem): accommodation = models.CharField(max_length=100) room = models.CharField(max_length=100) booking_method = models.CharField(max_length=100) class Payment(AbstractItem): booking = models.ForeignKey(Booking, on_delete=models.CASCADE) # paid, refund status = models.PositiveIntegerField(choices=core_choices.PAYMENT_STATUS, default=core_choices.PAID, null=True) # cash, credit_card, transfer payment_method = models.PositiveIntegerField(choices=core_choices.PAYMENT_METHOD, default=core_choices.CASH) price = models.DecimalField(max_digits=10, decimal_places=0, null=True) This is my serializer class BookingXLSXSerializer(ModelSerializer): paid_cash = SerializerMethodField() paid_card = SerializerMethodField() refund_cash = SerializerMethodField() refund_card = SerializerMethodField() class Meta: model = Booking fields = ('id', 'accommodation ', 'room', 'booking_method', 'paid_cash', 'paid_card', 'refund_cash', 'refund_card') def get_paid_cash(self, obj): payments = Payment.objects.filter(booking=obj.id, status=core_choices.CASH) cash = 0 for payment in payments: cash += payment.price return cash ... this is my view: class MyExampleViewSet(ListAPIView): queryset = Booking.objects.all() serializer_class = BookingXLSXSerializer pagination_class = SuperLargePagination I noticed that many SerializerMethodField() could share query and use different filter. Is there a smarter way to reduce calling queries for SerializerMethodField(). Or maybe a way to share the query? -
can't open manage.py file on Django (m1 Mac)
this is how error is shown on terminal I have tried using virtual envirnorment -
Python create password protected zip in-memory for Django HttpResponse
I would like to generate a password-protected Zip file for my csv data in memory and return to webpage via Django HttpResponse. So far I can generate zip file without password protection as follows: from django.http import HttpResponse import io, csv, zipfile, subprocess #... # write csv in buffer buffer_string_csv = io.StringIO() writer = csv.writer(buffer_string_csv) writer.writerow(['foo','bar']) # write zip in buffer buffer_zip = io.BytesIO() zip_file = zipfile.ZipFile(buffer_zip, 'w') zip_file.writestr('foobar.csv', buffer_string_csv.getvalue()) zip_file.close() # return zip file as response response = HttpResponse(buffer_zip.getvalue()) response['Content-Type'] = 'application/x-zip-compressed' response['Content-Disposition'] = 'attachment; filename="foobar.zip"' return response From Python code to create a password encrypted zip file? , I learned password-protecting Zip file may require 7-Zip utility. subprocess.run(['7z', 'a', '-pPASSWORD', '-y', 'password_foobar.zip'] + ['foobar.csv']) Is it possible to do that in-memory ? -
Python Django equivelant of preloading in Elixir Ecto
So I am coming from Elixir and Phoenix Background now working in a Django project. At this stage I am investigating the ORM part of Django and I have the following question Assume a model like the following class Shop(models.Model): name = models.TextField() class Product(models.Model): name = models.TextField() shop = models.ForeignKey(Shop) At this point in Ecto you can do something like the following shop = Context.get_by_id(1) shop = preload(shop, :products) and the result would be %Shop{ name: "Some name", products: [ %Product{}, %Product{} ] } Taking care of all the necceesary joing queries behind the scene is there any similar functionality when working with Django ? -
Django NoReverseMatch Error on Update and Delete Buttons
Thank you for reading my question, and for your help. I wrote a simple CRUD app, and used django-tables2 module to make my tables look pretty and more robust. I am using django 3.2, python 3.8.5, django_tables2 2.3.4. I can enter a query in the search bar on the home.html page and lists the returned results from a postgresql on the search_results.html page. On the search_results page, I have buttons next to each returned row with edit and delete options, when I hover over update buttons it points to url for localhost:8955/update/7887 or localhost:8955/delete/7887 for the delete button, of course the last four digits are unique to the returned rows, however when I click on the update or delete button I get a NoReverseMatch error. I am at my wits end what is causing the edit and delete buttons not to work, your help and assistance is very much appreciated it. Image with the returned results with the update and delete button tables.py from .models import EsgDatabase from django.urls import reverse_lazy from django.contrib.auth.models import User as user class EsgListViewTable(tables.Table): class Meta: model = EsgDatabase template_name = "django_tables2/bootstrap-responsive.html" fields = ('id','role', 'hq','system','market','state','zone','arrisseachangezone','xgsystem','xgzonecode','fto','xocnoc','snowticketassignment',) if user.is_authenticated: edit = TemplateColumn(template_name='update.html') delete = TemplateColumn(template_name='delete.html') app … -
Djongo (mongoDb) - Django rest framework Problem with search on JsonFields
I have a problem with filtering on JsonFIleds in Django REST API on MongoDB. I use djongo to connect with MongoDB. Every time I get this error: raise FieldError( django.core.exceptions.FieldError: Unsupported lookup 'seq' for JSONField or join on the field not permitted. [11/May/2021 10:21:00] "GET /rest/broker/topic/?decode_message_seq=34 HTTP/1.1" 500 21577 I would like to search for information in saved json in the database. In the code below it tries to search for data where the decode_message field contains the seq field. I searched the forums and documentation and couldn't find an answer to my bug. Model: from django.db import models from djongo.models import JSONField, DjongoManager class Topic(models.Model): topic = models.TextField(max_length=250) message = JSONField() decode_message = JSONField(blank=True, null=True) create_at = models.DateTimeField(auto_now_add=True, null=True) objects = DjongoManager() Serializer: from .models import Topic from .utilis import decodeMqttMessage from rest_framework import serializers class TopicSerializer(serializers.HyperlinkedModelSerializer): message = serializers.JSONField() decode_message = serializers.JSONField() class Meta: model = Topic fields = ['id', 'topic', 'message', 'decode_message', 'create_at'] def create(self, dict, *args, **kwargs): topic = dict.get('topic', None) message = dict.get('message', None) decode_message = decodeMqttMessage(message) new_broker_info = Topic.objects.create(topic=topic, message=message, decode_message=decode_message) new_broker_info.save() return new_broker_info Filters: import django_filters from .models import Topic class TopicFilter(django_filters.rest_framework.FilterSet): decode_message_seq = django_filters.CharFilter(field_name="decode_message__seq", lookup_expr='icontains') class Meta: model = Topic fields = … -
How to put conditions in the password field?
I am creating a system with Django. I already created a login page in the beginning of the project. But now, I realized that I have no conditions for password field. I want to put some restrictions like 8 characters, uppercase and lowercase letters and numbers. How can I check this when user fills the form? forms.py class SignUpForm(forms.ModelForm): password1 = forms.CharField(max_length=250, min_length=8, widget=forms.PasswordInput) password2 = forms.CharField(max_length=250, min_length=8, widget=forms.PasswordInput) class Meta: model = UserProfile fields = ( 'first_name', 'last_name', 'email', 'password1', 'password2', 'rank', 'image') labels = { 'email': 'E-mail', 'password1': 'Please Generate A Strong Password', 'password2': 'Please Confirm the Password', 'rank': 'Position' } widgets = { 'password1': forms.PasswordInput(), 'password2': forms.PasswordInput(), } def __init__(self, *args, **kwargs): # using kwargs user = kwargs.pop('user', None) super(SignUpForm, self).__init__(*args, **kwargs) self.fields['password1'].label = 'Please Generate A Strong Password' self.fields['password2'].label = 'Please Confirm the Password' models.py class UserProfile(AbstractUser, UserMixin): ... last_name = models.CharField(max_length=200) password = models.CharField(max_length=250) views.py def signup(request): current_user = request.user new_user = UserProfile(company=current_user.company) form = SignUpForm(request.POST or None, user=request.user, instance=new_user) rank_list = Rank.objects.filter(company=current_user.company) if request.method == 'POST': if form.is_valid(): form.instance.username = request.POST.get('email', None) new_user = form.save() new_user.refresh_from_db() # load the profile instance created by the signal new_user.is_active = False if form.cleaned_data['password1'] != "": new_user.set_password(form.cleaned_data['password1']) new_user.save() … -
(Django and React) I am unable to delete an user from my userlist. (HTTP Status Code 404)
I am following a tutorial, where I am attempting to delete an user from the user list as an Admin of the website. Even though it can be done from the django administration as well, in the tutorial we are trying to do this directly on the website itself. It is being done on the page, which is accessible only for the admin. http://localhost:3000/admin/userlist The thing is, that when I try to delete some user, (by clicking on an button, (icon) which is placed on the webpage) I am getting this error in my console - xhr.js:177 DELETE http://localhost:3000/api/users/delete/3/ 404 (Not Found) In my django terminal, I am getting this error - Not Found: /api/users/delete/3/ [11/May/2021 09:57:38] "DELETE /api/users/delete/3/ HTTP/1.1" 404 3479 Please take a look at the relevant parts of the codes - (I have triple checked the following codes with the ones, that are in the tutorial and they seem to be the same and that is why I would really appreciate some help, because it is working for my instructor, but not for me) user_views.py - @api_view(['GET']) @permission_classes([IsAdminUser]) def getUsers(request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) user_urls.py (inside urlpatterns) - path('delete/<str:pk>', views.deleteUser, name='user-delete') userConstants.js … -
How to deploy ReactJS/Django project on DigitalOcean
I am building web application with django as a backend and reactJS as a frontend. I need to know which hosting solution works best for me ? What I am looking for: I need to store a lot of images so I need a lot of disk space (my estimate around 500GB at a moment) Currently, there would only be 50 users of my app using my website 24/7 so right now I may not need huge amount of computing power but I may be doing some face recognition or detection on around 10,000 per day. Also, I am not sure how this django + react app works with deployment so if you can guide me ? like cloud hosting or linux virtual machine? I have no idea about it which is best in terms of performance+pricing Thanks in advance -
Currency not showing in Sum of a MoneyField
I have a MoneyField something like this: sample_money_field = MoneyField( decimal_places=2, max_digits=14, default_currency='USD', default=Decimal(0) ) When I try to sum the values for this field, it only gives me the value but it does not give the currency. @property def total_sample_money(self) -> Money: sample_money = self.sample_money_field_set.all() sample_money_sum = sample_money.aggregate(Sum('sample_money_field'))[ 'sample_money_field__sum' ] return sample_money_sum # return 0.00 instead of 0.00 USD Is there a way to show the currency too? I know I could probably do something like this: return Money(sample_money_sum, 'USD') but I'm hoping it would be more flexible if it makes sense -
How do I display certain information from SQLite Database?
I would like to display information obtained from an SQLite Database, but I would only want the data to be displayed that is related to the user. Since the email of each user is unique, I want it to see if it matches the email of the current signed user. Below is the code for the corresponding view above def viewclaims(request): context = initialize_context(request) user = context['user'] claims = SaveClaimForm.objects.all() return render(request, 'Login/existingclaims.html', {'claims':claims, 'user':user}) -
How can I link from homepage to another details page depending on a specific argument in for loop? - Django
I am learning django and during a project given I've stuck in linking the home.html to specific details.html My code is the following: urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('details/<statename>', views.details, name='details') ] views.py from django.shortcuts import render # This is the dictionary for all the attractions attractions = [ { 'attraction_name' : 'Niagra Falls', 'state' : 'New York'}, { 'attraction_name' : 'Grand Canyon National Park', 'state' : 'Arizona'}, { 'attraction_name' : 'Mall of America', 'state' : 'Minnesota'}, { 'attraction_name' : 'Mount Rushmore', 'state' : 'South Dakota'}, { 'attraction_name' : 'Times Square', 'state' : 'New York'}, { 'attraction_name' : 'Walt Disney World', 'state' : 'Florida'} ] def home(request): # The context is all of the variables we want passed into the template. context = {"attractions" : attractions} return render(request, 'tourist_attractions/home.html', context) def details(request, statename): # We replace the dash with a space for later ease of use. The dash is there because of the slugify filter. context = {"attractions" : attractions, "statename" : statename.replace("-", " ")} return render(request, 'tourist_attractions/details.html', context) home.html (I tried to link from home page to details/<statename> page using for loop) {% block content %} <h1>This is a … -
not able to filter data in graphql django showing error
just started graphql and i am able to fetch data but i am not able to filter the data unlike i saw in other graphql videos , i am pretty sure the solution would be straightforward.. plz find my code below schema.py import graphene from graphene.types import schema from graphene_django import DjangoObjectType, fields from .models import Books class Bookstype(DjangoObjectType): class Meta: model = Books fields = '__all__' class Query(graphene.ObjectType): all_books = graphene.List(Bookstype) def resolve_all_books(root,info): return Books.objects.all() schema = graphene.Schema(query=Query) -
fragment caching for jinja2 templates
I‘m trying to improve the rendering performance of my jinja2 templates in the context of Django (changing from the django engine to the jinja2 already gave a significant increase of around 5 times quicker rendering time). For context, I have a quite large template where major sections stay always the same making them suitable to the idea of caching. Then the other remaining sections within the template will almost always be different to the previous call making them less suitable for caching. I had the idea of splitting my template so that there is a base template (with the non changing sections) and the child template which extends the base template with the dynamic sections. The idea behind this was that the base template is cached, however I could not find any documentation which would validate this idea. The other approach I came across is template fragment caching (https://docs.djangoproject.com/en/3.2/topics/cache/#template-fragment-caching) which looked promising, but I was not able to get my head around on how to achieve this result using the jinja2 engine. I would like to do performance tests for both approaches, so was therefore looking for guidance on how to achieve fragment caching with jinja2 and validation if the … -
Django Admin: list_display and ImportExport not working Simultaneosly
I am working on a multi-database Django project with Import Export Function for a database update. If I place @admin.register before ImportExport List_display does not work Admin.py from django.contrib import admin from .models import * from import_export.admin import ImportExportModelAdmin class ViewAdmin(ImportExportModelAdmin): pass @admin.register(English,Data1,Data2, Data3, Data4, Data5) class EnglishAdmin(admin.ModelAdmin): list_display = ("name","views") if I use this method I'm not having the Import-export function, But I'm able to use the list_display function Admin.py from django.contrib import admin from .models import * from import_export.admin import ImportExportModelAdmin @admin.register(English,Data1,Data2, Data3, Data4, Data5) class ViewAdmin(ImportExportModelAdmin): pass class EnglishAdmin(admin.ModelAdmin): list_display = ("name","views") If I use this method I'm not able to use the list_display function, Import export function is working Is there any way we can Use both Functions ? -
Multiple form in single submit button
I am trying to create a hotel booking website and I have a feature to choose multiple rooms to book and when I choose 3 rooms, in booking form page 3 separate form appears for 3 separate room. Now I want store the information of all room in database separately with one single submit button. How Can I do it? I am creating website using Django and PHP my admin(Database) -
Django nested serialzers not working with ManyToMany relationship
I am trying to get thumbnail of one model to another model. I have tried both Nested Serializer not showing up Django Rest Framework nested serializer not showing related data models.py class Format_Image(models.Model): format_image = models.ImageField(upload_to="formatimages/") thumbnail = models.ImageField(upload_to='thumbs', editable=False) class Format_List(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image_format = models.ManyToManyField(Format_Image) format_name = models.CharField(max_length=200) serializers.py class Thumbnail_Serialzers(serializers.ModelSerializer): class Meta: model = Format_Image fields = ['format_image', 'thumbnail'] class Format_List_Serializers(serializers.ModelSerializer): format_image_set = Thumbnail_Serialzers(many=True, read_only=True) class Meta: model = Format_List fields = ['format_name','format_image_set'] I am getting response like below [ { "format_name": "Format1" }, { "format_name": "Format2" }, ] I am expecting something like below [ { format_name: Format1, format_image: [ { thumbnail: thumbnail.png } ] } ] -
Create user login and password for users from csv using ImportExport Module Django
I want to create a new user's login and random/same password using CSV file using the ImportExport module Django. I've tried many examples but for no use. Can you please suggest anything? I've even tried to make password field in the import csv file. Let me know any tutorial/link that you can share to achieve this. -
Java, Django, MySQL Coders wanted
Please see my profile for further info. I am seeking like minded coders to develop new cyber security ideas for profit. -
type object 'multichoice' has no attribute '_default_manager'
I'm using Django with mongoengine. The Admin Panel unable to add data in multichoice model I got this error. type object 'multichoice' has no attribute '_default_manager' Python Version: 3.9.2 Django Version: 3, 0, 5, 'final', 0Model from mongoengine import Document, fields # Create your models here. class multichoice(Document): m_class_choices = [('5_c', '5th Class'), ('6_c', '6th Class'), ('7_c', '7th Class'), ('8_c', '8th Class')] m_subject_choice = [('accounting','Accounting'), ('bus-math','Business-Math'), ('stats','Statistics'),] m_language_choice = [('en', 'English'), ('fr', 'French',)] m_type_choice = [('paper', 'Past Paper'), ('book', 'Book'),] m_title = fields.StringField(primary_key=True, max_length=255, default='A') m_slug = fields.StringField(default='a') m_question = fields.StringField(default='A') m_question_number = fields.StringField(max_length=255, default='1') m_alternatives = fields.ListField(default='A') m_class = fields.StringField(choices=m_class_choices, max_length=10, default='5_c') m_subject = fields.StringField(choices=m_subject_choice, max_length=50, default='accounting') m_lan = fields.StringField(choices=m_language_choice, max_length=2, default='en') m_type = fields.StringField(choices=m_type_choice, max_length=5, default='book') m_unit = fields.IntField(min_value=1, max_value=99, default='1') m_paper_year = fields.IntField(min_value=1990, max_value=2050, default='2021') def __str__(self): return self.m_title Admin from django_mongoengine import mongo_admin as admin from mcqs.models import * # Register your models here. class multichoice_admin(admin.DocumentAdmin): model = multichoice fields = ('m_title', 'm_slug', 'm_question', 'm_question_number', 'm_alternatives', 'm_class', 'm_subject', 'm_lan', 'm_type', 'm_unit', 'm_paper_year', ) admin.site.register(multichoice, multichoice_admin) Url from django.contrib import admin from django.urls import path from django_mongoengine import mongo_admin urlpatterns = [ path('admin/', admin.site.urls), path('content_admin/', mongo_admin.site.urls), ] Settings # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Passing html button tag with url href to template
I currently have a code which reads some data from firebase as well as a button which has html tags and a url href, passes it into my html template and into a table. My urls.py is formatted like this: path('history-report/', view.history_report, name="historyreport") In my views I pass the values like this: def history_report(request): # retrieving information code ziplist=zip(history, date) view_button='<a type="submit" class="btn btn-primary" name="view_history" value={0} href="{% url 'historyreport' %}">View</a>'.format(history) return render(request,'history.html', {"history":ziplist,"view_button":view_button}) This does not work and gives me a 500 error. Note that my page works fine if i remove the {% url 'historyreport' %} I tried using this instead: href='/historyreport' But this redirects me to the localhost/mycurrentpage/historyreport when it should have been localhost/historyreport Any suggestions on how i can get this to work? -
Django Pytest parallel run - How to configure database settings
I am using pytest to run my django tests and was trying to speed them up by running them in parallel. I tried modifying my database name using the enviroment variable PYTEST_XDIST_WORKER but my tests still cannot access the database. How do I need to set my database settings in my django configuration so that the parallel databases are created and used. db_suffix = env.str("PYTEST_XDIST_WORKER", "") DATABASES["default"]["NAME"] = f"""{DATABASES["default"]["NAME"]}_{db_suffix}""" pytest.ini [pytest] addopts = --ds=config.settings.test --create-db python_files = tests.py test_*.py norecursedirs = node_modules env_files= .env.tests command to run tests: pytest -n 4