Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files not loading properly
Things I have done: 1.base template i have provide {% load static %} <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="apple-touch-icon" sizes="76x76" href="/static/assets/img/apple-icon.png" > <link rel="icon" type="image/png" href="{% static 'assets/img/favicon.png' %}" > <title> Al Amal Jewellery - {% block title %}{% endblock %} </title> <!-- Fonts and icons --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet" /> <!-- Nucleo Icons --> <link href="{% static "assets/css/nucleo-icons.css" %}" rel="stylesheet" /> <!-- Font Awesome Icons --> <script src="https://kit.fontawesome.com/42d5adcbca.js" crossorigin="anonymous"></script> <!-- CSS Files --> <link id="pagestyle" href="{% static "assets/css/soft-ui-dashboard.css?v=1.0.5" %}" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha256-eTyxS0rkjpLEo16uXTS0uVCS4815lc40K2iVpWDvdSY=" crossorigin="anonymous"></script> <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} </head> <body class="{% block body_class %}{% endblock %}"> {% include "includes/sidebar.html" %} <main class="main-content max-height-vh-full h-100"> {% include "includes/navigation.html" %} {% block content %}{% endblock content %} </main> {% include "includes/fixed-plugin.html" %} {% include "includes/scripts.html" %} <!-- Specific JS goes HERE --> {% block javascripts %}{% endblock javascripts %} <script> var win = navigator.platform.indexOf('Win') > -1; if (win && document.querySelector('#sidenav-scrollbar')) { var options = { damping: '0.5' } Scrollbar.init(document.querySelector('#sidenav-scrollbar'), options); } </script> </body> </html> statics in setting.py based on Managing Static Files """ Django settings for … -
build docker container with postgresql on rpi2
I built django project with cookie-cutter-django. Everything works fine on my local, I could build and running stacks. Now, I am trying to deploy it to my raspberry pi 2. But having issue with psycopg. First, here is the basic config of the project. cookie-cutter-django django 4.2.8 python 3.11.7 Secondly, here is my rpi os info. Operating System: Raspbian GNU/Linux 11 (bullseye) Kernel: Linux 6.1.21-v7+ Architecture: arm postgresql is not installed Thirdly, my local device for development. ubuntu 22.04 I cloned the repo and tried to build production.yml. And got this error. 417.5 Collecting prompt-toolkit==3.0.43 (from -r production.txt (line 50)) 417.6 Downloading prompt_toolkit-3.0.43-py3-none-any.whl.metadata (6.5 kB) 420.4 ERROR: Could not find a version that satisfies the requirement psycopg-binary==3.1.17 (from versions: none) 420.4 ERROR: No matching distribution found for psycopg-binary==3.1.17 I researched a lot, but couldn't find the right answer. The possible solution I could think of was installing the pure python installation on psycopg official documentation. so I tried to add libpq5 to Dockerfile, but having different error like this screenshot. Here is my production Dockerfile. FROM node:20-bullseye-slim as client-builder ARG APP_HOME=/app WORKDIR ${APP_HOME} COPY ./package.json ${APP_HOME} RUN npm install && npm cache clean --force COPY . ${APP_HOME} RUN npm run … -
Django no app_label in model
I have a django rest app called hotels, my structure directory is the following: app/ ├── config │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── hotels │ ├── admin.py │ ├── apps.py │ ├── filters.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── serializers.py │ ├── tests │ └── views.py ├── __init__.py └── __pycache__ └── __init__.cpython-38.pyc In the models.py file I have defined a class called HotelChain as follows: class HotelChain(TimestampedModel): PRICE_CHOICES = [ (1, "$"), (2, "$$"), (3, "$$$"), (4, "$$$$"), ] title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) description = models.TextField(blank=True) email = models.EmailField(max_length=50, blank=True) phone = models.CharField(max_length=50, blank=True) website = models.URLField(max_length=250, blank=True) sales_contact = models.CharField(max_length=250, blank=True) price_range = models.PositiveSmallIntegerField(null=True, blank=True, choices=PRICE_CHOICES) def __str__(self): return f"{self.title}" But I am getting this error: RuntimeError: Model class app.hotels.models.HotelChain doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I tried adding class Meta: app_label = 'hotels' To the class definition but it doesn't fix the issue. My app config is this one: INSTALLED_APPS = ( 'hotels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'import_export', ) -
How to grant permissions to a so that server allows the creation of directories on the fly
When a user uploads a picture, my django code creates a directory (or folder if you want) with his name (picked up from the session user). This works in my local development environment but production does not grant that permission just like that. So, for savy system administrators out there here it goes: This code is fine MODEL def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user, filename) images = ResizedImageField(size=[500, 300], upload_to=user_directory_path, blank=True, null=True) VIEWS.py for image in images: Photos.objects.create(images=image, builtproperties_id=last_built_id, user=username) So, this creates me a directory in this path: media/user_peter media/user_mary etc I thought that by doing this: sudo chmod 775 media It would allow the creation of subdirectories (user_peter, user_mary etc) but, apparently it does not as I got a "permission denied" wrist slap. What command would do that? Thank you -
Is it possible to use requests-cache functionalities on vercel?
Since vercel doesn't support SQLite, I am wondering if python applications like Django deployed on vercel will be able to leverage the functionalities of python's popular requests-cache library. Reason for this is because this library generate SQLite files for caching purpose. Also, is there any workaround using SQLite on vercel. What I tried: using requests-cache library for serverless environment. What is expected: Django app running without any problem on vercel -
Using Model Field Values inside Model.py
I have Model in django and I wanna use username value inside this Account Model to Address ImageField How can I do that? class Account(models.Model): nickname = models.CharField(max_length=150) username = models.CharField(max_length=70) password = models.CharField(max_length=70) email = models.EmailField(max_length=70) avatar = models.ImageField(upload_to = f'userdata/{username}/avatar/' ,default= MEDIA_ROOT + 'default/img/avatar.png') -
Dealing with Tokens in django and react
I'm currently working on a social network app for my Backend, I'm using Django and for the Frontend React-TS. After doing a bit of research, I've decided to use a JWT Token (Generated with help of rest_framework_simplejwt), and use it in requests as a BearerToken. Currently, I'm saving the AccessToken and the RefreshToken in the local storage, but having read a bit about how storing tokens in local storage can pose security risks, such as exposure to Cross-Site Scripting (XSS) attacks, I grew a bit worried. I thought I'd ask here since I came across too many suggestions online (HTTP-Only Cookies, Database Storage with Encryption and Password-Based Encryption). Since I lack the experience to decide which to use when, I would appreciate any and every advice. How do you store your Tokens and why? -
Contact Form, with sending emails but no email is received, DJANGO REST FRAMEWORK
My problem is the terminal says that it is sending email, but there is no email received. Here is my views ` from rest_framework.views import APIView from GoGet import settings from .models import * from rest_framework.response import Response from .serializer import * from django.core.mail import send_mail from django.conf import settings Create your views here. class ContactView(APIView): serializer_class = ContactSerializer def post(self, request): serializer = ContactSerializer(data=request.data) # subject = models.Contact.subject if serializer.is_valid(raise_exception=True): serializer.save() self.send_contact_email(serializer.validated_data) return Response(serializer.data) def send_contact_email(self, data): subject = 'New Contact Form Submission' message = f''' Name: {data['name']} Email: {data['email']} Subject: {data['subject']} Message: {data['message']} ''' send_mail( subject, message, settings.EMAIL_HOST_USER, # Sender's email address [settings.CONTACT_EMAIL], # Receiver's email address (can be a list of multiple emails) fail_silently=True, )` Im expecting an email, but i dont receive any, checked the spams, sent, there is nothing -
Django Auth Login
I have a django project, when I create a user from empty migration files, I can logged in perfectly. But when I create a user from POST method, I can't logged in and it throwing invalid credentials. This is my user model class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField("Username", max_length=50, unique=True) password = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_password_reset = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True, blank=True) roles = models.ManyToManyField(Role, related_name='users') def delete(self, *args, **kwargs): self.deleted_at = timezone.now() self.save() def save(self, *args, **kwargs): # Hash the password before saving self.password = make_password(self.password) super(User, self).save(*args, **kwargs) def __str__(self): roles_str = "\n".join([str(role) for role in self.roles.all()]) return f"(username: {self.username}, id: {self.id}, is_active: {self.is_active}, is_password_reset: {self.is_password_reset}, roles:\n{roles_str})" this is my login API view @api_view(['POST']) @authentication_classes([]) @permission_classes([AllowAny]) def login(request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user: serializer = UserSerializer(user, context={'request': request}) refresh = RefreshToken.for_user(user) data = { 'user': serializer.data, 'refresh': str(refresh), 'access': str(refresh.access_token), } return Response(data) else: return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) I already tried to debug using raw password without hashing and print out the request from login. It prints out exactly the same as in the database. But it keeps … -
Herokuga django loyihamni joylashtirdim
Men loyihamni migrate va createsuperuser qilishim lozim. Lekin buni amalga oshirib bulmayapti. Qanday qilib loyihamni migrate qilsam buladi. Qanday tavsiya beraszlar Run consoledan migrate va boshqa buyruqlarni berdim ammo buyruqlarimni loyiha papkasiga saqlamayapti -
Django 5 signal asend: unhashable type list
Trying to make a short example with django 5 async signal. Here is the code: View: async def confirm_email_async(request, code): await user_registered_async.asend( sender=User, ) return JsonResponse({"status": "ok"}) Signal: user_registered_async = Signal() @receiver(user_registered_async) async def async_send_welcome_email(sender, **kwargs): print("Sending welcome email...") await asyncio.sleep(5) print("Email sent") The error trace is: Traceback (most recent call last): File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\django\core\handlers\exception.py", line 42, in inner response = await get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\asgiref\sync.py", line 534, in thread_handler raise exc_info[1] File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\django\core\handlers\base.py", line 253, in _get_response_async response = await wrapped_callback( ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\karonator\Desktop\signals\main\views.py", line 34, in confirm_email_async await user_registered_async.asend( File "C:\Users\karonator\AppData\Roaming\Python\Python311\site-packages\django\dispatch\dispatcher.py", line 250, in asend responses, async_responses = await asyncio.gather( ^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\asyncio\tasks.py", line 819, in gather if arg not in arg_to_fut: ^^^^^^^^^^^^^^^^^^^^^ TypeError: unhashable type: 'list' Will be grateful for any help, already broken my head. Thanks for your time. -
Getting 'Something went wrong' on form submission in Django signup view
I am experiencing an issue in my Django project's signup view. When I submit the form, the console prints 'Something went wrong,' and the user is not created. I have a custom User model, and the signup view appears to be correctly handling form data. However, despite thorough checks of my code, I'm unable to identify the root cause of the problem. --views.py from django.shortcuts import render, redirect from .models import User def signup(request): if request.method == 'POST': name = request.POST.get('name', '') email = request.POST.get('email', '') password1 = request.POST.get('password1', '') password2 = request.POST.get('password2', '') if name and email and password1 and password2: user = User.objects.create_user(name, email, password1) print('User created:', user) return redirect('/login/') else: print('Something went wrong') else: print('Just show the form!') return render(request, 'account/signup.html') I have also made the following settings: AUTH_USER_MODEL = 'account.User' --models.py import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager from django.db import models class CustomUserManager(UserManager): def _create_user_(self, name, email, password, **extra_fields): if not email: raise ValueError('You did not provide an valid e-amil address') email = self.normalize_email(email) user = self.model(email=email, name=name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, name=None, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user_(name, email, password, **extra_fields) def create_superuser(self, name=None, email=None, password=None, **extra_fields): … -
Guidelines to be good with programming [closed]
Please I really need help, I have been in the field of building websites for more than 3 years now as self thought but it seems as if I'm not learning, please guide me through on how best to be self thought I have tried building projects from Youtube but I always fail. how where and how can I build websites with python and Framework Django -
DRF override default router path
When i register viewset in SimpleRouter i get paths like [get] objects/ [post] objects/ [get] objects/{id} etc. Is there a way to replace default post route with its detailed version? like [post] objects/{id} I've tried to replace it with action in viewset @action(detail=True, methods=['post'], url_path="my-path"): def my_action: ... but all i've got is [post] /objects/{id}/my-path and default post path is still there -
how to delete cache on my VPS Ubuntu Server. Whatever I write on any page is never shown
This is driving me insane. No matter what I do on the pages nothing is shown. Even if I write "hello" on my index.html page it will not show it. The server only shows what I pulled from github a week ago. Nothing, no change. I added the sentry logging tool, it takes zero notice, I copied pasted the logging snippet used and it completely ignores it. I write an extra word on the menu bar at the top, nothing is shown. -
drf-yasg: how to skip some operations during generate_swagger
I use Django with drf-yasg. I have a REST endpoint similar to the following: @swagger_auto_schema( method="POST", request_body=... ) @api_view(["POST"]) def do_something(request: Request) -> HttpResponse: ... When I run the server, I see the do_something operation in /swagger panel, which is fine. Now, when I run ./manage.py generate_swagger I would like do_something operation to NOT show in the resulting OpenAPI yaml. I would like to be able to somehow annotate the operation to be conditionally included, like with some custom @include_conditionally decorator: @include_conditionally @swagger_auto_schema(...) @api_view(["POST"]) def do_something(request: Request) -> HttpResponse: ... I know that setting auto_schema=None prevents the endpoint from being included in Swagger, but it excludes the endpoint from both Swagger web panel and the yaml schema, which I do not want. I tried to use my own generator in ./manage.py generate_swagger -g MyGenerator class MyGenerator(OpenAPISchemaGenerator): def should_include_endpoint(self, path, method, view, public): ... while should_include_endpoint seems to be the right way to go, I failed to detect if the operation was annotated with include_conditionally. Background: I want to exclude some of the endpoints from being exposed with Google ESP while being available locally. How can I exclude some endpoints conditionally from being included in Swagger schema yaml file? -
Re-translate Django
Django comes translated in my language however it's not complete and I don't like some of the translated phrases (personal preference). So I set the locale folder up and run python manage.py makemessages -l fa_IR and I get the file django.po but when I open it, I find that the phrases that are already translated and included with Django are not there. So looks like I have to edit (for example) \venv\Lib\site-packages\django\contrib\auth\locale\fa\LC_MESSAGES\django.po but if I ever update Django package of this project, all my edits will be lost, right? Is there any other solution? -
sorting DataTables from Django
I'm currently working on a Django project where I need to display and sort weather station data in a DataTable. I'm facing an issue when it comes to sorting columns that contain calculated values, such as averages and sums. this code result in clickhouse error due to a problem with the inner join not working as properly I am out of ideas to sort the values (avg_value, max_value,min_value, sum_value, and count_value) please help @cache_page(120) @api_view(['GET']) def station_list(request): serializer = StationListSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) # Extracting DataTables parameters draw = int(request.GET.get('draw', 1)) start = int(request.GET.get('start', 0)) length = int(request.GET.get('length', 10)) order_column_index = int(request.GET.get('order[0][column]', 0)) order_direction = request.GET.get('order[0][dir]', 'asc') search_value = request.GET.get('search[value]', '') selected_region = request.GET.get('region') selected_governorate = request.GET.get('governorate') # QuerySet for AwsGov station_queryset = AwsGov.objects.all() if selected_region: station_queryset = station_queryset.filter(ADMIN=selected_region) if selected_governorate: station_queryset = station_queryset.filter(REGION_ID=selected_governorate) # Define columns for sorting and filtering direct_fields = ['station_id', 'Name', 'ADMIN_NA_1', 'REGION_N_1'] all_fields = direct_fields + ['avg_value', 'max_value', 'min_value', 'sum_value', 'count_value'] # Adjust for language if request.LANGUAGE_CODE == 'ar': direct_fields = ['station_id', 'Name', 'ADMIN_Name', 'REGION_NAM'] if order_column_index < len(all_fields): order_column = all_fields[order_column_index] else: order_column = all_fields[0] # else: # order_column = columns[0] # Default to the first column if out of range if order_column in direct_fields: if … -
Django models, filter based on the division of two fields
I am having trouble understanding the annotate of django models. I am trying to build a datatable where one of its value is the division of two fields that might contain zeros and filter the rest based on the user input so what I tried so far is: model from django.db import models from django.utils import timezone class Item(models.Model): item_name = models.CharField(max_length=200) item_price = models.FloatField(default=0.0) unit_per_item = models.FloatField(default=1) description = models.TextField(default='') is_active = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) date_added = models.DateTimeField(default=timezone.now) views from django.db.models import Q, F, Case, When, FloatField from .models import Item if request.POST['search[value]']: model_obj = Item.objects.annotate( unit_price = Case( When(Q(item_price__exact=0) | Q(unit_per_item__exact=0), then=0), default=F("item_price") / F("unit_per_item"), output_field=FloatField() ) ).filter( Q(item_name__icontains=request.POST['search[value]'])| Q(item_price__icontains=request.POST['search[value]'])| Q(unit_per_item__icontains=request.POST['search[value]'])| Q(description__icontains=request.POST['search[value]'])| Q(unit_price__icontains=request.POST['search[value]']) )[start:length] But I am getting an error that says RegisterLookupMixin.get_lookup() missing 1 required positional argument: 'lookup_name' What I am essentially trying to achieve here in SQL is this SELECT *, item_price/unit_per_item AS unit_price FROM inventory_item WHERE item_name LIKE '%some_value%' OR item_price LIKE '%some_value%' OR unit_per_item LIKE '%some_value%' OR description LIKE '%some_value%' OR CONVERT( CASE WHEN item_price=0 OR unit_per_item=0 THEN item_price ELSE item_price/unit_per_item END, CHAR) LIKE '%some_value%'; I am honestly a little lost at this point, if there is a documentation that can expound further … -
Which package to use when dealing with storing and displaying document files like pdf word excel etc in Django and Oracle
I have a requirement where I need to store documents( pdf, word, excel in Oracle database) and display a list of these files on a page serially. When clicked on its name it should open in next tabs in browser. I also need to be able to search and count few keywords in these documents while it been store in the Database. I am just not sure which package I must use in Django for this requirement and which datatype to be used in Oracle. Can anybody please help me for getting started in right direction. -
Implementing pagination in Angular Material with Django rest frameork
I am trying to implement pagination in my Angular Material that will work with the data coming from my Django server but I haven't gotten it right. Here is my customer.component.ts export class CustomerComponent { customers: Customer[] = [] dataSource: any; displayedcolumns: string[] = ['name', 'phone', 'debt_amount', 'remaining_credit', 'created_at', 'action'] @ViewChild(MatPaginator) paginator!: MatPaginator; @ViewChild(MatSort) sort!: MatSort; constructor(private http: HttpClient, private customerService: CustomerService,) {} ngOnInit(): void { this.fetchCustomers() } fetchCustomers() { this.customerService.getCustomers().subscribe({ next: (data: ApiResponse<Customer[]>) => { this.customers = data.results; this.dataSource = new MatTableDataSource<Customer>(this.customers) this.dataSource.paginator = this.paginator this.dataSource.sort = this.sort console.log(this.customers); }, error: (error: any) => { console.error('Error fetching customers', error); }, complete: () => { console.log('Finished fetching customers'); } }); } Filterchange(data:Event) { const value = (data.target as HTMLInputElement).value; this.dataSource.filter = value; } } Below is my customer.component.html <mat-card-header> <mat-form-field> <input matInput (keyup)="Filterchange($event)" placeholder="Search by Name" /> </mat-form-field> </mat-card-header> <mat-card-content> <table matSort mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container matColumnDef="name"> <th mat-sort-header mat-header-cell *matHeaderCellDef="">Name</th> <td mat-cell *matCellDef="let element">{{element.first_name}}</td> </ng-container> <ng-container matColumnDef="phone"> <th mat-header-cell *matHeaderCellDef="">Phone</th> <td mat-cell *matCellDef="let element">{{element.phone}}</td> </ng-container> <ng-container matColumnDef="debt_amount"> <th mat-header-cell *matHeaderCellDef="">Debt Amount</th> <td mat-cell *matCellDef="let element">{{element.debt_amount}}</td> </ng-container> <ng-container matColumnDef="remaining_credit"> <th mat-header-cell *matHeaderCellDef="">Remaining Credit</th> <td mat-cell *matCellDef="let element">{{element.remaining_credit}}</td> </ng-container> <ng-container matColumnDef="created_at"> <th mat-sort-header mat-header-cell *matHeaderCellDef="">Created At</th> <td mat-cell *matCellDef="let element">{{element.created_at | … -
(CRUD) Inventory System with Sub-inventories in DJANGO
This CRUD is basically a Main Inventory(a), which is going to be used by the inventory manager to feed workers inventories(b,c,d..)... When I try to transfer an item from A to B, the item gets transferred successfully, however, if item already exists, it still creates a new one, duplicating the Item several times. For Example: If a subinventory has "2 Screws", I add "3 Screws". Now the Subinventory has "2 Screws, and "3 Screws", instead of having now "5 Screws". The Models: Main Inventory class Articulo(models.Model): id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=50) descripcion = models.CharField(max_length=100, null=True) costo = models.IntegerField(null=True) cantidad = models.IntegerField(null=True) medida = models.CharField(max_length=20) fecha_ingreso = models.DateTimeField(auto_now_add=True, null=True) fecha_salida = models.DateTimeField(auto_now_add=True, null=True) ubicacion = models.CharField(max_length=50, default='Almacen') SubItem and Subinventory class articuloInventario(models.Model): articulo = models.CharField(max_length=50, null=True) cantidad = models.IntegerField(null=True) medida = models.CharField(max_length=20, null=True) fecha_ingreso = models.DateTimeField(auto_now_add=True, null=True) ubicacion = models.IntegerField(null=True) class brigadaInventario(models.Model): id = models.AutoField(primary_key=True) articulos = models.ManyToManyField(articuloInventario) Views: def transferir_articulo(item_id, quantity): item_a = get_object_or_404(Articulo, id=item_id, cantidad__gte=quantity) item_b = get_object_or_404(articuloInventario, id=item_id, cantidad__gte=quantity) inventario = articuloInventario.objects.all() for b in inventario: if item_a.nombre == b.articulo: item_a.cantidad -= quantity item_a.save() b.cantidad += quantity b.save() return JsonResponse({'mensaje': f'{quantity} items transferred from inventory A to inventory B.'}) item_a.cantidad -= quantity item_a.save() item_b.cantidad += quantity item_b.save() … -
I try to install geonode using ubuntu 20.04 and i failed in "docker-compose logs -f django"
i have an error while loging into geonode in ubuntu 20.04 specifically in the command : docker-compose logs -f django it stops at this line : MONITORING_DATA_TTL=365 and then exits with code 1 i tried to fix this several times but with no succes -
Unable to Commit Changes in Django Project When Including External Repository with Sass Partials
I am working on a Django project where I need to incorporate an external repository containing Sass partials for styling. To achieve this, I performed a git clone of the Sass partials repository into my Django project's repository. However, I've encountered an issue where any commits I make do not include the folder from the cloned Sass partials repository. It seems like the changes within the cloned repository are not being tracked or committed within the main Django project. Here are the steps I took: Cloned the Sass partials repository into my Django project: git clone <repository_url> Checked that the Sass partials folder is present within my Django project. Made changes to the Sass files and attempted to commit: git add . git commit -m "Made changes to Sass files" However, the commit does not include the changes made in the Sass partials folder. Additionally, I would like to emphasize that I do not want the changes made to the Sass partials to be committed within the Django project. I intend to maintain the Sass partials repository as a template only. I suspect there might be something related to the submodule behavior, but I want to ensure that the changes … -
Get graphics in Vue.js
I want to create a personal web application using Django for the backend and Vue.js for the frontend, but I need to know if it is possible to use graphics in Vue.js, is that possible? In my application, I want to implement regression functions in Django to visualise the output in graphics in Vue.js and I want also to show the data flow of some features of my data. Tell me if this is possible, thanks. I haven't tried to do anything yet because it is all a working progress.