Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJAX not interacting with my Django views functions
This is a simple todo-list developed with the Django framework. I have a categories dropdown on my main page that is to display the tasks based on that particular category chosen. Javasript (AJAX) Section function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + "=")) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const theselect = document.getElementById('catSelect'); theselect.addEventListener('change', (event) => { event.preventDefault(); const catname = theselect.value; fetch(`/?cat=${catname}`, { method: "GET", headers: { "X-Requested-With" : "XMLHttpRequest", "X-CSRFToken": getCookie("csrftoken"), } }) .then(response => response.json()) .then (data => { const display = document.getElementById("results"); display.innerHTML = ""; (data.context).forEach(x =>{ const items = ` <div class="row"> <div class="col-lg-7"> <a href="{% url 'detail_task' 17 %}" style="text-decoration: none;"> ${x.title} </a> </div> <div class="col-lg-1"> <a href="{% url 'update_task' 17 %}"> <i class="fa-regular fa-pen-to-square"></i></a> </div> <div class="col-lg-1"> <a href="{% url 'delete_task' 17 %}" style="color:rgb(219, 43, 37);"> <i class="fa-regular fa-trash-can"></i> </a> </div> </div> ` display.innerHTML += items; console.log(data) }); }); }); index.html <h3> To-Do … -
Problem sending an account confirmation email from Django
I'm trying to send an account activation email from a Django REST-based application and through two email services, gmail and Mailgun, using Heroku to deploy the application. I have no issues doing a user registration function using "django.core.mail.backends.console.EmailBackend", I run into issues while using the email backend "django.core.mail.backends.smtp.EmailBackend" with the following settings: from environs import Env env = Env() env.read_env() EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = env('MAILGUN_SMTP_PORT') EMAIL_HOST_USER = env('MAILGUN_SMTP_LOGIN') EMAIL_HOST_PASSWORD = env('MAILGUN_SMTP_PASSWORD') I get the following on my test system: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view web_1 | return view_func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 69, in view web_1 | return self.dispatch(request, *args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper web_1 | return bound_method(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/django/views/decorators/debug.py", line 90, in sensitive_post_parameters_wrapper web_1 | return view(request, *args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/dj_rest_auth/registration/views.py", line 47, in dispatch web_1 | return super().dispatch(*args, **kwargs) web_1 | File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch web_1 | response = self.handle_exception(exc) web_1 | … -
Django html not able to get the Add_More function working
I am working on a project, where I need to create target for employees. When creating the object, my intention is to get 'Target_Name' only once, and 'Category', 'target_percentage' to repeat upon clicking 'Add More'. From various sources, I ended up with below code. But my html keeps giving different errors. Can someone help to get this solved? models.py from django.db import models class Create_Target(models.Model): Target_Name=models.CharField(max_length=100) Category=models.CharField(max_length=100) target_percentage=models.FloatField() forms.py from django import forms from .models import Create_Target from django.forms.models import BaseModelFormSet class Create_Target_Form(forms.ModelForm): class Meta: model=Create_Target fields=('Target_Name', 'Category', 'target_percentage') class Create_Target_FormSet(BaseModelFormSet): model = Create_Target fields = ['Category', 'target_percentage'] extra = 1 formset_template = 'django.forms.formsets.DEFAULT_TABLE_TEMPLATE' views.py from django.shortcuts import render, redirect from django.views.generic.edit import CreateView from .forms import Create_Target_Form, Create_Target_FormSet from .models import Create_Target class Target_Create(CreateView): model = Create_Target form_class = Create_Target_Form template_name = 'create_target.html' success_url = '/home' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['formset'] = Create_Target_FormSet(self.request.POST, prefix='formset') else: data['formset'] = Create_Target_FormSet(prefix='formset', queryset=Create_Target.objects.none()) data['formset'].min_num = 1 data['formset'].max_num = 10 return data def form_valid(self, form): formset = Create_Target_FormSet(self.request.POST, prefix='formset') if formset.is_valid(): form.instance.Target_Name = form.cleaned_data['Target_Name'] self.object = form.save() formset.instance = self.object formset.save() return redirect('/home') else: return self.form_invalid(form) def get_initial(self): initial = super().get_initial() initial['Target_Name'] = self.request.POST.get('Target_Name', '') return initial html <!DOCTYPE html> … -
Select Related django
Como fazer para pegar os produtos da tabela ItensCompra e juntar com a de pedido e de compra? Segue models class ItensCompra(models.Model): produto = models.ForeignKey('cadastro.Produto', related_name="compra_produto", on_delete=models.CASCADE, null=True, blank=True) compra_id = models.ForeignKey('compras.Compra', related_name="itens_compra", on_delete=models.CASCADE) quantidade = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) valor_unit = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) saldo_atual = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) saldo_final = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) tipo_desconto = models.CharField(max_length=1, choices=TIPOS_DESCONTO_ESCOLHAS, null=True, blank=True) desconto = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) subtotal = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) inf_ad_prod = models.CharField(max_length=500, null=True, blank=True) vicms = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) vipi = models.DecimalField(max_digits=13, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) p_icms = models.DecimalField(max_digits=5, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) p_ipi = models.DecimalField(max_digits=5, decimal_places=2, validators=[MinValueValidator(Decimal('0.00'))], null=True, blank=True) `class Compra(models.Model): # Fornecedor fornecedor = models.ForeignKey( 'cadastro.Fornecedor', related_name="compra_fornecedor", on_delete=models.CASCADE) # Transporte mod_frete = models.CharField( max_length=1, choices=MOD_FRETE_ESCOLHAS, default='9') # Estoque local_dest = models.ForeignKey( 'estoque.LocalEstoque', related_name="compra_local_estoque", default=DEFAULT_LOCAL_ID, on_delete=models.PROTECT) movimentar_estoque = models.BooleanField(default=True) # Info data_emissao = models.DateField(null=True, blank=True) valor_total = models.DecimalField(max_digits=13, decimal_places=2, validators=[ MinValueValidator(Decimal('0.00'))], default=Decimal('0.00'))```` class PedidoCompra(Compra): orcamento = models.ForeignKey( 'compras.OrcamentoCompra', related_name="orcamento_pedido", on_delete=models.SET_NULL, null=True, blank=True) data_entrega = models.DateField(null=False, blank=False) status = models.CharField( max_length=1, choices=STATUS_PEDIDO_COMPRA_ESCOLHAS, default='0') PedidoCompra e Compra eu consegui juntar, ja a pedido_itens -
How can I set the QuerySet on a Wagtail InlinePanel - or hide/archive items without deleting them?
I need to set items in an InlinePanel on a page as 'archived' so they don't display in the InlinePanel. There should only be a few items visible at once but deleting them is not an option as they are required for historical information and reporting etc. Is there a way to do this without just hiding them with Javascript (which will slow down page loads over time)? If they are archived and removed from the QuerySet via filtering, they are then deleted when the page is published because they are not longer needed by the InlinePanel. I have tried SET_NULL but they are still deleted. Using PROTECT stops the page from being published but this wont work because it's just blocking the inline object from being deleted. So how could this be done, or is this just asking too much from an InlinePanel? Basic code example. SET_NULL is ignored and related object is deleted when the page is published. class Variant(models.Model): product = ParentalKey( 'wagtailcore.Page', related_name='variants', on_delete=models.SET_NULL, null=True, ) class Product(Page): panels = [ MultiFieldPanel([ InlinePanel('variants', label='Item Variants'), ]), ] -
How to return value instead of related object id in DynamicFieldsModelSerializer?
In django rest framework there is possibility to create serializer able to Dynamically modifying fields. Is there any chance to get value instead of related object ID? -
DigitalOcean: Django, Channels, Redis & Daphne
I am having issues with running websockets on DigitalOcean's App platform. I think I am fundamentally missing a configuration as it relates to Daphne. Here is my setup: Daphne 4.0.0 Channels-Redis 3.4.1 Settings.py INSTALLED_APPS = [ ... # Third-party 'channels', ... CSRF_TRUSTED_ORIGINS = [ 'https://blah.com', 'https://*.blah.com', ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ASGI.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.dev') import django django.setup() from django.core.asgi import get_asgi_application asgi_app = get_asgi_application() import api_waitlist.routing from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack application = ProtocolTypeRouter({ 'http': asgi_app, 'websocket': AllowedHostsOriginValidator(AuthMiddlewareStack( URLRouter( api_waitlist.routing.websocket_urlpatterns )) ), # new }) DigitalOcean Configurations DigitalOcean App: "run command" located under App>Settings>Run Command: daphne -b 0.0.0.0 -p 8080 config.asgi:application Redis Configuration: Redis is set up using DigitalOcean's managed Redis database. The connection string is provided by DigitalOcean. The app level variable "REDIS_URL" that contains the connection string is: rediss://default:password_here@fs-dev-redis-do-user-xxxx-0.b.db.ondigitalocean.com:25061 React Frontend (React is within the Django project scaffolding): The React frontend code to establish the websocket connection is: wb = new WebSocket("ws://127.0.0.1:8000/ws/waitlist/"); The frontend browser console error: -
AttributeError in ASGI/Daphne Django problem
I had done this tutorial for WebSocket with Django but I have this problem when I execute "python manage.py runserver": HTTP GET /chat/hello/ 200 [0.01, 127.0.0.1:65009] WebSocket HANDSHAKING /ws/chat/hello/ [127.0.0.1:65014] Exception inside application: 'int' object has no attribute 'decode' Traceback (most recent call last): File "D:\Projects\New Backend\venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\routing.py", line 116, in __call__ return await application( File "D:\Projects\New Backend\venv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "D:\Projects\New Backend\venv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "D:\Projects\New Backend\venv\lib\site-packages\channels\utils.py", line 57, in await_many_dispatch await task File "D:\Projects\New Backend\venv\lib\site-packages\channels\utils.py", line 49, in await_many_dispatch result = task.result() File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 367, in receive message_channel, message = await self.receive_single( File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 422, in receive_single content = await self._brpop_with_clean( File "D:\Projects\New Backend\venv\lib\site-packages\channels_redis\core.py", line 255, in _brpop_with_clean connection = self.connection(index) … -
Create child object in view as extra action
I have the following drf view: class HouseFullInfoViewSet(viewsets.ModelViewSet): queryset = House.objects.all() serializer_class = HouseSerializer permission_classes = (permissions.IsAuthenticated,) http_method_names = ['get', 'delete', 'post'] def retrieve(self, request, pk=None): house = self.get_object() serializer = self.get_serializer(house) return Response(serializer.data, HTTP_200_OK) @action(methods=['delete'], detail=True, url_name='remove_habitant') def remove_habitant(self, request,pk=None): house = self.get_object() habitant = CustomUser.objects.get(id = request.data['id']) house.habitants.remove(habitant) return Response({'msg':'Deletion success'}, status=HTTP_200_OK) @action(methods=['delete'], detail=True, url_name='remove_vehicle') def remove_vehicle(self, request,pk=None): house = self.get_object() vehicle = Vehicle.objects.get(id = request.data['id']) house.vehicles.remove(vehicle) return Response({'msg':'Deletion success'}, status=HTTP_200_OK) I am trying to make create_habitant and create_vehicle extra actions within this view, but I dont know how to do that exactly. I thought about something like this. @action(methods=['post'], detail=True, url_name='create_vehicle') def create_vehicle(self, request,pk=None): house = self.get_object() vehicle = Vehicle.objects.create(request.data) house.vehicles.add(vehicle) return Response({'msg':'Creation success'}, status=HTTP_200_OK) -
getting AttributeError: 'Settings' object has no attribute 'MODEL'
I have also installed pypi and tls using 'pip'. I am now trying to run 'python manage.py runserver' but after going to the local host and enter the url for checking whether the url is phishing or not, but getting this error after click on predict button. Any help on how to fix this and get my project running? -
django-tables2: row number ordering column not in DB
I am using django-tables2 to create a table, How to make the column row_number follow the sort of id and age columns? https://github.com/jieter/django-tables2/blob/master/docs/pages/ordering.rst import django_tables2 as tables import itertools class SimpleTable(tables.Table): row_number = tables.Column(empty_values=()) id = tables.Column() age = tables.Column() def render_row_number(self): self.row_number = getattr( self, 'row_number', itertools.count(self.page.start_index())) return next(self.row_number) def render_id(self, value): return f"<{value}" I think the best way is if statement if asc = itertools.count(self.page.start_index()) |row_number| id | age | | -------- | -------- |-------- | | 1 | id.1 | age | | 2 | id.2 | age | | 3 | id.3 | age | else desc = itertools.count(self.page.end_index(), -1) |row_number| id | age | | -------- | -------- |-------- | | 3 | id.3 | age | | 2 | id.2 | age | | 1 | id.1 | age | but i don't know how to implant that. -
Django + Docker + Postgres. FATAL: password authentication failed for user "postgres"
I don't know how to solve this simple error: django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" When I run docker-compose up, it can't connect to Postgres. I have tried stopping the service with docker-compose down -v. Please help me understand why am I getting this error. Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } docker-compose.yml: version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code env_file: - .env ports: - "8000:8000" depends_on: - db db: image: postgres:15 volumes: - ./data/db:/var/lib/postgresql/data/ environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres I've reviewed many tutorials and videos about this without success. -
Django Delete file from storage model not working from IIS but working on localhost
I have file Delete Model for deleting file chosen by user. for that after conforming from user that you want to sure delete file I have view.py code as below. @login_required(login_url='/login/') def Delete_files(request, pk): # Get the RadioFile object based on the primary key (pk) radio_file = get_object_or_404(RadioFile, pk=pk) print(radio_file) # get the file path and file object from the database file_obj = RadioFile.objects.get(id=pk).audio_file radio = radio_file.audio_file file_path =file_obj.path print(file_path) # Check that the user is the owner of the file if request.user != radio_file.uploaded_by: messages.success(request, 'File can be deleted by its owner.') # store the message in a message queue return redirect('/') elif os.path.exists(file_path) and not os.path.isfile(file_path): print(f"Error: {file_path} is not a file") response_data = {'success': False, 'error': str(e)} else: try : with transaction.atomic(): # Remove the many-to-many relationship with categories radio_file.categories.clear() radio_file.share_with.clear() # Delete the Radio object radio_file.delete() # Delete the file from the filesystem radio.close() radio.delete() messages.success(request, 'Radio and file deleted successfully.') response_data = {'success': True} except Exception as e: print(str(e)) messages.error(request, 'some error is coming while deleteing file.') # Redirect to the file list view return redirect('/') code deleting file when running from localhost. But it is giving me Win32 permission error says file already in … -
How to authenticate custom table of MySQL using Django?
I was trying to Authenticate my website using Django. Basically I am Using MySQL Database in the backend and I create a custom table that name is Signup. Data is successfully inserted into signup table but whenever I was trying to login it is showing 'No user found' my authenticate function is working properly but it did not fetch the data from signup table. What should I do? Here is so some Screenshot of my code what I have tried . This is the image of my settings.py where I connected MYSQL database using Django Login Code and Output This is image of my login page Code and the output is showing in the terminal Signup Code This is image of Signup Code where signup is correctly working MYSQL entered Datathis is the image of MySQL where I successfully entered my data from signup page -
Serializer has initial_data, but validated_data is empty
I passed some data via post request and Iwant to get the data in the key 'items' (it contains a list of objects that i need to use to create OrderItem). The problem is I don't get any data in the validated_data after calling is_valid(). However the data can be found in serializer.initial_data, Printing what is in serializer.validated_data() shows that it's empty ({}). I don't see where the issue is and why I can't get the data to be in validated_data after using is_valid(). Any help would be very much appreciated. Thanks An Order has 1 or many OrderItems. The model of OrderItem class OrderItem(models.Model): """Model for an item in an order""" order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name="items") bookedition = models.ForeignKey(BookEdition, on_delete=models.PROTECT, related_name="orderitems") quantity = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=8, decimal_places=2) price = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self): return '%s' % self.id The serializer of OrderItem class OrderItemSerializer(serializers.ModelSerializer): """Serializer for OrderItem""" class Meta: model = OrderItem fields = [ 'bookedition', 'quantity', 'unit_price', 'price' ] The model of Order class Order(models.Model): """Model for an order""" PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] payment_status = models.CharField(max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING) customer = models.ForeignKey(Customer, on_delete=models.PROTECT, related_name="orders") … -
Access to the date details in a Django database
I'm currently going over the official Django tutorial. At some point we're shown how to filter keys by the year of the the automatically-filled pub_date column. >>> Question.objects.get(pub_date__year=current_year) <Question: What's up?> But somehow the syntax when calling the year of the date directly has to be with a . instead of a __... In [56]: q=Question.objects.get(pub_date__year=current_year) In [57]: q.pub_date__year --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In [57], line 1 ----> 1 q.pub_date__year AttributeError: 'Question' object has no attribute 'pub_date__year' In [58]: q.pub_date.year Out[58]: 2023 Is there some reason it has to be different when called outside of the parenthesis? -
CSRF token (in Django) vs Session token
From what I understand CSRF token is generated on the server and sent to the client on every login. When client sends the request, CSRF token is sent with it and client token is checked if it matches server token. Isn't this how Session token works as well? The only difference I see is that CSRF token isn't saved anywhere (it's in the hidden field) as opposed to session token which is saved is session cookie? If that's the case, then how Django CSRF cookie works? From other post: When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. The site should require every form submission to include this pseudorandom value as a form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An attacker cannot read any data sent from the server or modify cookie values, per the same-origin … -
DJANGO : ManyToManyField self symetrical unique together how to mange it?
I have some trouble trying to fetch some manytomanyrelated data in by Django Application Here is my model : SoftwareVersion(models.Model): id = models.AutoField( primary_key=True, db_index=True ) ... Some other fields ... incompatibilities= models.ManyToManyField( "self", symmetrical=True, blank=True, default=None, through="Incompatibilities" ) Incompatibilities(models.Model): id = models.AutoField( primary_key=True, db_index=True ) softwareversion_a = models.ForeignKey( "SoftwareVersion", models.CASCADE, db_index=True, db_column='softwareversion_a ', related_name='softwareversion_a', verbose_name="software version a", ) softwareversion_b = models.ForeignKey( "SoftwareVersion", models.CASCADE, db_index=True, db_column='softwareversion_b', related_name='softwareversion_b', verbose_name="softwareversion_b", ) status = models.BooleanField( verbose_name='Status', default=False ) class Meta: unique_together = (('softwareversion_a', 'softwareversion_b'),) To this I add in the SoftwareVersion's save method a logic to create related Incompatibilities for each new software version. I have tried several way to do it (with a loop or with a bulk_create) here is the bulk create function i use : # Inside SoftwareVersion Model class def save(self, force_insert=False, force_update=False, using=None, update_fields=None) -> None: save = super().save(force_insert, force_update, using, update_fields) Incompatibilities.objects.bulk_create( (Incompatibilities( softwareversion_a=self, softwareversion_b=software_version, status=False ) for software_version in SoftwareVersion.objects.exclude(self)), ignore_conflicts=True, batch_size=1000 ) return save First problem I have is this method ignore the unique_together constraint, it creates duplicates. Before i was using a loop on each SoftwareVersion to create an object but it was too long so i wanted to use bulk_create but it seems … -
Django Loglevel is undefined in project app views.py
I try to log something with INFO level in the views.py in a created app in my Django project. When I initialize the logger with: logger = logging.getLogger(__name__) the loglevel is set to 0 which means undefined. Why does it not read the log level defined in the settings py? I start the project in the pycharm IDE and a environment variable with name LOGLEVEL is set to INFO (I checked if the loglevel was correctly read by debugging the settings.py on startup and it is correct set to INFO) Project Structure: myApp views.py ... myproject settings.py ... settings.py loggin config: # Disable Django's logging setup LOGGING_CONFIG = None LOGLEVEL = os.environ.get('LOGLEVEL', 'info').upper() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { # Use JSON formatter as default 'default': { '()': 'pythonjsonlogger.jsonlogger.JsonFormatter', }, 'django.server': DEFAULT_LOGGING['formatters']['django.server'], }, 'handlers': { # Route console logs to stdout 'console': { 'class': 'logging.StreamHandler', 'formatter': 'default', }, 'django.server': DEFAULT_LOGGING['handlers']['django.server'], }, 'loggers': { # Default logger for all modules '': { 'level': LOGLEVEL, 'handlers': ['console', ], }, # Default runserver request logging 'django.server': DEFAULT_LOGGING['loggers']['django.server'], } } views.py logger = logging.getLogger(__name__) def teams_overview(request): try: print(f"loglevel set: {logger.level}") print(f"info logleve: {logging.INFO}") logger.error("error") logger.info("info") logger.warning("warning") logger.critical("critical") logger.debug("debug") output: error warning … -
How to pass json data to frontend using Django
I have response from another api of json data and i want to send this json data to my frontend to parse this json there But when im using return JsonResponse it just returns html with json i dont need that, i want to return blank html with json which was send on front and frontend with js will parse it views.py def json_project_budget(request): session = requests_cache.CachedSession('project_budget_cache') url = config('REPORT_PROJECT_BUDGET') response = session.get(url=url, auth=UNICA_AUTH).json() queryset = [] for item in response: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) obj = parsed_json.ObjectGUID for budget in parsed_json.BudgetData: budget.SectionGUID = CleanSections.objects.get(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) return JsonResponse(response, safe=False) I will update bcs i think that i understand my problem I have problems in url or something like that I have ListView which renders my template and the main question how am i suppose to send this function json_project_budget in my template to get json data? views.pyy class ShowProjectBudgetList(ListView): login_url = '/login/' redirect_field_name = '' template_name = 'customer/customer_home.html' context_object_name = 'json_list' allow_empty = True # paginate_by = 5 def get_queryset(self): return None urls.py path('customer/', ShowProjectBudgetList.as_view(), name='customer_view'), path('customer/', json_project_budget, name='json_project_budget'), -
Django cannot find TemplateDoesNotExist
I am trying to create a login page using django and I am getting this error. TemplateDoesNotExist at /accounts/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 4.1.5 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/template/loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: /Library/Frameworks/Python.framework/Versions/3.11/bin/python3 Python Version: 3.11.1 Python Path: ['/Users/jasonfan/Desktop/Swe/TAPortal', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python311.zip', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages'] Server time: Mon, 20 Mar 2023 17:02:00 +0000 I have a couple ideas of where the problem may lie. I created a templates/registration/login.html. Does it matter which directory i put these subdirectories in? My file structure is attached. This is my settings.py folder. I modified TEMPLATES. I added 'DIRS': [BASE_DIR/"templates"], I also added LOGIN_REDIRECT_URL = "/" at the bottom. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/"templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I also modified urls.py adding urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include("django.contrib.auth.urls")) ] I modified the login.html to a basic login screen and that is where I am trying to get to when i run server. I do http://127.0.0.1:8000/accounts/login/ -
Django Rest Framework: Remove Appended "[]" from List Parameter
I have a django rest framework application set up with two packages: One's called djangorestframework-camel-case (to "camelizes" the parameters in the API docs) and the other is drf-spectacular (to automatically generate Swagger docs for my API). The camel case package also has the effect that it causes parameters from the request data sent from the frontend (in camelCase) to be received in the Python backend in snake_case. However, I just found out that when one of the requests from the frontend contains a list of data, lets say dataList = ["1", "2", "3"], the parameter is received in the Python backend as a dictionary with the key data_list[]. Is there a setting to remove that [] at the end? Its messing up with the rest of my logic. -
Adding items to wishlist
so Im trying to work on adding a wishlist item to the wishlist page. So Im creating a view to add a wishlist to the page and a view to show the items ive added. But the issues ocurs when i press the add to wishlist button on a product.The item i added is not showing up in the wishlist page for some reason i cant seem to figure out. I get the error of add_to_wishlist() missing 1 required positional argument: 'product' Here is my code below: views.py: @login_required def wishlist(request): wishlist, created = Wishlist.objects.get_or_create(user=request.user.userprofile) return render(request, 'products/wishlist.html') @login_required def add_to_wishlist(request, product, product_id): product = Product.objects.get(id=product_id) return redirect('wishlist') @login_required def remove_from_wishlist(request, product_id): product = get_object_or_404(Product, pk=product_id) wishlist = Wishlist.objects.get(user=request.user.userprofile) wishlist.products.remove(product) return HttpResponseRedirect(reverse('add_to_wishlist')) models.py: class Wishlist(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) product = models.ManyToManyField(Product, blank=True) wishlist.html: {% block content %} <div class="overlay"></div> <div class="container"> <h1>My Wishlist</h1> <div class="row"> {% if wishlist.products.all %} {% for product in wishlist.products.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <div class="card-body"> <h2 class="card-title">{{ product.name }}</h2> <p class="card-text">{{ product.description }}</p> <p class="card-text">$ {{ product.price }}</p> <form action="{% url 'remove_from_wishlist' product.id %}" method="POST"> {% csrf_token %} <button class="btn btn-danger" type="submit">Remove from Wishlist</button> </form> </div> </div> </div> {% endfor %} … -
Inertia Django Vite not working on deployment
I'm trying to deploy this template to fly.io (https://github.com/mujahidfa/inertia-django-vite-vue-minimal.git). Additionally I installed "gunicorn" as WSGI-server. I got it running locally but if I deploy it, I get a CORS-error because Vite ist still requesting localhost. All I see is a white page. index.html: {% load django_vite %} <!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" /> {% vite_hmr_client %} {% vite_asset 'main.ts' %} <title>Inertia + Django + Vite + Vue minimal</title> </head> <body> {% block inertia %}{% endblock %} </body> </html> In the browser it gets resolved to: <!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" /> <script type="module" src="http://localhost:5173/static/@vite/client"></script> <script type="module" src="http://localhost:5173/static/main.ts"></script> <title>Inertia + Django + Vite + Vue minimal</title> </head> <body> <div id="app" data-page="{&quot;component&quot;: &quot;Index&quot;, &quot;props&quot;: {&quot;name&quot;: &quot;World&quot;}, &quot;url&quot;: &quot;http://nameless-mountain-1344.fly.dev/&quot;, &quot;version&quot;: &quot;1.0&quot;}"></div> </body> </html> I think the interesting parts are: {% vite_hmr_client %} {% vite_asset 'main.ts' %} <script type="module" src="http://localhost:5173/static/@vite/client"></script> <script type="module" src="http://localhost:5173/static/main.ts"></script> Has anybody an idea how to get it working? I couldn't figure it out for days now. I've tried fiddling with the Dockerfile, but I'm still in the eary phase with fullstack-developement. Also in the vite.config.ts I've tried many … -
why do i get Forbidden (403) CSRF verification failed. Request aborted. when I'm trying to register?
from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm def register(response): if response.method == 'POST': form = UserCreationForm(response.POST) if form.is_valid(): form.save() else: form = UserCreationForm() return render(response, 'register/register.html', {'form':form}) html {% extends 'libraryfinish/base.html' %} {% block title %} Create an account {% endblock %} {% block content %} <form method="POST", class="form-group"> {% csrf_token %} {{form}} <button type="submit", class="btn btn-success">Register</button> </form> {% endblock %} I found that I should pass the RequestContext in my render_to_response for the context processors to actually be run, but I'm not using render to response from django.views.decorators.csrf import csrf_protect @csrf_protect doesn't work