Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I couldn't make virtual environment in visual-studio. please check this error
below is the screenshot of the error i got while making virtual environment in visual studio code. there is an error message in terminal section while the myvenv (virtual environment folder) was created. actually there is not 'activate' file in Scripts folder of myvenv folder. I cannot understand the error message, how can I handle this problem? -
Problem after upgrading to django 5.0 "AttributeError: 'BlankChoiceIterator' object has no attribute '__len__' "
I'm new in django triad to upgrade to version 5.0 but got this problem in my project Traceback (most recent call last): File "dirto/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "dirto/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "dirto/env/lib/python3.10/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "dirto/env/lib/python3.10/site-packages/django/template/response.py", line 92, in rendered_content return template.render(context, self._request) File "dirto/env/lib/python3.10/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 171, in render return self._render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 961, in render_annotated return self.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/loader_tags.py", line 159, in render return compiled_parent._render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 961, in render_annotated return self.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/defaulttags.py", line 325, in render return nodelist.render(context) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "dirto/env/lib/python3.10/site-packages/django/template/base.py", line 961, in render_annotated … -
How to override "save_model" for UserAdmin of User model
i'm trying to override save_model when i enter an existing email i get this error "<User: >" needs to have a value for field "id" before this many-to-many relationship can be used. class UserAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): email = form.data.get("email") if User.objects.filter(email=email).exists(): messages.set_level(request, messages.ERROR) return messages.error( request, _("An account with this email address already exists.") ) else: obj.set_password(form.cleaned_data["password"]) if ( Group.objects.get(id=form.data.get("groups")).is_staff and form.data.get("is_staff") is None ): obj.is_staff = True if ( not Group.objects.get(id=form.data.get("groups")).is_staff and form.data.get("is_staff") is not None ): obj.is_staff = False obj.save() EmailAddress.objects.create(email=email,user_id=obj.id) return super().save_model(request, obj, form, change) i think this error is triggered because it's trying to add user id to groups model but the user is not being created how can i fix it -
Django Bootstrap modal edit not showing data on inputs
I am developing a Django application to store customers data with a CRUD. I decided to use bootstrap modals to Add, edit info and delete a new customer. Therefore, I'm dealing with some problems when I try to open the edit modal. When the edit customer modal is opened the customer information that was clicked on is not appearing in the input fields of the form. Below I will show the pieces of my code in question, which are being used in this feature My base template is "meus-clientes.html" and the button to show the edit modal, is inside the table: <div> <div class="card mb-4" id="tabela-pedidos"> <div class="card-header"> <div> <i class="fas fa-user-tie"></i> Clientes cadastrados </div> </div> <div class="card-body"> <table id="datatablesSimple2"> <thead> <tr> <th>Nome</th> <th>Telefone</th> <th>E-mail</th> <th>CPF</th> <th>Endereço</th> <th>Pagamento</th> <th>Ações</th> </tr> </thead> <tfoot> <tr> <th>Nome</th> <th>Telefone</th> <th>E-mail</th> <th>CPF</th> <th>Endereço</th> <th>Pagamento</th> <th>Ações</th> </tr> </tfoot> <tbody> {% for dados_cliente in dados_clientes %} <tr> <td>{{ dados_cliente.nome }}</td> <td>{{ dados_cliente.telefone }}</td> <td>{{ dados_cliente.email_1 }}</td> <td>{{ dados_cliente.cpf }}</td> <td>{{ dados_cliente.endereco }}</td> <td>{{ dados_cliente.metodo_pagamento }}</td> <td> <div class="action-link"> <a title="Editar cliente" href="{% url 'editar_cliente' dados_cliente.id %}"> <i class="fas fa-pen"></i> </a> <a data-bs-toggle="modal" data-bs-target="#deleteModal{{ dados_cliente.id }}" title="Excluir Cliente"> <i class="fa-solid fa-trash-can"></i> </a> </div> </td> </tr> {% include 'editar-cliente.html' … -
Run pytest behind Django Admin custom action
I'm building API that allows users to send input data to generate printable documents. On top of that I need to allow users to define templates (HTML) for these documents in which users define the layout and logic. I would like users to be able to define test cases for their templates where they can define input data as well as expected output and run tests (pytest) behind a custom Django admin action. Pytest will use test input data, render the output document and compare it to the user defined benchmark. Stdout of pytest run should be written to text file which is included in the response of custom Django admin action. My initial implementation behind Django admin was using pytest.main() functionality. import sys from io import StringIO class TestCaseAdmin(admin.ModelAdmin): ... def run_selected_test_cases(self, request, queryset): sys.stdout = StringIO() pytest.main([ "tests/functional/test_user_cases.py", "-vv", ]) result = sys.stdout.getvalue() response = HttpResponse(result, content_type="text/plain") response["Content-Disposition"] = f"attachment; filename={filename}" return response The above implementation will run the tests defined in test_user_cases.py and download text file with pytest stdout. However after this is done, pytest crashes with error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. This … -
Django - form is always not valid
I am new to Django, I have to do a simple web page to register people. Some names is in Portuguese, but it does not matter. I do not know what I am doing wrong, maybe I am sending empty data to the view, but I am not sure. view.py: def get_form(request): logger = logging.getLogger('django') logger.info("Request") if request.method == 'POST': logger.info("POST method") form = cadastroForm(request.POST) logger.info(form.errors) if form.is_valid(): logger.info("Valid") insert_data(form.cleaned_data['nome'], form.cleaned_data['mat'], form.cleaned_data['telefone'], form.cleaned_data['email']) return HttpResponseRedirect(reverse('all-borrowed')) else: logger.info("Not Valid") else: form = cadastroForm() html page: {% block page_content %} <h1 style="text-align: center; margin-top: 10%; margin-bottom: 5%; font-size: 64px;">Cadastro</h1> <form action="../../views.py" style="display: inline-block; margin-left: 40%;" method = "POST"> {% csrf_token %} <label for="nome">Nome:</label> <input type="text" id="nome" name="nome" style="margin-left: 30px" maxlength="100" required><br><br> <label for="telefone">Telefone:</label> <input type="text" id="telefone" name="telefone" style="margin-left: 10px" required><br><br> <label for="email">Email:</label> <input type="text" id="email" name="email" style="margin-left: 36px" required> <p style="margin-top: 15px;">Frequenta o IESB: <input type="radio" id="iesb_sim" name="iesb" value="Yes" required><label for="iesb_sim" style="margin-left: 5px">Sim</label> <input type="radio" id="iesb_nao" name="iesb" value="No" required checked="checked"><label for="iesb_nao" style="margin-left: 5px">Não</label> </p> <label for="mat">Matrícula:</label> <input type="text" id="mat" name="mat"> <br><br> <input type="file" style="margin-bottom: 18px" id="myFile" name="filename"> <input type="submit" value="Enviar" style="margin: auto; display: block;"> </form> <script> document.getElementById("iesb_sim").addEventListener("change", function(){ document.getElementById("mat").disabled = false; }) document.getElementById("iesb_nao").addEventListener("change", function(){ document.getElementById("mat").disabled = true; }) </script> {% endblock page_content … -
Detecting non-translation wrapped strings in Django?
I have a Django project being maintained by multiple developers. It needs to support i18n, so all model field names, help text, labels in custom templates, etc need to get wrapped by gettext_lazy. Occasionally, however, a developer will forget to wrap a new string, which leads to regressions where text does not get translated in the UI. Is there an existing tool I can run to scan Django's templates and models and report non-translation wrapped strings so I can add a check to my build to catch these regressions? I guess it would be the inverse of django-admin makemessages, which finds all strings wrapped by gettext_lazy, but I can't find anything like this in Django's docs. -
How to prevent Pycharm from opening the source file of a function or a class when trying to edit a particular line,or a function/class name?
My current Pycharm version is 2023.2.5(Ubuntu linux) Whenever I try to edit a name of a function or click on a classname it takes me to it's source file which is annoying.How to disable this feature? from .views import test """when I click on the above line to add test2,it takes me to the views.py Expected behavior:-Should be able to edit a line(add to the end of it) without Pycharm taking me to the source file of that function or class...""" urlpatterns = [path('home', test, name='test'), path('about', test2, name='test2')] -
Django 5: custom AdminSite got " 'generator' object is not subscriptable "
I'm trying to do default admin site just like this here is settings.INSTALLED_APPS INSTALLED_APPS = [ #'django.contrib.admin', 'core.apps.AppAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'routefilterfeeder.apps.RoutefilterfeederConfig', ] here is my core.apps from django.contrib.admin.apps import AdminConfig class AppAdminConfig(AdminConfig): default_site = 'core.admin.AppAdminSite' and here is my core.admin from django.contrib.admin import AdminSite #from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from django.apps import apps from django.contrib.admin.sites import site from operator import itemgetter # ref: https://unfoldadmin.com/blog/custom-django-admin-site/ class AppAdminSite(AdminSite): def index(self, request, extra_context=None): # Update extra_context with new variables return super().index(request, extra_context) def get_app_list(self, request, app_label=None): """ Return a sorted list of all the installed apps that have been registered in this site. """ app_dict = self._build_app_dict(request, app_label) # First, sort the models of each app, based on 'admin_priority' # Ref: https://forum.djangoproject.com/t/reordering-list-of-models-in-django-admin/5300 for app_name in app_dict.keys(): app = app_dict[app_name] model_priority = { model['object_name']: getattr( site._registry[apps.get_model(app_name, model['object_name'])], 'admin_site_priority', 9999 ) for model in app['models'] } app['models'].sort(key=lambda x: model_priority[x['object_name']]) yield app # Sort the apps alphabetically. all_app = sorted(app_dict.values(), key=lambda x: x["name"].lower()) app_list = [] prio_list = [] # Sort the models alphabetically within each app. for app in all_app: this_config = apps.get_app_config(app["app_label"]) try : this_prio = this_config.admin_site_priority prio_list.append([this_prio,app['app_label']]) except Exception as e: app_list.append(app) prio_list = sorted(prio_list, … -
how I can catch when pressed cancel_url on stripe?
I have a question about Stripe payments... I figured out how to do some code when payment was succesful, but what and where I can check that user even didn't enter anything in checkout form, and just pressed Back cancel_url? my checkout code: domain = 'http://127.0.0.1:8000/profiles/'+username+'/balance/' stripe.api_key = settings.STRIPE_SECRET_KEY try: # Create new Checkout Session for the order # Other optional params include: # [billing_address_collection] - to display billing address details on the page # [customer] - if you have an existing Stripe Customer ID # [payment_intent_data] - capture the payment later # [customer_email] - prefill the email input in the form # For full details see https://stripe.com/docs/api/checkout/sessions/create # ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID set as a query param checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.username if request.user.is_authenticated else None, success_url=domain + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain + 'cancelled', payment_method_types=['card'], mode='payment', line_items=[ { 'price_data': { 'currency': 'eur', 'unit_amount': grata_points_amount, #6900, 'product_data': { 'name': pack.name, #'69 GP', # 'description': 'package with 6900 Grata Points', # 'images': [''], }, }, 'quantity': pack_cnt, #1, } ], metadata={ 'transactionID': transaction.id } ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) sucess payment (all needed fields was filled up): def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY endpoint_secret … -
Token Expiry based on user inactivity
So I am using django rest framework, and i am using simple jwt for token authentication, and i want to implement this (if the user hasn't been active on the website for 30 min then the token should expire and the user should be redirected to login page). How should i do this, for your information i know about session authentication, however, i don't want to use it. Note: If you have any other security methods/approaches i am open to hearing them since this is the only one that i know and i don't know how to implement it :-) i have tried adding some fields in the payload, so i can use it to determine if the user is active or not, however idk how to make the server check it, since the only way that i check on the token is when the clinet make an api call -
Why does my filter __exact not working in my django, postgresql?
Before are my codes in my django app frame, everything is working well. There is no error but my filter __exact does not print out the results in my html. Please help. def list(request, type): genes = Gene.objects.filter(entity__exact=type) return render(request, 'genedata/list.html', {'genes': gene, 'type': type}) def poslist(request): genes = Gene.objects.filter(entity__exact='Chromosome').filter(sense__startswith='+') return render(request, 'genedata/list.html', {'genes': gene, 'type': 'Poslist'}) path('list/\<str:type\>', views.list, name='list'), path('poslist/', views.poslist, name='poslist') class Gene(models.Model): gene_id = models.CharField(max_length=256, null=False, blank=False, db_index=True) entity = models.CharField(max_length=256, null=False, blank=False) start = models.IntegerField(null=False, blank=True) stop = models.IntegerField(null=False, blank=True) sense = models.CharField(max_length=1) start_codon = models.CharField(max_length=1, default="M") sequencing = models.ForeignKey(Sequencing, on_delete=models.DO_NOTHING) ec = models.ForeignKey(EC, on_delete=models.DO_NOTHING) def __str__(self): return self.gene_id index.html <h1>D.Bucheria Genes List</h1> Gene ID {% for gene in genes %} <a href="/gene/{{ gene.pk }}"> {{ gene }}</a> {% endfor %} <h2>Select Gene Location</h2> <a href="/list/Chromosome">Chromosome</a> OR <a href="/list/Plasmid">Plasmid</a> <h2>Show Positive Chromosome Genes</h2> <a href="/poslisti">Chromosome</a>Show Positive List</a> list.html: <h1>Filtered List: {{ type }} </h1> Gene ID {% for gene in genes %} <a href="/gene/{{ gene.pk }}"> {{ gene }}</a> {% endfor %} -
get TaskResult object when testing the Celery task in Django
I have a very simple celery task inside my Django application: @app.task(name='test', bind=True) def my_celery_task(self, schema=None, ref_id=None, user_id=None): print('Start Task 1') with schema_context(schema): print(self.get_task_result()) print(self.get_task_result().pk) print('Start Task 2') return {'status': 'Task finished successfully'} I also have the base class for Celery tasks class MyTaskBase(Task): def delay(self, *args, **kwargs): print('Delaying task: {}'.format(self.name)) argsrepr = [arg for arg in args] kwargsrepr = {key: value for key, value in kwargs.items()} new_task = super().s(*args, **kwargs) return new_task.apply_async( argsrepr=json.dumps(argsrepr), kwargsrepr=json.dumps(kwargsrepr) ) def get_task_result(self): from django_celery_results.models import TaskResult task_result = TaskResult.objects.get_task(self.request.id) return task_result I also have the trigger for a TaskResult on_save: @receiver(post_save, sender=TaskResult) def create_task_entry(sender, instance=None, created=None, **kwargs): print("INSIDE THE POST_SAVE") ... TaskEntry.objects.create(...) I want to test this configuration: SO... : I wrote this little test: @override_settings(CELERY_TASK_ALWAYS_EAGER=True) def test_test(self): my_celery_task.delay(schema=self.get_test_schema_name()) print(TaskResult.objects.all()) print(TaskEntry.objects.all()) The prints are: Delaying task: my_celery_task Start Task 1 <Task: 7a0e8063-2be9-44b1-b438-1c0d37e33456 (PENDING)> None Start Task 2 <QuerySet []> <QuerySet []> From this, I conclude: the task was run The TaskResult was created but never saved to the DB If I omit the CELERY_TASK_ALWAYS_EAGER and run this def test_test(self): my_celery_task.delay(schema=self.get_test_schema_name()) print(TaskResult.objects.all()) print(TaskEntry.objects.all()) Then the prints are on the worker: Delaying task: my_celery_task Start Task 1 <Task: 7a0e8063-2be9-44b1-b438-1c0d37e33456 (PENDING)> None Start Task 2 INSIDE THE … -
fetching Django API with pagination in react
so I have this code in my react import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { Bar } from 'react-chartjs-2'; import moment from 'moment'; import 'chartjs-adapter-moment'; import { MultiSelect } from "react-multi-select-component"; const AllFilters = () => { const [startDate, setStartDate] = useState(null); const [endDate, setEndDate] = useState(null); const [operatorId, setOperatorId] = useState(null); // const [statuses, setStatuses] = useState([]); const [operatorsList, setOperatorsList] = useState([]); const [orderStatuses, setOrderStatuses] = useState([]); const [orders, setOrders] = useState([]); const [selectedStatuses, setSelectedStatuses] = useState([]); const [viewBy, setViewBy] = useState('month'); const filterOrdersByDay = (day) => { const formattedDay = moment(day).format('YYYY-MM-DD'); const filteredOrders = orders.filter(order => moment(order.created_at).isSame(formattedDay, 'day', 'minute')); console.log(`Filtered orders for day ${formattedDay}:`, filteredOrders); return filteredOrders; }; const getStatusCountByDay = (status, day) => { const formattedDay = moment(day).format('YYYY-MM-DD'); return filterOrdersByDay(formattedDay).filter(order => order.status === status).length; }; useEffect(() => { const fetchData = async () => { try { const loginToken = localStorage.getItem('loginToken'); const operatorsListResponse = await axios.get('http://localhost:8000/accounts/profile/operators/', { headers: { Authorization: `Token ${loginToken}`, }, }); const orderStatusesResponse = await axios.get('http://localhost:8000/dashboard/OrderStatus/', { headers: { Authorization: `Token ${loginToken}`, }, }); setOperatorsList(operatorsListResponse.data); setOrderStatuses(orderStatusesResponse.data); let pageOrders = []; const response = await axios.get('http://localhost:8000/dashboard/AllFilters/', { headers: { Authorization: `Token ${loginToken}`, }, params: { start_date: startDate ? … -
no idea about how to store a token or another credentials of another Django app that acts as a gateway in my another Django app
I have a Django app named something like d1 app that acts as my gateway service in my micro service architecture and another Django app as a client of d1 named as something like d2. I'm confused about how can I get a token or some credentials like phone number and password from the frontend and pass it to d1 to verifying user and logging it in my d2 Auth system. big part of my problem is confusing about how to store the temporary token or credentials of my frontend in d2 app. one of my own ideas was using REDIS or some caching server like that; but as I'm new to backend I don't have a great confidence about it and I'll be thank of any advices of anybody who can guide me. thanks -
performing case insensitive validation in django
I'm new to the backend world and learning how to make an API with django rest framework. I went through some concepts already but I ran into some issues. Context: There are 4 resources. Store, Author, Book, Address. 1 CRUD endpoint for each of them except address. A store must have an address and a name. if the address exists, link it on creation, else create the address and create the store. Problem: I cannot seem to figure out this part "if the address exists, link it on creation, else create the address and create the store." Here is the relevant info to the problem in hand views.py class StoreViewSet(viewsets.ViewSet): def list(self, request): stores = Store.objects.prefetch_related('address') serializer = StoreSerializer(stores, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def retrieve(self, request, pk=None): pass def create(self, request): serializer = StoreSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Address(models.Model): country = CountryField(null=False) city = models.CharField(max_length=255, null=False) street = models.CharField(max_length=255, null=False) street_number = models.IntegerField(null=False) addition = models.CharField(max_length=255, blank=True, default='') class Meta: unique_together = ['country', 'city', 'street', 'street_number', 'addition'] constraints = [models.CheckConstraint(check=models.Q(street_number__lt=100000), name="street_number_lt_100000")] class Store(models.Model): name = models.CharField(max_length=255, null=False) address = models.OneToOneField(Address, null=False, on_delete=models.CASCADE) books = models.ManyToManyField(Book, blank=True) serializers.py class AddressSerializer(CountryFieldMixin, serializers.ModelSerializer): class Meta: model … -
django rest framework, how to prefetch_related with a single object
for some reason,I pass a instance(not queryset) to ModelSerializer. but I want to do prefetch_related with this instance. # instance is a Workout object instance = queryset.order_by('?').first() # I want to do something like: instance.prefetch_related('exercises') to avoid N+1 problem workout = WorkoutModelSerializer(instance) return Response(workout.data, status=status.HTTP_200_OK) -
What does the new `Field.db_default` of django 5 imply ? Should we use it by default or stick with `Field.default`?
If I understand correctly, Field.default do not set a value in the DB, but the value is used when a model instance is created. On the other hand, Field.db_default set the value in the DB. I am not sure to fully understand the implications that this new option is giving us. So my question is, which one should be used by default (no pun intended) and why? -
Find which IP address was used by manage.py while the Django dev server was started
In Django dev environment, we start our Django server in various way, like:- python3 manage.py runserver which auto starts development server at http://127.0.0.1:8000/ OR python3 manage.py runserver 192.168.1.1:8005 which auto starts development server at http://192.168.1.1:8005/ How or in what ways, can I find the IP address that the development server was started using which IP address and which port number? I want to write a python script within this Django project (in an app), which could tell me that the dev server is accessible on <this_specific_ip_address> (ex: 127.0.0.1 or 192.168.1.1) and then on <this_specific_port_number> (ex: 8000 or 8005). Is there a way this can be achieved? -
making downloaded file not transferable in django
I am developing a bookstore app, I want to make downloaded files not shareable to other devices. which means users can not share files that are downloaded from the site. I tried searching different sites to know how I can make the file downloaded not shareable but I didn't get any solution. please help me with what can I do to solve this problem. -
How to create a separate column for each related field while exporting data via django-import-export
I have a PaymentRecord model which stores user payments for event tickets. I have a TicketPurchase model which records which tickets were purchased by which PaymentRecord. So my models look something like this - class Event(models.Model): name = models.CharField(max_length=128) class PaymentRecord(models.Model): event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True, related_name='payments') payment_time = models.DateTimeField(auto_add_now=True) # various payment details and user identifiers class TicketPurchase(models.Model): payment_record = models.ForeignKey(PaymentRecord, on_delete=models.CASCADE, related_name='tickets') tier_name = models.CharField(max_length=32) ticket_count = models.IntegerField() Each event that I am selling tickets for has a few "tiers", like Silver, Gold, Platinum (Each event has different names for tiers). When I export all the PaymentRecord objects for a particular event, I want to have a separate column for each tier showing how many tickets for that tier were purchased by a payment. So I want my output to be something like this - Event Name Payment Time Silver Tickets Gold Tickets Platinum Tickets Event 1 # time 1 3 0 0 Event 1 # time 2 1 1 1 How can I achieve this using django-import-export? Right now I am using a ModelResource to export a summary of the different tiers purchased in a single column, as so - class PaymentRecordsResource(resources.ModelResource): class Meta: model = PaymentRecord … -
How to fix "IntegrityError Foreign Key constraint failed" error in django rest framework?
I have Client (AbstractUser) and Team models in my django app class Team(models.Model): name = models.CharField(max_length=255) class Client(AbstractUser): team = models.ForeignKey(Team, blank=True, null=True, related_name='client', on_delete=models.SET_NULL, db_index=True) name = models.CharField(max_length=255) code = models.CharField(max_length=255, unique=True) pass So, when I logged in using Client (not superuser, with permission to add-change Client) I can't change Client. I want to be one administrator for each team to manage own team, can add or change Client. So Client with permission is_staff can manage own team. But it gives an error IntegrityError. Django admin.py -
Django Nextjs webscoket connecting can't established and getting 404 error
I am trying to build an real time chat app so using django channel but I can't build web socket connect with my django and nextjs app. my folder and file structure backend ->backend ->settings.py ->wsgi.py ->routing.py ->consumers.py my code: settings.py ASGI_APPLICATION = "backendfb.routing.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from backendfb.consumers import TextRoomConsumer application = ProtocolTypeRouter({ 'websocket': URLRouter( [ path('ws/<room_name>/', TextRoomConsumer.as_asgi()) ] ), }) consumers.py # backendfb/consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class TextRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f"chat_{self.room_name}" # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat.message', 'message': message } ) async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) wsgi.py import os from backendfb.routing import application from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backendfb.settings') application = application app = get_wsgi_application() my fontend code const client = new WebSocket(`ws://localhost:8000/ws/${Room}/`); -
how to remove the first slash in django?
The tutorial is written like this urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include("polls.urls") but i prefer urlpatterns = [ path('/admin', admin.site.urls), path('/polls', include("polls.urls") So the url would be '127.0.0.1:8000//polls' Is there any way to remove the first slash that is automatically added? I try to set APPEND_SLASH = FALSE but it makes nothing -
How do I always add a value from my data to serializer.errors (DRF)?
I'd like to pass an integer field called Id into a serializer, and always add it to serializer.errors (if there are any. For example: class ItemSerializer(serializers.ModelSerializer): # magical way to take Id in and add it to errors class Meta: model = Item fields = "__all__" Then, if there are any errors, they should look like: {"error": "error message", "Id": 1} I can't just add the field to serializer.errors after serializer.is_valid() runs, because I also want to use many=True on my serializer. Also, it turns out that you can't add a dictionary as an error message, for example: validators = [ UniqueTogetherValidator( queryset=Item.objects.all(), fields=["org", "item_name"], message={"cool":"dictionary"}, #this doesn't work :( ) ] And no, I can't store the Id in the model itself. Due to the way my frontend is using this API, the Id will change on most API calls.