Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF serializer data property not overridden
I have a the following serializer where I need to override the data property but for some reason it does not seem to be overridden at all. class ShopItemListSerializer(AvailabilitySerializerFieldMixin, serializers.ModelSerializer): is_aggregation_product = serializers.BooleanField() price = MoneyField(allow_null=True) discount_price = serializers.SerializerMethodField() is_favorite = serializers.SerializerMethodField() categories = ShopItemCategorySerializer(many=True) price_effect = ProductPriceEffectSerializer(source="aggregation_product.price_effect") special_information = serializers.CharField() @property def data(self): logging.error("I should be overridden") ret = super().data return_dict = ReturnDict(ret, serializer=self) if self.context.get("include_unavailable", False) is True: """ remove products that are not available """ for product in return_dict.copy(): if product["availability"] and product["availability"]["is_available"] is True: return_dict.remove(product) return return_dict I am using viewsets like the following: class ProductViewSet(StorePickupTimeSerializerContextMixin, ReadOnlyModelViewSet): queryset = ShopItem.app_visibles.prefetch_related("pictures").distinct() permission_classes = [IsCustomer] filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilterWithNoneSupport) filterset_class = ShopItemFilter search_fields = ["name", "number", "categories__name"] def get_serializer_class(self): if self.action == "list": return ShopItemListSerializer return ShopItemProductDetailSerializer I would appreciate any insights explaining the reason behind this behavior. -
Return value if not exist
Within my template, I have a number of values being presented from data within the database. {{ fundamentals.project_category }} But when no data exists it throws an error matching query does not exist. i think because the no data is being returned in the query set within the fundamentals model. fundamentals = project.fundamentals_set.get() within my view im trying: if project.fundamentals_set.get().exists(): fundamentals = project.fundamentals_set.get() else: #what should i put here? Im assuming an if statment is requried along with exists(): but this isn't working and im not sure what i should put in the else statement to return something like nothing exists when no data exists within the fields? -
(553, b'Relaying disallowed as webmaster@localhost')
I'm trying to send a password reset email on Django web app using the Zoho SMTP but it keeps throwing this error when I use Gmail. Below are some snippets Views.py def post(self, request): name = request.POST['Name'] email = request.POST['Email'] phone = request.POST['Phone'] message = request.POST['Message'] email_msg = EmailMessage( subject='New Enquiry', body=message + phone, from_email='noreply@domain.com', to=['support@domain.com'], ) email_msg.send() settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.zoho.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' -
Specific problem while migrating Django models
Attempt to migrate just default models in Django app with python manage.py migrate returns following annoying error: Traceback (most recent call last): File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/home/stepski/anaconda3/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/checks/model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/models/base.py", line 1307, in … -
hot reload of Django development in Docker is delayed
The hot reload is delayed by 1 cycle. So for example, if I have print("Hi"), nothing changes, but then if I have print("Hello"), then print("Hi") appears on the screen. If I have a third command print("Goodbye"), then print("Hello") appears. So it is always delayed by a cycle. How can I fix the code below so it is not delayed by 1 cycle but the update happens instantly. Here is my dockerfile. ########### # BUILDER # ########### # pull official base image FROM python:3.9.9-slim-bullseye as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.9.9-slim-bullseye # installing netcat (nc) since we are using that to listen to postgres server in entrypoint.sh RUN apt-get update && apt-get install -y --no-install-recommends netcat && \ apt-get install ffmpeg libsm6 libxext6 -y &&\ apt-get autoremove -y && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* # install dependencies COPY --from=builder /usr/src/app/wheels /wheels COPY --from=builder /usr/src/app/requirements.txt . RUN pip install --no-cache /wheels/* # set work directory WORKDIR /usr/src/app # copy our django … -
different between title and title_icontains in model filter django
what is diffrent between title and title_icontains in django ? from .model import product product.objects.filter(title='blah') product.objects.filter(tite__icontains='blah') -
ArrayField in djongo models, i get json response like these
[ { "id": 10, "table_name": "cars", "columns": "[{"column_key": "paul", "display_key": "paul@mail.com", "column_type": "text", "char_limit": "0"}, {"column_key": "tus", "display_key": "tus@mail.com", "column_type": "text", "char_limit": "1"}]" }, { "id": 26, "table_name": "comics", "columns": "[{"column_key": "ben-10", "display_key": "ben@mail.com", "column_type": "text", "char_limit": "5"}]" } ] -
Django: Changing of value of particular fields in previous instances of model if particular instance occurs
I' m creating small django project. Is any way to change value of particular fields in previous instances of particular model? class Fruit (models.Model): name=models.CharField(max_length=40) amount=models.IntegerField() So far for example i have three instances of my model. [0 Object{ "model": "Fruit","pk": 1,"fields": {"name": "Banana", "amount": "2"}}, 1 Object{ "model": "Fruit","pk": 2,"fields": {"name": "Apple", "amount": "2"}}, 2 Object{ "model": "Fruit","pk": 3,"fields": {"name": "Mango", "amount": "1"}}] And i decided that fourth instance will be Orange in amount 3. [0 Object{ "model": "Fruit","pk": 1,"fields": {"name": "Banana", "amount": "2"}}, 1 Object{ "model": "Fruit","pk": 2,"fields": {"name": "Orange", "amount": "2"}}, 2 Object{ "model": "Fruit","pk": 3,"fields": {"name": "Orange", "amount": "1"}} 3 Object{ "model": "Fruit","pk": 4,"fields": {"name": "Orange", "amount": "3"}}] As you see my goal is to change all previous names of fruits to Orange in case of creating of instance with Orange as name until Banana occurs so banana remains unchanged. Is there any way to do something like that? -
Problema no GET python Django
Probably something simple I did not notice: <h1> WRITE YOUR TEXT: </h1> <form method="" action="counter"> <textarea name= "words" rows="25" cols="65"></textarea><br> <input value="submit" type="submit"/> </form> from typing import Counter from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), path('counter', views.counter, name = 'counter'), ] from django.shortcuts import render from django.http import HttpResponse # Create your views here def index(request): return render(request, 'index.html') def counter(request): words = request.GET['words'], return render(request, 'counter.html', words) and the error is: https://i.stack.imgur.com/U7pNy.png -
What attributes are allowed on custom django admin field methods?
I've noticed in some Django project that uses Django admin methods on model-admin that look like this: def some_field(self, obj): return calculate_something(obj) some_field.short_description = "Some description" And then it's used in field-set as normal field. It gets somehow magically recognized by name. Where can I find documentation about the short_description and what other things I can set? -
Failed at step EXEC spawning /var/www/loveIt/env/bin/gunicorn: No such file or directory
I have a problem with gunicorn. I followed this guide to run website hosting on my raspberry on debian. But I got this error: gunicorn.service: Failed at step EXEC spawning /var/www/loveIt/env/bin/gunicorn: No such file or directory I don't understand why it don't create gunicorn. I watched a lot of guides but no one helped me. Here is my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=anton Group=www-data WorkingDirectory=/var/www/loveIt ExecStart=/var/www/loveIt/env/bin/gunicorn \ --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn.sock \ lulu.wsgi:application [Install] WantedBy=multi-user.target And this is my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target What I need to do to solve this problem? -
django application not working after i add watchtower logging
import boto3 boto3_logs_client = boto3.client("logs", region_name=AWS_REGION_NAME) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': logging.ERROR, 'handlers': ['console'], }, 'formatters': { 'simple': { 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'aws': { # you can add specific format for aws here 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'watchtower': { 'level': 'DEBUG', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_client': boto3_logs_client, 'log_group_name': AWS_LOG_GROUP, 'log_stream_name': AWS_LOG_STREAM, 'formatter': 'aws', }, }, 'loggers': { 'django': { 'level': 'INFO', 'handlers': ['watchtower'], 'propagate': False, }, # add your other loggers here... }, } Here i implemented watchtower logging in my django app My server is running but when i view http://127.0.0.1:8000/ This site can’t be reached what can be the error ? am i missing something please take a look. please take a look how can i fix this -
IntegrityError : null value in column of relation " violates not-null constraint
'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a " null value in column "customer_id" of relation "products_order" violates not-null constraint DETAIL: Failing row contains (21, null)." error : models.py class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) quantity = models.PositiveIntegerField(default=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png") def __str__(self): return self.name class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.IntegerField() city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) views.py : class ProductDetailView(FormMixin, TemplateView): model = Product template_name = 'product.html' form_class = OrderForm def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): context = self.get_context_data() form = OrderForm(request.POST) if context['form'].is_valid(): product = get_object_or_404(Product, name=self.kwargs['product_name']) customer = form.save() Order.objects.create(customer=customer) instance= Order.objects.create() instance.product.set(product) return super(TemplateView, self) def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['product'] = Product.objects.get(name=self.kwargs['product_name']) context['form'] = self.get_form() return context -
i couldn't find out this script at all in django-form
would you please explain this scripts? why we used **def init(self, *args, kwargs): AND **super(ProfileForm, self).init(*args, kwargs) ? *from django import forms from django.forms import fields from .models import User class ProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['username'].help_text = None self.fields['username'].disabled = True self.fields['email'].disabled = True self.fields['special_user'].disabled = True self.fields['is_author'].disabled = True class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'special_user', 'is_author' ] thanks.* -
SMTPAuthenticationError at /members/register after deployment in heroku ut works in local host
I am getting the below error when I aam trying to send an email to user. It is wroking fine in localhost, but after deploying it to heroku I am getting this error. My less secure app is turned on. SMTPAuthenticationError at /members/register (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 iREvsLOCGsSdIvQozvsLAI32usRkAKeN9zrVcpG8_5BPTE8Cid59meSrouoFeVL7uexVM\n5.7.14 9BeaQ5gSKAKohzILe4Nqyrn_p3OJhBZJVuJ3Nb36rtmD2h_Rb7TCpJRB6xMw87Ow>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 n7sm3256692wro.68 - gsmtp') settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'password' SERVER_EMAIL = EMAIL_HOST_USER -
How to intersect two query sets in django?
I have two queries. One of them has sold product id and sale amount, other one has product id and product price. query_product = Model1.objects.filter(...).values_list('ProductID', 'ProductPrice') query_sale = Model2.objects.filter(...).values_list('SaleProductID', 'ProductAmount') I want to calculate IF SaleProductID = ProductID, Sum(F('ProductPrice')*F('ProductAmount'). However, I could not find how to do that with query. Note: Model2 has foreign key to Model1. Do you have any suggestions? Thank you! -
FormData and Django: How to pass empty array
I have email_list field in my form If there are no emails entered as Json payload i can send it as: { email_list: [] } Where as with FormData how to send it. I am thinking something like this if (data["email_list"].length === 0) { formData.append("email_list", []); } data["email_list"].forEach((item) => { formData.append("email_list", item); }); Am i doing the right way I checked the data i recieved in the django backend print(request.POST.getlist('email_list')) it prints [""] i want it to be [] -
Not redirecting to next page after login in Rest Framework
I have been trying to redirect the user to the main page after successful login in API. Email id and password which will be comes from the Angular. However, the email and password which is already existed in the SQL server where I have called the Stored Procedure in the Django rest framework. All I just want to pass the user's input in the place of 'demouser@demo.com' and 'NewUser@1' into the Stored Procedure now I have hardcoded value of the email and password which I suppose to get it from the POST request. How could I able to pass the post request in the Stored Procedure. views.py @api_view(['GET', 'POST']) def CheckUserStatusView(request): if request.method == 'GET': users = Tblusers.objects.all() serializer = CheckUserStatusSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_CheckOneQUserStatus] @EmailId=%s, @Password=%s', ('demouser@demo.com', 'NewUser@1')) result_set = cursor.fetchall() for row in result_set: row[2] if request.data.get('EmailId') == row[2]: serializer = CheckUserStatusSerializers(data=request.data) if serializer.is_valid(): serializer.save() return HttpResponseRedirect(redirect_to='https://127.0.0.1:4200/#/dashboard') # return Response(status=status.HTTP_308_PERMANENT_REDIRECT) return Response(status=status.HTTP_201_CREATED) serializers.py class CheckUserStatusSerializers(serializers.ModelSerializer): class Meta: model = Tblusers fields ='__all__' models.py class Tblusers(models.Model): UserID = models.AutoField(db_column='UserID', primary_key=True) FullName = models.CharField(db_column='FullName', max_length=255) Emailid= models.CharField(db_column='AccentureID', max_length=255) Password = models.CharField(db_column='Password', max_length=200) -
Adding foreign key data through django rest framework serializer
I am new to django, I have two models User and Todo. User can have multiple todos, while creating the todos I want to pass user_id with it but while including user_id or user field along with request.data, I am getting validation error for Todo fields. Here is the User model and Todo model: class User(AbstractUser): email = models.EmailField(unique=True) password = models.CharField(max_length=128) username = None name = models.CharField(max_length=128) is_email_verified = models.BooleanField(null=True) mobile = models.CharField(max_length=13, validators=[RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}', message="Enter a valid mobile number")], default='+911234567890') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['mobile'] class Todo(models.Model): title = models.CharField(null=False, blank=False, max_length=100) description = models.TextField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: indexes = [ models.Index(fields=['created_at']), models.Index(fields=['updated_at']) ] Here is the Todoserializer: from rest_framework.serializers import ModelSerializer, CharField from todos.models import Todo from users.models import User class TodoSerializer(ModelSerializer): class Meta: model = Todo fields = '__all__' read_only_fields = ['id', 'created_at', 'updated_at'] Here is the view for creating todos: @api_view(['POST']) def create(request): user = request.user todo = TodoSerializer(data={ **request.data, 'user': user.pk }) todo.is_valid(raise_exception=True) todo.save() return Response(status=status.HTTP_200_OK, data={'todo': todo}) The serializer doesn't get validated any time -
Are "max_length" and "choices" in Model's class definition supposed to prevent from inserting invalid values into the database?
I have a situation where i have a model (in Django/python) like: ''' class Box(models.Model): BOX_CHOICES = [('L','Large'),('M','Medium'),('S','Small')] size= models.CharField(max_length=1,choices=BOX_CHOICES, blank=True, null=True) ''' I thought that this would insure that i couldn't add a string like "Humongous" into size field. And yet, i was able to accomplish just that using get_or_create function to insert. Could you please explain how come the max_length and choices did not restrict that from inserting. Thank you! -
How to visualize data in a Django (real-time)
The problem here is that, there are several options I can use in order to display real-time visualization in django. But which one of them is simple enough to be used in teaching a newbie? What I'm trying to do is visualize data which is fetched from an external API. -
how to group by with annotate in django?
I tried absolutely everything with values().annotate() or aggregate() , or by following tutorials with Subquery I cant get what I want, let me explain : There is what I get with QuizzUserItem.objects.filter(examuser=user_exam).values('item__question', 'item') {'item': 759, 'item__question': 429} {'item': 762, 'item__question': 430} {'item': 763, 'item__question': 430} {'item': 767, 'item__question': 431} What I want is to group by item__question and get this result : {'item': 759, 'item__question': 429} {'item': 762,763 'item__question': 430} {'item': 767, 'item__question': 431} I start to think there is absolutely no way :/ What I tried : QuizzUserItem.objects.filter(examuser=user_exam).values('item__question','item').annotate(items_number=Count('item__question')) I got : {'item': 759, 'item__question': 429, 'items_number': 1} {'item': 762, 'item__question': 430, 'items_number': 1} {'item': 763, 'item__question': 430, 'items_number': 1} {'item': 767, 'item__question': 431, 'items_number': 1} or QuizzUserItem.objects.filter(examuser=user_exam).values('item__question').annotate(items_number=Count('item__question')) This one is the closest result that I got : {'item__question': 429, 'items_number': 1} {'item__question': 430, 'items_number': 2} {'item__question': 431, 'items_number': 1} But I have not the item_ids 762,763... Thank you for reading -
TypeError: An asyncio.Future, a coroutine or an awaitable is required in the django-channels
Requirements Python 3.8 asgiref 3.2.0 channels 2.4.0 channels-redis 2.4.2 Django 3.0.9, gunicorn 20.1.0 redis 3.5.3 uvicorn 0.11.5 websockets 8.1 I run channels as gunicorn -w 5 -b 0.0.0.0:8000 --log-level debug -k uvicorn.workers.UvicornWorker config.asgi:application. Also I have nginx as proxy-server. Logs class TokenAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): return TokenAuthMiddlewareInstance(scope, self) class TokenAuthMiddlewareInstance: def __init__(self, scope, middleware): self.middleware = middleware self.scope = dict(scope) self.inner = self.middleware.inner async def __call__(self, receive, send): try: token_key = (dict((x.split("=") for x in self.scope["query_string"].decode().split("&")))).get( "token", None ) except ValueError: token_key = None if token_key is None: self.scope["user"] = AnonymousUser() else: token_data = await get_token_data(token_key) self.scope["user"] = await get_user(token_data["user_id"]) inner = self.inner(self.scope) return await inner(receive, send) -
What is the implication of using request.user over self.request.user
I want to know the major difference between self.request.user (when using generic view View) and request.user (when using a user defined view), at times when I use django's generic View (django.views.generic import View) which has access to the django User model, I'd interact with the authenticated user as request.user and self.request.user without having any problem. For instance, in a django views.py: from django.contrib.auth import get_user_model User = get_user_model() class GetUserView(View): def get (self, request, *args, **kwargs): user_qs = User.objects.filter(username=request.user.username) #Do some other stuffs here class AnotherGetUserView(View): def get(self, request, *args, **kwargs): user_qs = User.objects.filter(username=self.request.user.username) #Do some other stuffs here I realize that the two queryset works fine but I can't still figure out the best to use. -
python Bad Request: /emails
I am trying to make an email web app using python but when I try to press the submit button to send the email this is what I get: [08/Dec/2021 15:26:26] "POST /emails HTTP/1.1" 400 61 Bad Request: /emails [08/Dec/2021 15:26:38] "POST /emails HTTP/1.1" 400 61 Bad Request: /emails ``` Please help!