Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. Star rating multiple form displayed in a grid view not working
I've got a little problem. I have a page that is used to rate ski resorts. They are displayed in a grid view and each resort has a star rating form beneath. The problem is that only the first item in the grid can be rated. I tried to assign each form an unique id but that didn't work. Here is the code: class AddRatingForm(forms.ModelForm): class Meta: model = ResortUserRating fields = '__all__' widgets = { 'resort_rating': forms.RadioSelect() } def __init__(self, pk, *args, **kwargs): super(AddRatingForm, self).__init__(*args, **kwargs) self.pk = pk self.fields['user'].initial = self.pk def clean(self): return self.cleaned_data {% for resort in dashboard_resorts %} <div class = "grid-item"> {% if resort.img %} <img class="card-img-top" src="{{resort.img.url}}" alt ="Card image cap" height="300px" width="380px"> {% endif %} <p> <b>{{resort.name|upper}} </b></p> <p> <b>{{resort.id|upper}} </b></p> <form method="post" action = "{% url 'aplicatie2:rating' %}"> {% csrf_token %} <input type = "hidden" name = "user" value = "{{user.id}}"> <input type = "hidden" name = "resorts" value = " {{resort.id}}"> <div class="rate"> <input type="radio" name="resort_rating" id="rating1" value="1" required /><label for="rating1" title="1"> </label> <input type="radio" name="resort_rating" id="rating2" value="2" required /><label for="rating2" title="2"> </label> <input type="radio" name="resort_rating" id="rating3" value="3" required /><label for="rating3" title="3"> </label> <input type="radio" name="resort_rating" id="rating4" value="4" required /><label … -
django submit multiple forms
have concocted the following so far. pretty sure its sloppy code, but its meant for some crude maintenance and seems to work up to the point i would like it to work. point is i get a long list of forms, i can use Ajax to select them them all or assign them all to the category all at once, that is exactly what i want. what i can not figure out however is to submit all these forms in one go, the code as is works that i can submit 1. but just like the select all and categorize all code, after selecting those i also would like to SUBMIT ALL <script language="JavaScript"> function toggle(source) { checkboxes = document.getElementsByName('blockbutton'); for(var i=0, n=checkboxes.length;i<n;i++) { checkboxes[i].checked = source.checked; } } </script> <script language="javascript"> function setDropDown() { var index_name = document.getElementsByName('ForceSelection')[0].selectedIndex; var others = document.getElementsByName('Qualifications'); for (i = 0; i < others.length; i++) others[i].selectedIndex = index_name; } </script> <input type="checkbox" onClick="toggle(this)" /> Toggle All<br/> <select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();"> <option value="" selected="selected">Select Category</option> {% for category in categories %} <optgroup label="{{ category.name }}"> {% for item in category.subcategory_set.all %} <option val="{{ item.name }}"> {{ item.name }} </option> {% endfor %} </optgroup> {% … -
how to add slug argument to url in django?
i want to add slug in url using django like this <a href="{% url 'tutorials:tutorial' topic.tutorial_category.slug topic.tutorial_topic_category.slug topic.slug %} </a> i dont really know how to pass in triple slug in the url for example: i want to access the programming > html > introduction-to-html like this http://127.0.0.1:8000/tutorial/programming/html/introduction-to-html error Reverse for 'tutorial' with arguments '('', 'html', 'introduction-to-html')' not found. 1 pattern(s) tried: ['tutorial/(?P<main_category_slug>[^/]+)/(?P<topic_category_slug>[^/]+)/(?P<tutorial_slug>[^/]+)$'] topic.html {% for topic in topic %} <a href="{% url 'tutorials:tutorial' topic.tutorial_category.slug topic.tutorial_topic_category.slug topic.slug %}">{{topic.title}} - Start Now</a> {% endfor %} views.py def tutorial(request, main_category_slug, topic_category_slug, tutorial_slug): tutorial_category = TutorialCategory.objects.get(slug=main_category_slug) tutorial_topic_category = TutorialTopicCategory.objects.get(slug=topic_category_slug) topic = Topic.objects.filter(tutorial_topic_category=tutorial_topic_category) tutorial = Topic.objects.get(slug=tutorial_slug) # Getting all topics context = { 'topic': topic, 'tutorial':tutotial, } return render(request, 'tutorials/tutorial.html', context) urls.py path("<slug>", views.tutorial_topic_category, name='tutorial-topic-category'), path("<slug:main_category_slug>/<slug:topic_category_slug>", views.topic, name='topic'), path("<main_category_slug>/<topic_category_slug>/<tutorial_slug>", views.tutorial, name='tutorial'), `` -
How to quickly reset Django DB after changes?
I'm often experimenting around creating different models, changing relations and so forth. This usually happens when starting a new project. At this phase I do not want to create any migrations but instead just get the thing up and running. So i very often do this: rm db.sqlite3 rm -r project/apps/app/migrations/* python manage.py makemigrations app python manage.py migrate app python manage.py createsuperuser bla bla Is there any way to have this "reset" function more quickly? I frustratingly found out, that django does not allow superusers to be created by a shell script. Is there any way to purge the db without removing the users? How do you do this? -
How to send data with Url Django
I want to send {{order.id}}, but getting error like pictuce in bellow, please helping me to solve problem Image Error View.py def Detail_pem(request, idor): print(idor) return render(request, 'store/detail.html' ) pemby.html <!-- <a href="{% url 'Detail_pem' %}"><button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> </a> --> <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> <a href="{% url 'Detail_pem' idor=order.id %}"></a> </td> </tr> {% endfor %} </tbody> </table> </div> <!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> --> <script> var id_order = document.getElementsByClassName('id_order') for (i = 0; i < id_order.length; i++) { id_order[i].addEventListener('click', function(){ var orid = this.dataset.product var ornm = this.dataset.act console.log('orid :', orid) console.log('ornm :', ornm) window.location.href = "{% url 'Detail_pem' %}" }) } urls.py path('Detail_pem/<idor>', Detail_pem, name='Detail_pem'), -
Password encryption in Django's model
I hope you are doing fine, I am currently working on a Django project and it's my first one so I have found lots of problems which I am fixing one by one, but I've really got stuck with this one. It's about Django's password encryption in the database records, it simply doesn't encrypt the password for all the users except the admin. I hope that u can help me and thank you for your time :D models.py from django.db import models from django.db.models import Model from passlib.hash import pbkdf2_sha256 from django.utils.translation import gettext_lazy as _ from .manager import * # Create your models here. class User(Model): id = models.AutoField(primary_key=True, unique=True) email = models.EmailField( _("email"),max_length = 254 ,null=False) password = models.CharField(max_length= 255, null=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects=CustomUserManager() USERNAME_FIELD="email" REQUIRED_FIELDS= ["password"] class Meta: abstract = True verbose_name = _("user") verbose_name_plural = _("users") def __str__(self): return self.first_name + " " + self.last_name def getID(self): return self.id def getEmail(self): return self.email def getPass(self): return self.password def getFirstName(self): return self.first_name def getLastName(self): return self.last_name def checkIfSuperUser(self): return self.is_superuser def checkIfStaff(self): return self.is_staff def checkIfActif(self): return self.is_active def verify_password(self, raw_password): return pbkdf2_sha256.verify(raw_password, self.password) … -
AttributeError: module 'collections' has no attribute 'Iterator' python 3.10 django 2.0
Hello its a clone project but when ı try "python manage.py makemigrations" ım getting this error how can ı fix it? requirements django==2.0 django-ckeditor==5.4.0 django-cleanup==2.1.0 django-crispy-forms==1.7.2 django-js-asset==1.0.0 this error -
Convert a nested dictionary into list of tuples like (date,value)
I have a dict like this: {'2022':{'01':{'20':55,'25':80,'30':70},'08':{'04':14,'10':18}}} and I want convert it to list of tuples or lists like this: [("2022-01-20",55),("2022-01-25",80),("2022-01-30",70),("2022-08-04",14),...] The keys of dict are as year,month and day In other words, the keys must be converted to date -
I want to get different id of multiple select boxes after click on add button in ajax and using POST method send those value in django
When I click on add, then it will be adding and I'm getting same values of select and input boxes but I want the different id's every time for ajax call and change the value dynamically and send those values in django. I have tried 1 solution but after applying that my add functionality stop working. I have tried multiple solution and have been working on it for 2-3 weeks, but I didn't get what I want. $(document).ready(function() { var maxField = 10; //Input fields increment limitation var addButton = $('.add_button'); //Add button selector var wrapper = $('.field_wrapper'); //Input field wrapper var fieldHTML = '<section class="row"><div class="col-md-3 mt-2"><label for="CustomerCity" class="">Select Product</label><select class="form-control selectitem" name="item[]" id="selectitem" required><option selected>Select Item</option></select></div><div class="col-md-2 mt-2"><label for="CustomerCity" class="">Unit Price</label><input name="customer_city" id="customer_city" type="text" class="form-control" value="" placeholder="Unit Price" required></div><div class="col-md-2 mt-2"><label for="CustomerCity" class="">Quantity</label><input name="customer_city" id="customer_city" type="text" class="form-control" value="" placeholder="Quantity" required></div><div class="col-md-2 mt-2"><label for="CustomerCity" class="">Tax Amount</label><input name="customer_city" id="customer_city" type="text" class="form-control" value="" placeholder="Tax Amount" required></div><div class="col-md-2 mt-2"><label for="CustomerCity" class="">Extended Total</label><input name="customer_city" id="customer_city" type="text" class="form-control" value="" placeholder="Extended Total" required></div><div class="col-md-1 mt-2"><a href="javascript:void(0);" class="remove_button btn btn-danger mt-4 p-2 form-control">Delete</a></div></section>'; //New input field html var x = 1; //Initial field counter is 1 //Once add button is clicked $(addButton).click(function() { //Check maximum number … -
How to limit the number of responses to my for loop to 3 in Django Templates?
In my current Django template I have two models in use, which are defined in my views.py as: 'tasks' : IndividualTask.objects.all(), 'updates' : TaskUpdate.objects.all(), I have set up signals so that when there is an update to a task, an update is created. Currently, I iterate through each task, then each of their updates and pull out the relevant updates for each task, as shown below. {% for task in tasks %} {% for update in updates %} {% if task.id == update.task.id %} {{ update.update }} {% endif %} {% endfor %} {% endfor %} However, I would like to limit the number of updates I show to three. I have tried using slice, show below, but this limits all updates to the top 3 of all updates as opposed to the top 3 of each individual task's updates. {% for task in tasks %} {% for update in updates|slice:":3" %} {% if task.id == update.task.id %} {{ update.update }} {% endif %} {% endfor %} {% endfor %} I would be grateful for any advice as to how I can limit the number of updates shown for each task to 3 please? -
How can I access database of Worldpress website in Django Application?
I have multiple blogging websites which are made in WordPress and hosted on hostinger. I want to access my WordPress database so that I can keep a record of when I have added articles on which website. How can I do that? -
How to use toastr in django to display messages
So django has built-in messages framework to display appropriate messages. I'm trying to display these messages as a toast notification rather than the default list as shown in the documentation or as a div message like those in bootstrap for which I'm trying to use toastr. I've tried a couple of things but nothing seems to work. I've also gone through this question but I couldn't figure out where to import the messages.html code. Below is the base.html <!DOCTYPE html> <html lang="en"> {% load static %} <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"> <title>Kaushal Sharma</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.css" integrity="sha512-3pIirOrwegjM6erE5gPSwkUzO+3cTjpnV9lexlNZqvupR64iZBnOOTiiLPb9M36zpMScbmUNIcHUqKD47M719g==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <style> html { scroll-behavior: smooth; } </style> </head> <body> {% block content %} {% endblock %} <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js" integrity="sha512-VEd+nq25CkR676O+pLBnDW09R7VQX9Mdiij052gVCp5yVH3jGtH70Ho/UUv4mJDsEdTvqRCFZg0NKGiojGnUCw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> {% block scripts %} {% endblock scripts %} </body> </html> I have a home.html which extends the base.html and includes all my other html pages like below {% extends 'base.html' %} {% block content %} <!-- include pages --> {% endblock %} {% block scripts %} {% include 'messages.html' %} {% endblock scripts %} and here is my messages.html {% block scripts %} {% if messages %} {% for message … -
Django error "Please correct the error below"
Please guide me as I have already gone through most of the posts submitted here and I am still not able to find a solution. I have created a custom user model and manager in Django. Also created a change form and creation form. I am able to create a user using the manage.py shell but when I try to create a user using the Django admin interface I am getting an error "Please correct the error below" but this error does not provide any error information. There are many questions her asked about this but none of them are able to resolve my issue. Here is my user manager class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name,contact_no, password=None,is_staff=False, is_admin=False, is_active=True): if not email: raise ValueError('Users must have an email address') if not password: raise ValueError('Users must have a password') if not first_name: raise ValueError('Users must have a First Name') if not last_name: raise ValueError('Users must have a Last Name') if not contact_no: raise ValueError('Users must have a Contact No') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.first_name = first_name user.last_name = last_name user.contact_no = contact_no user.active = is_active user.staff = is_staff user.admin = is_admin user.save(using=self._db) return user def create_staffuser(self, email, first_name, … -
How i can to pass parameter to model method in django template?
Hi everyone i have a question about django template and models method include function parameter. example code in models.py class Item(models.Model): name = models.CharField(max_length=30) price = models.IntegerField() owner = models.ForeignKey('User',on_delete=models.CASCADE) def get_something(self,requestuser): # <-- pass request.user here // calculate something here return "output" in views.py def assets(request): return render(request, 'index.html', {'items':Item.objects.filter(owner=request.user)}) in template {% for item in items %} <h1>{{item.name}}</h1> <h2>{{item.price}}</h2> <h2>{{item.get_something(request.user) }}</h2> <!-- How to inject request.user to get_something Here --> {% endfor %} -
Form post data is not passing back to html file in django
I am creating a Django app and I am trying to show the data received from a POST request on an HTML table. I have used JavaScript fetch API to submit the form and fetch the data in views.py . I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table. Without the fetch API submit, everything is working fine as per my need. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong. views.py def home(request): if request.method=="POST": options_value=request.POST['dropdown_val'] value=request.POST['val'] print(options_value,value) return render(request, 'index.html',context) index.html <form method="POST" action="" id="form"> {% csrf_token %} <div class="d-flex justify-content-center" style="margin-top: 6rem"> <div class="dropdown" style="display: flex" id="dropdown"> <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> </div> <div class="col-3 bg-light" style="margin-left: 2rem"> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> </div> <div style="margin-left: 2rem"> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </div> </div> </form> <table style="display: table" id="table"> <tbody> <tr> … -
type object is not subscriptable - I understand the error, but I don't know why it happens
Disclaimer: this code worked on python 2.7, I just migrated to 3.7 :) The error that's happening does happen in Django 1.11 I have this line of code which throws me the 'type object is not subscriptable' error: from ..settings import Settings skinurl = join(url_base, 'css/skins/skin-%s.min.css' % Settings['THEME.SKIN']) The settings class is this: class Settings(SettingsBase): store = DEFAULT_SETTINGS __metaclass__ = Meta def __getitem__(self, key): print(self.store['THEME.SKIN']) return self.iget(key) in DEFAULT_SETTINGS, I have THEME.SKIN: 'THEME': { 'SKIN': 'green', }, I have an idea why it might happen - that print in getitem doesn't return anything. If I change it to print(self.store['THEME']['SKIN']) it does, though. If I also change that join call to this skinurl = join(url_base, 'css/skins/skin-%s.min.css' % Settings['THEME']['SKIN']) I still get type object is not subscriptable. What is happening here and how can I fix it? -
Setup Django on Apache server
I need help with install #django on Apache using wsgi.py Thanks in advanceenter image description here -
Django initialization stuck at import netrc
My django app starts very slowly. I ran python -v manage.py check and it stucks at line import 'netrc' # <_frozen_importlib_external.SourceFileLoader object at 0x7efff40f3d30> I found this related question : Django "Performing System Checks" is running very slow Here it says he removed the elastic beanstalk urls from ALLOWED_HOSTS and it fixed. I did that too but my app still stucks at that import statement. What else can cause that? -
DRF add computed field based on requesting user
I have a model which has specific many to many fields to the user model. Now, to prevent information leaking, I do not want to return the whole related field though the rest framework. But, I want to create some kind of computed field, such that it return True if the requesting user is in the related field, and False otherwise. Is there a way to make this work? For example, as it stands now, the rest framework will list the users for "user_like" and "user_bookmark", which I dont want to happen, hence I want to exclude them from the serialized. But I want to have a field, say, named is_liked, which will be true if request.user is in user_like, and false otherwise. My current setup: model class Post(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='dream_photos') description = models.TextField(max_length=500) date_added = models.DateTimeField(auto_now_add=True) user_like = models.ManyToManyField(User, related_name='likes', blank=True) user_bookmark = models.ManyToManyField( User, related_name='bookmarks', blank=True) total_likes = models.PositiveIntegerField(db_index=True, default=0) tags = TaggableManager() serialiser class PostSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Dream fields = ('title','user', 'image','description','date_added', 'tags', 'total_likes' ) views class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.prefetch_related('user').all() serializer_class = PostSerializer permission_classes = [permissions.IsAuthenticated] @action(detail=False, methods=['get'], url_path='current-profile', url_name='current-profile') def current_user_posts(self, … -
How can I get Loged in user details from different Mdels as arguments
I am trying to integrate a payment system in my Django project and I models for profile, and submitted. The issue is that I want a situation where when a user clicks on pay button the system should check whether he/she has submitted application and if so; grab the username, email, phone, amount and pass them as arguments into my process_payment view where the payment is going to be done. here is code for Profile model: class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=30, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) nation = models.CharField(max_length=255, choices=NATION, blank=True, null=True) state = models.CharField(max_length=20, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=16, null=True) image = models.ImageField(default='avatar.jpg', upload_to ='profile_images') here is code for Scholarship model: class Submitted(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) confirm = models.BooleanField() approved = models.CharField(max_length=20, null=True) date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.application == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.applicant def __str__(self): return f'Application Number: {self.application}-{self.applicant}' Here is my view code: @login_required(login_url='user-login') def scholarship_detail(request, pk): data = Scholarship.objects.get(id=pk) if request.method=='POST': applicant= request.user email = 'henry@gmail.com' amount = 2 phone = 8034567 return redirect(str(process_payment(applicant,email,amount,phone))) … -
how to filter the model we use in model.ForeignKey in django
I have model in django that has some instaces in itself: class Account(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=50, unique=True) #some instances... is_agent = models.BooleanField(default=False) agent = models.ForeignKey("self", verbose_name=('agent'), on_delete=models.SET_NULL, blank=True, null=True) i want to pass only Accounts objects that is_agent set to True in my model.ForeignKey() method. i don't want to use inheritence for some reasons. -
getting error while I run this code(django,rest_framework)
I am learning django rest_framework , But here's the problem, I get the following error. What am I doing wrong?I've done a lot of research on trying to resolve the jsondecodeerror. However, I'm not finding a solution. import requests import json URL = "http://127.0.0.1:8000/studentapi/" def get_data(id=None): data = {} if id is not None: data = {'id':id} json_data= json.dumps(data) r= requests.get(url = URL , data = json_data) data = r.json() print(data) get_data()``` error--- python myapp.py Traceback (most recent call last): File "C:\Users\P.ARYAPRAKASH\Documents\Djangovs\fun_api_view\myapp.py", line 15, in <module> get_data() File "C:\Users\P.ARYAPRAKASH\Documents\Djangovs\fun_api_view\myapp.py", line 12, in get_data data = r.json() File "C:\Users\P.ARYAPRAKASH\AppData\Roaming\Python\Python39\site-packages\requests\models.py", line 910, in json return complexjson.loads(self.text, **kwargs) File "C:\Python39\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Python39\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python39\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) -
Django RestFramework - Test View failing with 400
right now I'm trying to create a simple test-file for a ListCreateAPIView inside my views.py: views.py: class AuthorListCreateView(ListCreateAPIView): queryset = Author.objects.all() serializer_class = AuthorSerializer serializers.py: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' urls.py: urlpatterns = [ path('author/', AuthorListCreateView.as_view(), name='author-list'), ] models.py from django.contrib.auth import get_user_model USER = get_user_model() class BaseModel(models.Model): id = models.BigAutoField(primary_key=True, editable=False, unique=True) created_by = models.ForeignKey(USER, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True get_latest_by = 'created_at' class Author(BaseModel): class Gender(models.TextChoices): NO = 'NO', 'No gender chosen' DIVERSE = 'DI', 'Diverse' FEMALE = 'FE', 'Female' MALE = 'MA', 'Male' first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) born = models.DateField(null=False, blank=False) died = models.DateField(null=True, blank=True) passed = models.BooleanField(default=False) gender = models.CharField(max_length=2, choices=Gender.choices, default=Gender.NO) slug = models.SlugField(null=False, blank=False, unique=True) class Meta: ordering = ['last_name', 'first_name'] constraints = [ models.UniqueConstraint(fields=['last_name', 'first_name'], name='unique_name_constraint'), ] indexes = [ models.Index(fields=['last_name', 'first_name'], name='index_unique_name'), ] verbose_name = 'Author' verbose_name_plural = 'Authors' def __str__(self) -> str: return f'{self.first_name} {self.last_name}' def save(self, *args, **kwargs): self.passed = True if self.died is not None else False self.slug = slugify(f'{self.last_name}-{self.first_name}') if not self.slug else self.slug super(Author, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('author-detail', kwargs={'slug': self.slug}) def clean(self): if self.died is not None … -
Django - TypeError at /api/v1/latest-products/ FieldFile.save() got an unexpected keyword argument 'quality'
I don't know why, but every time I try to go to the API URL, I keep getting this error message, I think the problem is in one of these modules, but I don't know what to change. models.py module found in the product package from io import BytesIO from PIL import Image from django.core.files import File from django.db import models class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.slug}' class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.category.slug}/{self.slug}' def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def get_thumbnail(self): if self.thumbnail: return 'http://127.0.0.1:8000' + self.thumbnail.url else: if self.image: self.thumbnail = self.make_thumbnail(self.image) self.save() return 'http://127.0.0.1:8000' + self.thumbnail.url else: return '' def make_thumbnail(self, image, size=(300,200)): img = Image.open(image) img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() image.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail I think the problem is found in the make_thumbail function or the get_thumbnail function? serializers.py module found in … -
Gunicorn is throwing Out of Memory with max request and max requests jitter
Gunicorn is throwing Out of Memory I have tried to add max request and max requests jitter but still getting Out of Memory. Gunicorn is being controlled by supervisor exec gunicorn myproject.wsgi:application --bind unix:/webapps/run/myproject/gunicorn.sock --max-requests 500 --max-requests-jitter 50 --workers 3 --timeout 300 --user=root --group=webapps I have tried to check the gunicorn process ID it consumes 95% of memory out of 20GB and started 18 hours ago what I am doing wrong. Any help appreciated