Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to give specific users specific persmissions to view and edit Specific Areas in Django admin
I'm making a django website whose admin page looks like this I want users(The content writer) to access only the Main Area(Events, Formats, Organisers) and not the whole thing. I haven't made any such user as Content Writer as of now. What are the permissions that should be given to that user. Should I make Groups for users(since there are basically 3 types of users as of now, i.e., Admin(Full Access), Content Writer(Limited Access), Basic Users(No access)) or should I just add one/two more variable(s) in my custom user model so that that user can access only the main area of the admin site. After Giving these permissions can I extract the main area on a new html page and style it accordingly as:- Events, Formats, Organisers, in Navbar and the details of these page presented somewhat beautifully models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # Custom User Manager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name=None, **extra_fields): if (not email): raise ValueError("Email Must Be Provided") if (not password): raise ValueError("Password is not Provided") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_active', … -
Django - POST/GET for HyperlinkedIdentityField
I've tried following several guides https://stackabuse.com/creating-a-rest-api-with-django-rest-framework/ https://www.django-rest-framework.org/tutorial/2-requests-and-responses/ Both were not suited because my code uses a HyperlinkedIdentityField How may I go and add a POST/GET request to it? views.py class SpecialityView(APIView): def get(self, request, id=None): if id: item = Speciality.objects.get(id=id) serializer_class = SpecialitySerializer(item) return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) items = Speciality.objects.all() serializer_class = SpecialitySerializer(items, many=True) return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) def post(self, request): serializer_class = SpecialitySerializer(data=request.data) if serializer_class.is_valid(): serializer_class.save() return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer_class.errors}, status=status.HTTP_400_BAD_REQUEST) class WorkerView(APIView): def get(self, request, id=None): if id: item = Worker.objects.get(id=id) serializer_class = WorkerSerializer(item) return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) items = Worker.objects.all() serializer_class = WorkerSerializer(items, many=True) return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) def post(self, request): serializer_class = WorkerSerializer(data=request.data) if serializer_class.is_valid(): serializer_class.save() return Response({"status": "success", "data": serializer_class.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer_class.errors}, status=status.HTTP_400_BAD_REQUEST) serializers.py class SpecialitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Speciality fields = ['id', 'url', 'name'] class WorkerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Worker fields = ['id', 'url', 'name', 'last_name', 'hire_date', 'email', 'phone_number', 'job', 'speciality', 'salary', 'commission_pct', 'manager_id', 'department_id'] Error page : AssertionError at /speciality/ `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. -
Is it possible to restore data from docker postgres volume backup
Primarely wanted to migrate postgress volume to another host, following this instruction https://docs.docker.com/storage/volumes/ on macos made a backup of volume using docker run --rm --volumes-from a1df4bee1dc1 -v $(pwd):/backup debian:jessie tar cvf /backup/backup_db_floo.tar /var/lib/postgresql/data And after deleting and recreating new container/volume and restoring via docker run --rm --volumes-from docker-db-1 -v $(pwd):/backup debian:jessie bash -c "cd /var/lib/postgresql/data && tar xvf /backup/backup_db_floo.tar --strip 1" no my data is there. Now realise that it was bad idea and i have to use pg_dumpall - but is it possible to recover somehow database from that postgres volume backup? -
CREATE MANY TO MANY FIELD DATA IN SERIALIZER
I am trying to send a post request to create an object - course, but every time I get an error, how can I write a serializer for a class - course. What do I need to do so that it creates an object and at the same time displays a list of contacts instead of a list of keys MODELS: class Category(models.Model): title = models.CharField(max_length=30) imgpath = models.CharField(max_length=100) def __str__(self): return self.title class Branch(models.Model): latitude = models.CharField(max_length=250) longitude = models.CharField(max_length=250) address = models.CharField(max_length=250) def __str__(self): return self.address class Contact(models.Model): class Type(models.IntegerChoices): PHONE = 1, FACEBOOK = 2, EMAIL = 3 type = models.IntegerField(choices=Type.choices) value = models.CharField(max_length=250) def __str__(self): return self.value class Course(models.Model): name = models.CharField(max_length=30) description = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') logo = models.CharField(max_length=20, blank=True) contacts = models.ManyToManyField(Contact) branches = models.ManyToManyField(Branch, blank=True) def __str__(self): return self.name SERIALIZER: from rest_framework import serializers from application.category.models import Category, Branch, Contact, Course class CategorySerializers(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class BranchSerializer(serializers.ModelSerializer): class Meta: model = Branch fields = '__all__' class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__' class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = '__all__' def create(self, validate_data): contacts_data = validate_data.pop('contacts') branchs_data = validate_data.pop('branches') … -
Django page reloading too long
I have some issues with the reloading time in some page in django, it takes too long. I use debug_toolbar and shows me Browser timing request: 4 (+113577) models.py class Subsidiary(models.Model): name = models.CharField(unique=True, max_length=100, blank=False) def __str__(self): return self.name class Department(models.Model): name = models.CharField(unique=True, max_length=200, blank=False,) def __str__(self): return self.name class SubBudget(models.Model): name = models.CharField(max_length=100, unique=True, blank=False) def __str__(self): return self.name class SubBudgetOwner(models.Model): budget_owner = models.ForeignKey(Person, models.PROTECT, related_name="budgets_owned") sub_budget_owner = models.ForeignKey(Person, models.PROTECT, related_name="sub_budgets_owned") class Meta: ordering = ["id"] unique_together = (("budget_owner", "sub_budget_owner"),) verbose_name = "Budget Owner" # Title on the maint page for this table verbose_name_plural = "Budget Owners" # Title for the navbar navigation def __str__(self): return str(self.budget_owner) + " - " + str(self.sub_budget_owner) class Combination(models.Model): id = models.AutoField(primary_key=True) subsidiary = models.ForeignKey(Subsidiary, verbose_name="Subsidiary", null=True, blank=True, on_delete=models.CASCADE,) department = models.ForeignKey(Department, verbose_name="Department", on_delete=models.CASCADE,) sub_budget = models.ForeignKey(SubBudget, verbose_name="Sub Budget", on_delete=models.CASCADE,) budget_owner = models.ForeignKey(SubBudgetOwner, verbose_name="Budget Owner & Sub Budget Owner", null=True, blank=True, on_delete=models.CASCADE,) def __str__(self): return (f"{self.subsidiary} {self.department} {self.sub_budget} {self.budget_owner}") class Meta: ordering = ["id"] My views.py class CombinationListView(LoginRequiredMixin, ListView): model = Combination template_name = "budget/combination_list.html" What can I do to improve it? TNX guy -
Django ORM , Query optimization
I am building e-commerce website with Django and wanted to optimize my database , but stuck with the following problem: I have Order model which has property attributes, like : overallamount and overallprice .So they make many similar queries to the database , is there any way to optimize it . models.py class Product(models.Model): name = models.CharField(max_length=15) price = models.IntegerField() digital = models.BooleanField(default=False) image = models.ImageField(upload_to='store/', null=True, blank=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, default=None, null=True, on_delete=models.SET_NULL) completed = models.BooleanField(default=False) date_ordered = models.DateField(auto_now=True) @property def overallprice(self): return sum([item.totalprice for item in self.orderitem_set.all()]) @property def overallamount(self): return sum([item.quantity for item in self.orderitem_set.all()]) def __str__(self): return str(self.customer) class OrderItem(models.Model): order = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL) date_ordered = models.DateField(auto_now=True) product = models.ForeignKey(Product, default=None, null=True, on_delete=models.SET_NULL) quantity = models.IntegerField(default=0) views.py @login_required(login_url='login') def cart(request): order, created = Order.objects.get_or_create(customer=request.user.id) orderitem = OrderItem.objects.filter(order=order).select_related('product') return render(request, 'cart.html', {'orderitem': orderitem, 'order': order}) and the template/cart.html {%extends 'layout.html'%} {% load static %} {%block content%} <div class="box-element"> <a class="btn btn-outline-dark" href="{% url 'menu' %}">&#x2190; Continue Shopping</a> <br> <br> <table class="table"> <tr> <th><h5>Items:<strong>{{order.overallamount}}</strong></h5></th> <th><h5>Total:<strong>${{order.overallprice}}</strong></h5></th> <th> <a style="float:right; margin:5px;" class="btn btn-success" href="{% url 'checkout' %}">Checkout</a> </th> </tr> </table> </div> <div class="box-element"> <div class="cart-row"> <div style="flex:2"></div> <div style="flex:2"><strong>Item</strong></div> <div style="flex:1"><strong>Price</strong></div> <div style="flex:1"><strong>Quantity</strong></div> … -
Not able to migrate for my custom user model
Hey guys I am having this problem with my django migrations when I am trying to create a custom user model for my website So what is happening is when I run migrations it throws an error on me saying:- ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'user.newuser', but app 'user' doesn't provide model 'newuser'. The field user.UserInfo.user was declared with a lazy reference to 'user.newuser', but app 'user' doesn't provide model 'newuser'. I tried my best to try and debug it but it nothing is working i also did follow a answer on stack overflow but that also did not work I have implemented everything that is needed so yea the rest is the rest, and here is my code along with the migrations file models:- class CustomAccountManager(BaseUserManager): def create_user(self, first_name, last_name, phone_number, email, password, **other_fields): if not email: raise ValueError(_('You must provie an email address')) if not first_name: raise ValueError(_('You must provide a first name')) if not last_name: raise ValueError(_('You must provide a last name')) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, phone_number=phone_number, **other_fields) user.set_password(password) return user def create_superuser(self, email, first_name, last_name, phone_number, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') … -
How to manage devices on docker-compose automatically?
Here is the docker-compose.yml to map local USB cameras to container on a django web application. In this case, it works if 10 cameras are connected to the local PC, but cause errors if I take out any of them because the container can not map some of the cameras listed up. So for now, I need to comment out them depending on the number of cameras connected to the local. Is there any solutions for this case so that I do not have to comment out like I mentioned above? version: '3' web: build: . devices: # Here is the problem!!! - '/dev/video0:/dev/video0:mwr' - '/dev/video1:/dev/video1:mwr' - '/dev/video2:/dev/video2:mwr' - '/dev/video3:/dev/video3:mwr' - '/dev/video4:/dev/video4:mwr' - '/dev/video5:/dev/video5:mwr' - '/dev/video6:/dev/video6:mwr' - '/dev/video7:/dev/video7:mwr' - '/dev/video8:/dev/video8:mwr' - '/dev/video9:/dev/video9:mwr' ports: - '8000:8000' volumes: - '.:/code' tty: true stdin_open: true command: > bash -c 'python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000' Thank you in advance for my very first question in stack overflow! -
Why doesn’t Heroku add or remove database tables after initial launch for django app
So I punched my Django app on heroku and every thing has been going fine for about 3 weeks now. Now I want to update my models and add more fields but when I do so, it doesn’t seem to update the database. I run the following: heroku run python manage.pu makemigrations and the same for migrate. Every run through fine but the migrations doesn’t really go through although it says the fields have been altered. Anyone know how to update models for django app on heroku after initial launch? -
How can I run Javascript on Django without exposing static files?
On my Django site, I used Stripe to integrate payments in a .js file. I noticed that this file appears under Sources in the developer tools when you "Inspect Element" on any browser. Anyone can access this file (scary). How can I restructure my file organization so that apple-pay.js is not public facing? home.html {% load static %} <!DOCTYPE html> <html> <head> // Scripts for CSS and Stripe Pay </head> <body> <section> <div id="payment-request-button" data-amount="{{event.price}}" data-label=". {{event.public_name}}"> <!-- A Stripe Element will be inserted here if the browser supports this type of payment method. --> </div> <div id="messages" role="alert"></div> </section> </body> </html> apple-pay.js document.addEventListener('DOMContentLoaded', async () => { const stripe = Stripe('pk_mykeyishere'); //need to protect this information and the other functions from bad actors ///functions I run here }); My file structure: ├── Procfile ├── README.md ├── db.sqlite3 ├── interface │ ├── migrations │ ├── models.py │ ├── static │ │ ├── apple-developer-merchantid-domain-association │ │ └── interface │ │ ├── apple-pay.js <------------------ │ │ ├── CSS/other JS files │ ├── templates │ │ └── interface │ │ ├── home.html <------------------- │ ├── urls.py │ └── views.py ├── manage.py └── AppName ├── settings.py ├── urls.py └── wsgi.py -
cannot import name 'force_text' from 'django.utils.encoding'
Things suddenly started breaking when trying to use rest_framework_simplejwt. Now when I run python manage.py runserver I get the following: raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'force_text' from 'django.utils.encoding' (/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/encoding.py) Searching online, I found this post that seemed to work for some. However, when I tried that hack, I get the following exception: raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'FieldDoesNotExist' from 'django.db.models.fields' (/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/db/models/fields/__init__.py) This is my requirements.txt algoliasearch-django>=2.0,<3.0 django>=4.0.0,<4.1.0 djangorestframework djangorestframework-simplejwt pyyaml requests django-cors-headers black isort -
Django SecurityMiddleware and
what is the correct way to configure? settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware' .... ] so that you can pass parameters from one window to another from javascript parent.window.opener.postMessage -
File Size of attachment becoming 0 (compressed) in Python Django email automation i.e. file name appears, no content shows in attached pdf
The code to send email in Django is written like this in views.py file - it sends the pdf fine, if the file size is large (~3mb), but for smaller files (~1 or 2mb) it does not send the file (it appears as a zero byte file) in the email, and hence we cannot access it. The code is as belows - Please let me know if there is a way to avoid such a compression of file and send small files to. def addbeast(request): if request.method == 'POST': form = BeastForm(request.POST, request.FILES) # print("here") # print(form.cleaned_data['name']) if form.is_valid(): # print("here") # print(form.cleaned_data['media']) form.save() # media = Beast.objects.get(name = '') name = form.cleaned_data['name'] media = form.cleaned_data['media'] media.seek(0, os.SEEK_END) filesize = media.tell() print(filesize) subject = "NDA IS Attached" message = "NDA Attachment from " + name sender = "-----@gmail.com" cc_myself = True cc_mail = "----!!!!!!@gmail.com" recipients = ['9999999999@gmail.com'] if cc_myself: recipients.append(cc_mail) try: mail = EmailMessage(subject, message, sender, recipients) mail.attach(media.name, media.read(), media.content_type) mail.send() return HttpResponse("FORM SUBMISSION IS SUCCESSFUL") except: return HttpResponse('no success') else: form = BeastForm() return render(request, "post_list.html", { "form": form }) Please help with how the code can be made right, on printing the variable media, I get 'filename.pdf'. -
While importing the URL file from my app to the main URL file (Django)
#I am trying to import the URL file from my app to the main file# #main url file# from django.contrib import admin from django.urls import path,include from django.http import HttpResponse urlpatterns = [ path('admin/', admin.site.urls), path('',include ('base.links')) ] the error i am getting: cannot import name 'path' from partially initialized module 'base.links' (most likely due to a circular import) (C:\Users\Sam\Desktop\studybudy\base\links.py) #the url file in my app# from base.links import path from . import views urlpatterns = [ path(' ',views.home), path('room',views.room), ] #the views file in my app# from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('home123') def room(request): return HttpResponse('Room') -
Why do I always get a message that there are insufficient money, even though the amount I'm withdrawing is less than my balance?
I intended to show the user the message "insufficient balance" when the amount he wants to withdraw is larger than the available balance, but the message appears even when the amount he wants to withdraw is less. What's the problem here, exactly? def create_withdrawal_view(request): if request.method == 'POST': withdraw_form = InvestmentForm(request.POST) if withdraw_form.is_valid(): investment = withdraw_form.save(commit=False) if investment.amount > investment.balance: messages.success(request, 'insufficient funds') else: investment.balance -= investment.amount investment.save() messages.success(request, 'your Withdrawal is successfull') else: withdraw_form = InvestmentForm() context = {'withdraw_form': withdraw_form} return render(request, 'create-withdrawal.html', context) -
Is there a way to use files uploaded in django in the template?
I have a django model form where I uploaded images for my app. I am just storing them temporarily locally since its not a real project. The Admin looks like this I'm wondering if there is a way to use the images uploaded with each object in the template. I cant find any articles. How can I make a link to what images are associated with what models? -
How to add counter that increments after an object is created in Django?
I am making a simple list website that displays a list of movies I want to watch. So, basically, I use a form to add a movie to my list. Nothing fancy, but I want to display a count variable alongside each movie I add to my list from like 1-10 and I want it to increase/decrease based on if I delete/add a new movie. Where would I need to add this? I have separate views for my addition/deletion of movies (objects) -
Passing variables from HTML to Javascript file that uses addEventListener
I'm using Stripe to accept Apple pay payments (not super important here). I'm using Django. The code works fine for processing the payments, but I'm having trouble passing in a variable to my separate .js file. (amount to charge) from my HTML file to the Javascript file that actually processes the payments. home.html {% load static %} <!DOCTYPE html> <html> <head> import more scripts here <script src="https://js.stripe.com/v3/"></script> <script src="{% static 'interface/utils.js' %}" defer></script> <script src="{% static 'interface/apple-pay.js' %}" defer></script> </head> <body> <header class="text-center"> <div id="rectangle"></div> </header> <section> <div class="text-center"> <div class="container container--narrow"> <script>amount=parseInt("{{event.price}}")</script> <div id="payment-request-button"> <!-- A Stripe Element will be inserted here if the browser supports this type of payment method. --> </div> </div> </div> </section> </body> </html> The Javascript file that gets called to process the payment: apple-pay.js document.addEventListener('DOMContentLoaded', async () => { const stripe = Stripe('pk_test_testkey'); const paymentRequest = stripe.paymentRequest() ({ currency: 'usd', country: 'US', requestPayerName: true, requestPayerEmail: true, total: { label: 'Test payment', amount: amount, //trying to pass the variable in here } }); // Other functions that get called go here }); The error I see in the console is that 'total' in the API call is no longer an object. Console.log(typeof amount) returns a … -
I get an error TypeError at /brand/5 get() missing 2 required positional arguments: 'self' and 'request'
Everything worked well until I made a brand details page for my online store. I never encountered this error, and it looks like there is no solution availble for my case. I think its unique for every developer. TypeError at /brand/5 get() missing 2 required positional arguments: 'self' and 'request' Here is my code: views.py from django.shortcuts import render, get_object_or_404 from .models import Product,ProductCategory, Brand # Create your views here. from django.views import generic class Brands(generic.ListView): model = Brand template_name = 'productcatalog/brands.html' def get_context_data(self, **kwargs): context = super(Brand, self).get_context_data(**kwargs) brands = Brand.objects.all() context['brands']=brands return context class Brand(generic.DetailView): model = Brand tempal_name = 'productcatalog/brand_details.html' def get_context_data(self, **kwargs): context = super(Brand, self).get_context_data(**kwargs) brand = get_object_or_404(Brand, id=self.kwargs['pk']) context['brand']=brand return context models.py class Brand(models.Model): name = models.CharField(max_length=300,blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_catalog') Can anyone assist? Thank you in advance! -
How and Where to put 10GB of content for a website?
I am making a Django website for our college's debating society. They have approx. 30GB worth of video content. Where should I store it in Database (PostgreSQL is being used) during development and when in production. Does it cost to have a certain amount of GB content when in production? If there is another way for the same, please feel free to share that as well! -
Django 4.0.5: How to properly link static files into templates
I'm following the CS50W course, and I noticed a weird behavior when going through the Django lecture. In summary, I was getting a 404 error when loading the styles.css file on one of the apps. After checking the lecture source code, the main difference was that the lecture used the following to define STATIC_URL: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = '/static/' And noticed that even Django's documentation defines STATIC_URL as STATIC_URL = 'static/', and somehow, adding that slash at the beginning fixes the 404 issues. Could someone explain to me why that is? For reference, this is the project structure I have (the issue is within the app called newyear): . ├── db.sqlite3 ├── manage.py ├── myapp │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── admin.cpython-38.pyc │ │ ├── apps.cpython-38.pyc │ │ ├── models.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── views.cpython-38.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-38.pyc │ ├── models.py │ ├── templates │ │ └── myapp │ │ ├── greet.html │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py ├── … -
Django - API links shown as serializers instead
My API looks something liks this { "id": 7, "url": "http://127.0.0.1:8000/workers/7/", "first_name": "ellie", "last_name": "hodjayev", "email": "zenmyx@gmail.com", "phone_number": 502461700, "hire_date": "2022-06-18", "job": 1, "speciality": 5, "salary": 17000, "commission_pct": 0, "manager_id": 0, "department_id": 0 } 'job' and 'speciality' should be shown as links since they're configured to be serializers.hyperlinkedmodeserializers but instead we're seeing a serial number.. from here it looks everything is configured correctly. serialize.py from rest_framework import serializers from .models import Worker, Speciality, Job class WorkerSerializer(serializers.ModelSerializer): class Meta: model = Worker fields = ['id', 'url', 'first_name', 'last_name', 'email', 'phone_number', 'hire_date', 'job', 'speciality', 'salary', 'commission_pct', 'manager_id', 'department_id'] class SpecialitySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Speciality fields = ['id', 'url', 'speciality'] class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Job fields = ['id', 'url', 'job'] -
Como puedo poner mi moneda local en Django?
Tengo un problema con un proyecto , con un amigo sacamos codigo de otros proyectos y resulta que el formato de moneda es el de la india , alguien sabe como cambiar el tipo de moneda por otra? el problema -
Problem with permutations function in Django, how to make it work?
Hi i have problem with large amount of data while doing permutations teamA = [tournament.p1, tournament.p2, tournament.p3] teamB = [player.op1, player.op2, player.op3] for perm in permutations(teamA): result.append(list(zip(perm, teamB))) for pairing in result: score = [] total = 0 for i in pairing: if i == (tournament.p1, player.op1): i = player.p11 elif i == (tournament.p1, player.op2): i = player.p12 elif i == (tournament.p1, player.op3): i = player.p13 elif i == (tournament.p2, player.op1): i = player.p21 elif i == (tournament.p2, player.op2): i = player.p22 elif i == (tournament.p2, player.op3): i = player.p23 elif i == (tournament.p3, player.op1): i = player.p31 elif i == (tournament.p3, player.op2): i = player.p32 elif i == (tournament.p3, player.op3): i = player.p33 points.append(i) for s in points: if s == -3: mp = 1 elif s == -2: mp = 4 elif s == -1: mp = 7 elif s == 1: mp = 13 elif s == 2: mp = 16 elif s == 3: mp = 19 else: mp = 10 score.append(mp) total += mp data_list.append([pairing, score, total]) This is code i run for sets od pairs in teams of 3, but if i want to do teams of 8, and permutations of 8 where teamA … -
Django search returning Exception Value: object of type 'method' has no len()
Pretty new to Django Rest Framework and I'm not quite sure how to debug this error at the moment. When I set a breakpoint in the view search view. I see all my products in results <bound method QuerySet.distinct of <ProductQuerySet [<Product: Product object (4)>, <Product: Product object (8)>, <Product: Product object (9)>, <Product: Product object (10)>]>> Pagination is set in settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "api.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticatedOrReadOnly", # GET for everyone, all other calls need to be authenticated ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10, } Search view from rest_framework import generics from products.models import Product from products.serializers import ProductSerializer class SearchListView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) q = self.request.GET.get("q") results = Product.objects.none() if q is not None: user = None if self.request.user.is_authenticated: user = self.request.user results = qs.search(q, user=user) return results Products view from rest_framework import generics, mixins from django.shortcuts import get_object_or_404 from api.mixins import StaffEditorPermissionMixin, UserQuerySetMixin from .models import Product from .serializers import ProductSerializer class ProductListCreateAPIView( UserQuerySetMixin, StaffEditorPermissionMixin, generics.ListCreateAPIView ): queryset = Product.objects.all() serializer_class = ProductSerializer def perform_create(self, serializer): title = serializer.validated_data.get("title") content = serializer.validated_data.get("content") or None if content is None: content = title serializer.save(user=self.request.user, …