Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest api __init__() takes 1 positional argument but 2 were given
api link is not working. show this error "init() takes 1 positional argument but 2 were given" Please help me. I am beginner in django trying to creat blog api model.py: class Blog(models.Model): blog_id = models.AutoField(primary_key=True, editable=False) title = models.CharField(max_length=100, null=False) description = models.TextField(null=False) image = models.ImageField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title view.py class BlogViewSet(viewsets.ModelViewSet): serializer_class = BlogSerializer permission_classes = IsAuthenticated queryset = Blog.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) serializer.py: class BlogSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField(read_only=True) class Meta: model = Blog fields = '__all__' urls.py from django.urls import path from rest_framework.routers import DefaultRouter from . import views from rest_framework_simplejwt.views import ( TokenObtainPairView, ) router = DefaultRouter() router.register('blogs', views.BlogViewSet, basename='blogs') urlpatterns = [ path('users/login', views.MyTokenObtainPairView.as_view()), path('users/register', views.register_user, name='register'), path('users/profile', views.get_user_profile, name='profile'), path('blogs/', views.BlogViewSet, name='blogs'), path('avatar/', views.get_avatar, name='avatar'), ] so when i perform a get request to "http://localhost:8000/api/blogs/" it shows this error: TypeError at /api/blogs/ __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://localhost:8000/api/blogs/ Django Version: 3.2.4 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: D:\work environment\Django_Api\codersavvy\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response Python Executable: D:\work environment\Django_Api\codersavvy\Scripts\python.exe Python Version: 3.9.2 Python … -
Django rest framework: Id not returned when adding a new user
I am new to the Django rest framework. I am trying to register a new crew member(read "new user") and get their ID. my views.py file for registration of crew member def register_crew(request): fields = ('id','phone','name','email','user_type','is_verified','is_active','password') serializer = UserSerializer(data=request.data,fields=fields) if serializer.is_valid(): serializer.create_crew() content = { "status": True, "Http_response": status.HTTP_200_OK, "message": 'crew account created', "data": serializer.data } else: content = { "status": False, "Http_response": status.HTTP_400_BAD_REQUEST, "message": 'input errors', "errors": serializer.errors } return Response(content) my create_crew serializer def create_crew(self): reg = User( phone=self.validated_data['phone'], ) reg.email = self.validated_data['email'] reg.name = self.validated_data['name'] reg.user_type = self.validated_data['user_type'] reg.set_password(self.validated_data['password']) reg.save() return reg I am able to register the user but the serializer does not return the id of the object. Even though when I list the users the id is visible. -
ValueError: Field 'id' expected a number but got 'gaming-peripherals'
I'm building an e-commerce (like) project. While running the program, from Homepage, if we select a product I got hit by this error, instead of showing that product details. Now I can't figure out how to fix this please help me to fix it.enter image description here Here's my Models.py class Category(models.Model): name=models.CharField(max_length=250,unique=True) slug=models.SlugField(max_length=250,unique=True) desc=models.TextField(blank=True) image=models.ImageField(upload_to='category',blank=True) class Meta: ordering=('name',) verbose_name='category' verbose_name_plural='categories' # for menu linking (url) def get_url(self): return reverse("ecommerce_app:products_by_category",args=[self.slug]) def __str__(self): return '{}'.format(self.name) class Product(models.Model): name=models.CharField(max_length=250,unique=True) slug = models.SlugField(max_length=250, unique=True) desc = models.TextField(blank=True) image = models.ImageField(upload_to='product', blank=True) category=models.ForeignKey(Category,on_delete=models.CASCADE) price=models.DecimalField(max_digits=10,decimal_places=2) stock=models.IntegerField() available=models.BooleanField(default=True) created=models.DateTimeField(auto_now=True) updated=models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' # for url def get_url(self): return reverse("ecommerce_app:ProdCatDetails",args=[self.category.slug,self.slug]) def __str__(self): return '{}'.format(self.name) Her's my Urls.py from django.urls import path from . import views app_name='ecommerce_app' urlpatterns=[ path('',views.allProdCat,name='allProdCat'), # for special urls for Category path('<slug:c_slug>/',views.allProdCat,name='products_by_category'), # for special urls for Product Details path('<slug:c_slug>/<slug:product_slug>/',views.ProdCatDetails,name='ProdCatDetails'), ] Here's my Views.py from django.http import HttpResponse from .models import Category,Product from django.shortcuts import render,get_object_or_404 # Create your views here. def home(request): return HttpResponse("Hello") def allProdCat(request,c_slug=None): c_page=None products=None if c_slug!=None: c_page=get_object_or_404(Category,slug=c_slug) products=Product.objects.all().filter(category=c_page,available=True) else: products=Product.objects.all().filter(available=True) return render(request,'category.html',{'category':c_page,'products':products}) # For product details def ProdCatDetails(request,c_slug,product_slug): try: product=Product.objects.get(category__product=c_slug,slug=product_slug) except Exception as e: raise e return render(request,'product.htmal',{'product':product}) -
Why doesn't the "Order details" button open?
Created a personal account in the online store made in Django. It looks like this But for some reason the button "Order details" is not pressed. It should look like this Personal account template: profile.html {% extends 'base.html' %} {% block content %} <h3 class="mt-3 mb-3">Заказы пользователя {{ request.user.username }}</h3> {% if not orders.count %} <div class="col-md-12" style="margin-top: 300px; margin-bottom: 300px;"> <h3>У вас ещё нет заказов. <a href="{% url 'base' %}">Начните делать покупки</a></h3> </div> {% else %} <div class="col-md-12" style="margin-bottom: 250px; margin-top: 250px;"> <table class="table"> <thead> <th scope="col">Номер</th> <th scope="col">Статус</th> <th scope="col">Сумма</th> <th scope="col">Товар</th> <th scope="col">Дополнительно</th> </thead> <tbody> {% for order in orders %} <tr> <th scope="row">{{ order.id }}</th> <td>{{ order.get_status_display }}</td> <td>{{ order.cart.final_price }} руб.</td> <td> {% for item in order.cart.products.all %} <li>{{ item.products.title }} x {{ item.qty }}</li> {% endfor %} </ul> </td> <td> <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#exampleModal-{{ order.id }}">Подробнее о заказе </button> <div class="modal fade" id="exampleModal-{{ order.id }}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Детализация заказа</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h4 class="text-center">Товар</h4> <table class="table"> <thead> <tr> <th> scope="col">Наименование</th> <th> scope="col">Изображение</th> <th> scope="col">Цена</th> <th> scope="col">Кол-во</th> <th> scope="col">Общая цена</th> </tr> </thead> <tbody> {% for item … -
How to pass array from javascript to views.py and views.py to javascript in django
Currently I am working on sudoku solver project in django which takes array from javascript and that array should be passed to the function in views.py for processing and then it again should be passed back to javascript to show the final output. So how to transfer this arrays between two different Programming languages... -
Pandas export to excel not working after deployment [closed]
I have created a api in django in which I am writing a file by pandas and the end used df.to_excel function is used .It works fine on local. But after deployment on apache it does not write file . -
Django Redirect with non-default table
In my Django project, I have a generic view. It has a single select form in which the user can choose a formset from a list of formsets to load. Then, a POST request is sent to the server, requesting the new formset. The view is reloaded with the new formset while remaining on the same URL. Here's an example: Assume there are two tables: default_formset and formset_2 If I am making updates on my default_formset the redirect works perfectly. The issue I am having is with 'updating' non-default formsets like formset_2. When an update is made on formset_2 on redirect it will load up the default_formset rather than loading up formset_2 In foo.py: def generic_view(request): #Here, the user's input determines what formset is rendered formset_names = SingleSelectForm(formsets, 'formset_name', request.POST) #This is the formset which is rendered formset_selected = request.POST.get('formset_name', 'default_formset') ''' ''' Forms are initialized ''' ''' if request.POST: if 'formset_name' in request.POST: formset = the_formset(form_kwargs=empty_forms, initial=initial_values) if 'update' in request.POST: if formset.is_valid(): for form in formset: if form.has_changed(): # Do some mysql stuff return HttpResponseRedirect("/foo/") In urls.py: from website.foo import foo urlpatterns = [ path('foo/', foo.generic_view, name='generic_view'), ] If a user updated a row in formset_2, is it … -
Gallery with different paths, depending on the model name
I need to store images in different paths, depending on the model name. To do that, i define a function which creates the correct path according to the model name, and we can pass that function to the upload_to setting of the ImageField: from django.db import models def get_upload_path(instance, filename): model = instance.album.model.__class__._meta name = model.verbose_name_plural.replace(' ', '_') return f'{name}/images/{filename}' class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Image(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to=get_upload_path) default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=255) album = models.OneToOneField(ImageAlbum, related_name='model', on_delete=models.CASCADE) class BlogPost(models.Model): name = models.CharField(max_length=255) author = models.CharField(max_length=255) album = models.OneToOneField(ImageAlbum, related_name='model', on_delete=models.CASCADE) But when there are a few models with same related_name associated OneToOne with Album, an error occurs. I'm making a gallery based on this tutorial https://medium.com/ibisdev/upload-multiple-images-to-a-model-with-django-fd00d8551a1c Something is clearly missing in this manual. I also tried setting different related_name, and checking them with that shitty code: def get_upload_path(instance, filename): if hasattr(instance.album, 'product'): name = 'product' elif hasattr(instance.album, 'blogpost'): name = 'blogpost' else: name = 'album' but that wasn't successful either. -
Access object instances from other pages in Python [duplicate]
I have been tasked to convert a few php based web apps into python. My concern is, is it possible to have other python pages access a class that has been instantiated by another python page? I have my classes in page1.py and use page2.py to create an instance. Does FLASK or DJANGO allow me to read/update that instance from page3.py? -
Can't serialize read only field
I want to serialize read only field (perform get request and view all objects) Problem: i don't see read_only_fields in response: GET http://127.0.0.1:8000/api/cameras/ [ // no 'proc_id', 'path_frames' { "id": 1, "building": 3, "name": "1", "url": "1", "zoneIdX": 1, "zoneIdY": 1 } ] serializers.py class CameraSerializer(serializers.ModelSerializer): class Meta: model = Camera fields = ('id', 'building', 'name', 'url', 'zone_id_x', 'zone_id_y') read_only_fields = ('proc_id', 'path_frames') def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance view.py class CameraView(viewsets.ModelViewSet): serializer_class = CameraSerializer queryset = Camera.objects.all() def get_camera_create_serializer(self, *args, **kwargs): kwargs["context"] = self.get_serializer_context() return self.serializer_class(*args, **kwargs) def list(self, request): serializer = CameraSerializer(self.queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): user = get_object_or_404(self.queryset, pk=pk) serializer = CameraSerializer(user) return Response(serializer.data) -
How to fix my views.py to pass second parameter (email) to my html link
urls.py path('property_details/<str:id>/', views.property_details, name="property_details"), views.py def property_details(request, id): referrer = request.GET.get('referrer') property = get_object_or_404(Property, slug=id) sharing.html href="{% url 'property_details' property.slug **email** %}" -
Django default of ArrayField is a callable, but I still get a warning?
so I've got this model: class Action(models.Model): d_changes = ArrayField(models.FloatField(), default=list(), verbose_name='D Changes') w_changes = ArrayField(models.FloatField(), default=list(), verbose_name='A Changes') And when I want to create a migration or a fixture I always receive the following warning for both fields: backend.Action.d_changes: (postgres.E003) ArrayField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `list` instead of `[]`. For my migrations its not such a big deal, since everything still works fine. But when I try to create a fixture of my db, my .json File always ends up with this bit in the very top of my .json file: System check identified some issues: WARNINGS: [33;1mbackend.Action.d_changes: (postgres.E003) ArrayField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `list` instead of `[]`.[0m [33;1mbackend.Action.w_changes: (postgres.E003) ArrayField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `list` instead of `[]`.[0m Which breaks my .json file and thus I cannot use loaddata, as I always receive a DeserializationError(), … -
How to filter model objects in django using checkboxex?
For example i have such filters Colors: red blue black Material: wood plastic where * is a checkbox, Color and Material - model field. And i want to filter my QuerySet with such parameters: Colors: red,blue; Material: wood; How can i do that? -
What is the difference between context and _context in a DRF serializer?
In a nested serializer I tried to pass some context while creating the serializer. But it seems, the context of Inner serializer is overridden by context of Outer serializer. Explained with example below: class WebsiteImagesSerializer(serializers.ModelSerializer): class Meta: list_serializer_class = FilterSerializer model = WebsiteImages fields = ('id', 'website', 'image_url', 'category') def __init__(self, *args, **kwargs): # Instantiate the superclass normally super(WebsiteImagesReadSerializer, self).__init__(*args, **kwargs) print('context at init of WebsiteImagesSerializer', self.context) print('_context at init of WebsiteImagesSerializer', self._context) def to_representation(self, data): ''' updating the image_url to complete url which can be used ''' print('context at to_representation of WebsiteImagesSerializer', self.context) print('_context at to_representation of WebsiteImagesSerializer', self._context) repr = super(WebsiteImagesReadSerializer, self).to_representation(data) return repr class FilterSerializer(serializers.ListSerializer): def to_representation(self, data): print('context at FilterSerializer', self.context) print('_context at FilterSerializer', self._context) data = data.filter(status=True) return super(FilterSerializer, self).to_representation(data) class WebsiteSerializer(serializers.ModelSerializer): websiteimages_set = WebsiteImagesSerializer(many=True, read_only=True, context={'filter': {'category': 'logo'}}) class Meta: model = Website fields = ('id', 'url', 'websiteimages_set') Now when I create an Object of WebsiteSerializer with context data as {'required_fields': []}, and fetch its data, the output is as follows: context at init of WebsiteImagesSerializer {'filter': {'category': 'logo'}} _context at init of WebsiteImagesSerializer {'filter': {'category': 'logo'}} context at FilterSerializer {'required_fields': []} _context at FilterSerializer {'filter': {'category': 'logo'}} context at to_representation of WebsiteImagesSerializer {'required_fields': … -
Django migration with 2 DBs?
I've the databases db1 and db2. The schemas of both DBs should be created with the same migration script. The Django docs mention DATABASE_ROUTERS and RunPython, but I didn't manage to get it working so far. The function is called, but migrations.CreateModel() has no impact when called from the function: the table is not created. Migration script: # 0001_initial.py def forwards(apps, schema_editor): if schema_editor.connection.alias == 'db1': print('This line is called!') migrations.CreateModel( name='MyModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), # ... ] ) class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.RunPython(forwards, hints={'target_db': 'db1'}), ] Router: DatabaseRouter: # ... def allow_migrate(self, db, app_label, model_name=None, **hints): if 'target_db' in hints: return db == hints['target_db'] return True Command: python manage.py migrate --database=db1 Any idea? Thanks in advance! -
Images not uploading to database djanjo/pyton
Previously I when posting to the database and displaying it through the template everything was fine. Now however I am attempting to upload multiple images but the images are not posting/uploading to the database. Is it possible for you guys to scan my code and give me a clue as to what I am missing. I have been at this a couple days now without any luck. I would just like the multiple images uploaded to my database so I can render on tmemplate. Thanks in advance for input Model.py class VehicleStats(models.Model): car_id = models.AutoField(primary_key=True) make = models.CharField(max_length=30) model = models.CharField(max_length=30) series = models.CharField(max_length=10) year = models.CharField(null=True, max_length=10) color = models.CharField(null=True, max_length=30) engine_size = models.DecimalField(null=True, max_digits=2, decimal_places=1 ) milage = models.IntegerField(null=True, ) transmission = models.CharField(max_length=30, choices=transmission_choices) features = models.TextField(null=True, ) additional_info = models.TextField(null=True, ) contact_name = models.CharField(max_length = 60) contact_phone = models.CharField(max_length=16) contact_email = models.EmailField(null=True, max_length=40) asking_price = models.DecimalField(max_digits=10000, decimal_places=2) date_added = models.DateField() page_views = models.IntegerField(blank=True, null=True) car_image = models.ManyToManyField('CarImages', blank=True) def __str__(self): return self.contact_name class CarImages(models.Model): car = models.ForeignKey(VehicleStats, on_delete=models.CASCADE) car_image = models.ImageField(upload_to="images/", blank=True) def __str__(self): return self.car.contact_name View.py def add_seller(request): if request.method == "POST": sellerform = SellerForm(request.POST, request.FILES) files = request.FILES.getlist('car_image') if sellerform.is_valid(): seller_form = sellerform.save(commit=False) seller_form.save() for … -
Handle Production Migrations and Development Migrations in Django
While developing a Django project, all your migrations are stored within each app folder, however, in production I don't want those migrations, I want to keep a Production database, and a Development database: How do I handle Django migrations in a Production and Development environment? I'm asking this question because it's been really hard to update my deployed project with new additions in the development one, my ideal scenario would be to keep each set of migrations in a folder outside my source code, just like the databases. -
Django annotate by adding months to date field
from datetime import timedelta from django.db.models import DateTimeField, ExpressionWrapper, F MyModel.objects.annotate( date_plus345=ExpressionWrapper(F('creation_date') + timedelta(days=345), output_field=DateTimeField() ) ) Like this is there any ways to add 40 months to the creation_date field and annotate it? -
Get "Server Error (500)" as soon as I turn debug off (DEBUG = False) on django but working fine when DEBUG = True
I tried to deploy my app through Heroku but as soon as I turn debug off, the whole thing goes bust. Same happens locally. When DEBUG = True, everything is OK, both locally or through Heroku. I have no clue where this is coming from. Here's my settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent print(BASE_DIR) print(BASE_DIR / 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'XXX.herokuapp.com', '127.0.0.1', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party #own apps 'pages', 'templates', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'mysite.urls' 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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } … -
Django DRF: Name returned objects dynamically
I am not sure if a dynaimc serializer is what I need, as I did not exactly understand when to use it. Following problem: My serializer returns a working/valid json, but in a suboptimal shape: [ { "store": { "last_update": "2021-06-01T12:06:00Z", "store_id": 238, } }, { "store": { "last_update": null, "store_id": 1, } } } ] where I would want it to be: [ { "store_id": 238, "data": { "last_update": "2021-06-01T12:06:00Z", } }, { "store_id": 1, "data": { "last_update": null, } } ] simple model: class Store(models.Model): store_id = models.IntegerField("store id", null = True, blank = True) last_update = models.DateTimeField("last update") serializer: class StoreSerializer(serializers.ModelSerializer): store = serializers.SerializerMethodField("get_info") def get_info(self, store): tmp = {} tmp["store_id"] = store.store_id tmp["last_update"] = store.last_update return tmp views: class StoreViewSet(viewsets.ViewSet): serializer_class = StoreSerializer http_method_names = ['get', 'head'] def list(self, request): try: query = Store.objects.all() results = StoreSerializer(data = query, many = True) results.is_valid() return Response(data = results.data, status = status.HTTP_200_OK) except Exception as E: return Response(data = str(E), status = status.HTTP_400_BAD_REQUEST) How can I alter the serializer to achieve the desired shape of the JSON? -
Is it possible to disable django model permissions?
I want to add my own custom permission inside the django cms pages instead of CMS model permissions. How can I do that ? For example: {% if request.user.is_manager %} {% cms_toolbar %} {% endif %} OR is there a way to disable all the django default permission management system or a way to apply own custom permission on the cms templates ? -
Why is the email line not displayed in the registration form?
I am trying to do registration by mail, did everything according to this guide https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef but in the registration form a line with email is not displayed, although I indicated it in forms.py from django import forms from .models import Post, Comment from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'body') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), } class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = User fields = ('username', 'email', 'password1', 'password2') signup.html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> {% endblock %} myblog/views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post, Comment from .forms import CommentForm from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import login from .forms import SignupForm from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode … -
Django Signals set signal to create a default avatar image on UserExtended model after registering User
I want to create an entry on UserExtended model after registering an user on Django default user model. here is UserExtended model: class UserExtended(models.Model): extended_id = models.AutoField(primary_key=True, editable=False) avatar = models.ImageField(null=True, blank=True, default='Capture.PNG') user = models.OneToOneField(User, on_delete=models.CASCADE, null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) here is the view function that registering the user @api_view(['POST']) def register_user(request): data = request.data user = User.objects.create( first_name=data['name'], username=data['username'], email=data['email'], password=make_password(data['password']) ) serializer = UserSerializerWithToken(user, many=False) return Response(serializer.data) here is the serializer class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) avatar = serializers.SerializerMethodField() def get_avatar(self, obj): avatar = obj.userextended.avatar.url print(avatar) if avatar == '': avatar = 'null' return avatar class Meta: model = User fields = ['id', 'username', 'email', 'name', 'avatar', 'isAdmin'] def get_name(self, obj): name = obj.first_name if name == '': name = obj.email return name def get_isAdmin(self, obj): return obj.is_staff class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', 'username', 'email', 'name', 'isAdmin', 'token'] here is the signal.py: from django.db.models.signals import post_save, pre_delete from django.contrib.auth.models import User from django.dispatch import receiver from .models import UserExtended @receiver(post_save, sender=User) def create_user_extended(sender, instance, created, **kwargs): if created: UserExtended.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_extended(sender, instance, **kwargs): instance.userextended.save() but the signal is not working to … -
got an unexpected keyword argument 'pk' when use decorator in django
i want to run decorator function before my view's dispatch method below is my decorators.py from django.urls import reverse from django.shortcuts import render from django.shortcuts import redirect def check_point(point=None): def decorator(view_func): def wrap(request, *args, **kwargs): price = point or request.get_object().price if request.user.point.get_point() >= price: return view_func(request, *args, **kwargs) return wrap return decorator and my view code @method_decorator(check_point, name='dispatch') class CheckWinningView(SingleObjectMixin, RedirectView): model = Product But when I run the code, I get the following error: I'm not sure why I'm getting this error. I know that 'pk' must be entered unconditionally due to the characteristics of singleobjectmixin. how can i fix it? -
filter from a case when annotate queryset django
hello filter on a "when case" annotation seems don't work.. models.py class Product(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(primary_key=True) description = models.TextField() price = models.PositiveSmallIntegerField() TTC_price = models.BooleanField(default=False) .... def price_exact_ttc(): return Case(When(TTC_price=False, then=F("price") * TVA), default=F("price")) the result that I return: Products.objets.annotate(price_exact_ttc=price_exact_ttc()) .filter( price_exact_ttc__range=( Decimal(self.request.GET["min_ttc_price"]), Decimal(self.request.GET["max_ttc_price"]) ) ) return nothing with a interval that contains some products. So HELP :)