Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RabbitMQ Pika and Django Channels websocket
I am using Django Channels and RabbitMQ pika, for the first time. I am trying to consume from RabbitMQ queue. I am using Django Channels AsyncConsumer to group send it to everyone connected in the websocket. User type 1 : Can create a task User type 2 : Can accept the task. Use case : When user type 1 creates the task it is published in the rabbitmq. When it is consumed from the queue, it has to be group-sent to frontend. And when the user type 2 accepts the task other instances of user type 2 cannot accept the same and we consume from the queue again and send the next task in the queue to everyone. I have created the connection in a different thread using sync_to_async I am appending it to an in-memory list from the callback function. And whenever someone accepts I just pop it out of the list and acknowledge the queue. class AcceptTaskConsumer(AsyncConsumer): body = [] #IN MEMORY LIST delivery = {} #To store ack delivery_tag async def websocket_connect(self, event): print("AcceptTaskConsumer connected", event) AcceptTaskConsumer.get_task() #STARTS Queue listener in new thread self.room_group_name = "user_type_2" await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.send({ "type": "websocket.accept" }) async … -
How to optimize my code and the database access?
I'm creating a sme budingeting application, where I have the necessity to manage a lot of data ( huge list of products, balance sheet table etc.). I want to have an efficient and optimized code, respecting the DRY principle and less querysets possible to the database. Ad example this code in my views.py is it efficient and optimized? def conto_economico(request): # Creazione tabella materie prime, sussidiarie, di consumo e merci defaults = list(0 for m in range(12)) elements = dict() for conto_id, year, month, totale in(Materiale.objects.values_list('conto__nome', 'data__year', 'data__month').annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo')), output_field=FloatField())).values_list('conto__nome', 'data__year', 'data__month', 'totale').order_by("conto_id")) : if conto_id not in elements.keys(): elements[conto_id]=list(defaults) index=month-1 elements[conto_id][index]=totale total_elements={'Per materie prime, sussidiarie, di consumo e di merci': [sum(t) for t in zip(*elements.values())],} I utilize this code for a lot of model to create my tables, but I think that are not efficient. -
AWS Django project throws AttributeError at /contact when sending a form
I've been working on my first website with django, it's deployed to aws with zappa. The page is using Lambda, S3, Apigateway and cloudfront. When I get the api url from my terminal after deployment/update the form works fine. But when I try to send the form from my actual website urls I've set up in aws the website throws the following error: AttributeError at /contact 'list' object has no attribute 'lower' Request Method: POST Request URL: https://asdasdasd.execute-api.eu-west-1.amazonaws.com/my_bucket/contact Django Version: 2.1 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'lower' Exception Location: /var/task/django/utils/http.py in is_same_domain, line 278 Python Executable: /var/lang/bin/python3.8 Python Version: 3.8.2 Python Path: ['/var/task', '/opt/python/lib/python3.8/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python38.zip', '/var/lang/lib/python3.8', '/var/lang/lib/python3.8/lib-dynload', '/var/lang/lib/python3.8/site-packages', '/opt/python/lib/python3.8/site-packages', '/opt/python', '/var/task'] Server time: Thu, 7 May 2020 06:13:04 +0000 My settings.py looks like this: """ Django settings for sciar_website project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ['DEBUG'] # EMAIL_HOST = ALLOWED_HOSTS = ['127.0.0.1', '(my_api_numbers).execute-api.eu-west-1.amazonaws.com', 'mywebsite.co/'] # Application definition INSTALLED_APPS = [ … -
Having trouble when migrating changes to the database - Python/Django
I was making some changes to the database in my project but i am facing some problems, it appears to not be a column in one of my tables but there it is, don't know what may be the cause of the problem, i'm not sure if it has to be with the onetoonefield relationships or what just broke it up entirely. Models from django.db import models # Create your models here. class BloodType(models.Model): Tipo = models.CharField(max_length=100) def __str__(self): return self.Tipo class Gender(models.Model): Genero = models.CharField(max_length=100) def __str__(self): return self.Genero class Nationality(models.Model): Nacionalidad = models.CharField(max_length=100) def __str__(self): return self.Nacionalidad class CivilStatus(models.Model): Estado = models.CharField(max_length=100) def __str__(self): return self.Estado class InsuranceCompany(models.Model): Compania = models.CharField(max_length=200) def __str__(self): return self.Compania class Policy(models.Model): Tipo_Poliza = models.CharField(max_length=256) def __str__(self): return self.Tipo_Poliza class Insurance(models.Model): Aseguradora = models.OneToOneField(InsuranceCompany,on_delete=models.DO_NOTHING) Tipo_de_Poliza = models.OneToOneField(Policy, on_delete=models.DO_NOTHING) Numero_de_poliza = models.CharField(max_length=100) Vencimiento = models.DateField() def __str__(self): return str(self.Aseguradora) + ' ' + str(self.Tipo_de_Poliza) class Patient(models.Model): Codigo = models.CharField(max_length=15) Nombre = models.CharField(max_length=100) Apellidos = models.CharField(max_length=200) Fecha_Nacimiento = models.DateField() Telefono = models.CharField(max_length=25,blank=True) Correo = models.EmailField(blank=True) Expediente = models.CharField(max_length=200, blank=True) Tipo_sangre = models.OneToOneField(BloodType,on_delete=models.DO_NOTHING) Peso = models.PositiveIntegerField() Estatura = models.PositiveIntegerField() Genero = models.OneToOneField(Gender,on_delete=models.DO_NOTHING) Nacionalidad = models.OneToOneField(Nationality,on_delete=models.DO_NOTHING) Estado_civil = models.OneToOneField(CivilStatus,on_delete=models.DO_NOTHING) Ocupacion = models.CharField(max_length=100,blank=True) Lugar_de_procedencia = models.CharField(max_length=100) Lugar_de_residencia = … -
How to add JS file in Django Admin just before the body tag
I am inserting two scripts into Djnago Admin as follows: class TutorialAdmin(admin.ModelAdmin): class Media: js = ( 'tutorials/js/ckeditor.js', 'tutorials/js/custom.js', ) formfield_overrides = { models.TextField: {'widget': Textarea( attrs={'id': 'custom_textarea'})} } Notice the formfield_overrides where I am adding an id custom_textarea to textarea tags so that I can get them later via javascript. If we look at my custom.js file: ClassicEditor .create( document.querySelector( '#custom_textarea' ) ) .catch( error => { console.error( error ); } ); This is the file which gets the element with id of custom_textarea. But the problem is that these files are added in the head tag so they run as soon as the page loads (before the textarea is rendered). I get the following error in the Chrome console: TypeError: Cannot read property 'appendChild' of null Is there a way where I can instruct Django to inject the custom.js just before the body tag? I know of a solution where I could edit my base.html in admin app. But I am wondering if there is a Django Way of doing this! Thanks. -
How to add user profile attributes to custom user model ( from AbstractUser ) in django admin panel? - StackInline
I saw an example in django document like this; from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from my_user_profile_app.models import Employee class EmployeeInline(admin.StackedInline): model = Employee can_delete = False verbose_name_plural = 'employee' class UserAdmin(BaseUserAdmin): inlines = (EmployeeInline, ) admin.site.unregister(User) admin.site.register(User, UserAdmin) I would like to use my custom user model with some extra fields (user_photo, user_credit...), so i wrote following code; accounts/models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) photo = models.ImageField(blank=True, upload_to='prof_pic/company', default='static/images/default_pp.png') credit = models.IntegerField(default=0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class FirmProfile(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='firmprofile_user') firm_name = models.CharField(max_length=200) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='userprofile_user') user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, default=1) and then accounts/admin.py class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'UserProfile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (UserProfileInline,) model = CustomUser list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) admin.site.register(CustomUser, CustomUserAdmin) admin.site.register(FirmProfile) But i got "no such table: main.auth_user" error when … -
it has show error when i am poting data 'str' object has no attribute 'update'
@api_view(['GET', 'POST']) def compnay_list(request): """ List all Compnays, or create a new Compnay. """ if request.method == 'GET': compnay = Company.objects.all() serializer = CompanySerializer(compnay, many=True) return Response(serializer.data) elif request.method == 'POST': try: print(request.data.get('email')) user_id = User.objects.get(email=request.data.get('email')).id print(request.data) user_response = request.data.get('user_response') for item in user_response: item.update({"user": user_id}) serializer = CompanySerializer(data=user_response) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: print("Error:email not available") -
How do I create a MAX value for column referring to another table's column
class Agent(models.Model): nickname = models.CharField(max_length=64) club_agent_id = models.IntegerField() club = models.ForeignKey( Club, on_delete=models.CASCADE, related_name="agents") **rakeback** = models.DecimalField(max_digits=3, decimal_places=3) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="agents") def __str__(self): return f"{self.nickname} - {self.club} - {self.rakeback}" class Account(models.Model): nickname = models.CharField(max_length=64) club_account_id = models.IntegerField() **rakeback** = models.DecimalField(max_digits=3, decimal_places=3) club = models.ManyToManyField(Club, blank=True, related_name="accounts") agent = models.ManyToManyField(Agent, related_name="accounts") def __str__(self): return f"{self.club_account_id} - {self.nickname}" Here the program will create Agent and Account are tied to it. Account belongs to Agent. Agent has many Accounts. When creating Agent, the rakeback value is set by the User. How do I set MAX for rakeback on Account referring to the value of rakeback on Agent? -
How Do We Attach a Django User to a ModelForm
Our group is working on setting up a Django Project 'for fun' having users add and remove books to sell. However, we have run into a problem of trying to assign a logged in user automatically to the book they are adding through the AddBookForm(ModelForm). Trying something along the lines of Book.objects.get(AccountUser) just returns a list of all created accounts as well as Book.objects.filter(seller=request.user). We are only looking to automatically assign the current user that is logged in when they go to add a book but have had no success reading documentations and watching tons of tutorials. Any help would be greatly appreciated!! MODEL class Book(models.Model): NEW = 'NEW' USED = 'USED' CONDITION_CHOICES = [ (NEW, 'New'), (USED, 'Used'), ] FICTION = 'FICTION' NON_FICTION = 'NON-FICTION' POETRY = 'POETRY' DRAMA = 'DRAMA' EDUCATION = 'EDUCATION' GENRE_CHOICES = [ (FICTION, 'Fiction'), (NON_FICTION, 'Non-Fiction'), (POETRY, 'Poetry'), (DRAMA, 'Drama'), (EDUCATION, 'Education'), ] class Subject(models.IntegerChoices): architecture_and_construction = 0 arts_and_digital_arts = 1 business_and_management = 2 communications_and_media = 3 computing_and_mathematics = 4 criminal_justice = 5 education_and_teaching = 6 engineering_and_technology = 7 entrepreneurship = 8 exploratory = 9 government_and_administrations = 10 health_and_wellness = 11 humanities = 12 interdisciplinary_studies = 13 law_and_public_services = 14 medical_studies_and_sciences = 15 nursing_and_health_care … -
Cant display database values in django page
models.py from future import unicode_literals from django.conf import settings import requests import json from urllib.parse import quote from django.db import models class Company(models.Model): name = models.CharField(max_length=100, db_index=True) description = models.TextField(default='1') companyPhone=models.CharField(max_length=100,blank=True) companyWebsite=models.CharField(max_length=100,blank=True) companyIsPrivate=models.BooleanField(default=True) dividend=models.DecimalField(max_digits=7, decimal_places=2) priceEarningsToGrowthAndDividendYieldRatio=models.DecimalField(max_digits=7, decimal_places=2) price=models.DecimalField(max_digits=7, decimal_places=2) numberOfEmployees=models.DecimalField(max_digits=7, decimal_places=2) type=models.CharField(max_length=100,default='2') bicsIndustry=models.CharField(max_length=100,default='3') bicsSector=models.CharField(max_length=100,default='4') companyDescription=models.TextField(default='5') companyAddress=models.TextField(default='') priceToSalesRatio=models.DecimalField(max_digits=7, decimal_places=2) priceToBookRatio=models.DecimalField(max_digits=7, decimal_places=2) priceEarningsRatio=models.DecimalField(max_digits=7, decimal_places=2) totalAssets=models.DecimalField(max_digits=7, decimal_places=2, default=0.0) volume=models.DecimalField(max_digits=7, decimal_places=2,default=0.0) is_unique = models.BooleanField(default=True) def str(self): return self.name class Meta: db_table = 'post_company' view.py from django.forms import ModelForm from django.shortcuts import get_object_or_404, render from .models import Company def my_view(request): names = request.GET.get('name') instance = Company.objects.filter(pk=names).first() class ClientForm(ModelForm): class Meta: model = Company fields= '__all__' #fields = ('name', 'description','companyPhone','companyWebsite') form = ClientForm(instance=instance) return render(request,'pdf.html', {'form': form} ) display.py {% for field in form %} {{ field.label }} {% endfor %} {% for field in form %} {{ field.value }} {% endfor %} -
How to configure Django VPS location in URL request
I am trying to configure my Django app (Djnago 3.05) to work from a server location. The location is http://dev.apps.net/tac. How do i include this in each request? I managed to do this if adding in views.py the '/tac' prefix and add a folder named 'tac' in which all the templates exist. myviews.py @login_required def item_list(request): meta = "V1.1" if not any(field in request.GET for field in set(UserFilter.get_fields())): user_list = item.objects.order_by("-date").all()[:50] else: user_list = item.objects.order_by("-date").all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, "tac/items/item_list.html", {"filter": user_filter}) urls.py urlpatterns = [ url( r"^login/$", admin_views.LoginView.as_view(template_name="registration/login.html"), name="login", ), url(r"^$", TemplateView.as_view(template_name="home.html"), name="home"), url(r"^input/$", views.inputprocess, name="inputprocess"), url(r"^items/$", views.item_list, name="item_list"), url(r"^items/create/$", views.item_create, name="item_create"), url(r"^items/(?P<pk>\d+)/update/$", views.item_update, name="item_update"), url(r"^items/(?P<pk>\d+)/delete/$", views.item_delete, name="item_delete"), url(r"^reports/$", views.reports, name="reports"), url(r"^timeline/$", views.timeline, name="timeline"), url(r"^support/$", views.support, name="support"), url(r"^dbToools/$", views.dbTools, name="dbTools"), url(r"^logout/$", views.logout_view, name="logout_view"), url(r"^upload/$", views.upload, name="upload"), path("accounts/login/", auth_views.LoginView.as_view()), path("admin/", admin.site.urls), ] I am not sure if this is the correct way. How could I do this more efficient? Could you guys please gelp me here? Thanks! -
Django Filter: __exact lookup doesn't work although no lookup works
I want to use filters on my endpoint using Django Filters. My field is a boolean field, and I justs want to filter on the exact value. When query api/mybooks?is_read=true it works (no operator --> use exact instead, it is fine) if I use the exact operator explicitely api/mybooks?is_read__exact=true it doesn't work, the filter is ignored. my filter: class MyBookFilter(django_filters.FilterSet): class Meta: model = MyBook fields = { "is_read": ["exact"], } I use the default postgres sql database. Am I missing something? -
Django full text search with PostgreSQL, across multiple different models
I need to perform FTS across multiple different models. I want to get any model type in search result. I would like to sort results by rank, to get most relevant result. I can run search one by one, but not sure how can I combine results, especially preserving rank relevancy. Here are models, its an example from Making queries manual page. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() -
Edit Django files on Heroku without editing my database files
I wanna make some changes to my Django site running on Heroku, how can i upload my new changes with git push without touching my database, so i don't loose any data? -
How can I generate a dynamic shorturl with expiring time?
I have a python code with django that make shorturl with hash decoder, but it cannot generate dynamic code for especial full url. In fact i want to generate shorturl codes with expiring time so that when its time expired, i woud be able to generate new shorturl for my full url. Thanks you for your answers! model.py class URL(models.Model): full_url = models.URLField(unique=True) short_url = models.URLField(unique=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.id: self.short_url = md5(self.full_url.encode()).hexdigest()[:8] validate = URLValidator() try: validate(self.full_url) except ValidationError as e: raise GraphQLError('invalid url') return super().save(*args, **kwargs) -
Django Nginx Gunicorn Upstream Premature closed connection while reading response
nginx conf server { listen 80; server_name private.com; client_max_body_size 4G; client_body_buffer_size 8000M; client_body_timeout 120; proxy_connect_timeout 900s; proxy_read_timeout 900s; location = /favicon.ico { access_log off; log_not_found off; } autoindex on; location / { include proxy_params; proxy_pass http://unix:/home/dm/stat.cok; } } gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=Pa Group=www-data WorkingDirectory=/home/un/foldername ExecStart=/home/un/foldername/bin/gunicorn \ --access-logfile - \ --workers 3 \ --timeout 450 \ --bind unix:/home/dm/stat.sock scistat.wsgi:application [Install] WantedBy=multi-user.target I upload a large excel file 90mb size, It contains 450000+ rows and 6 columns. After the file upload, It calculate the row and columnf of excel file the multiply it to compute the total row and column of excel file, but this error show "upstream prematurely closed connection while reading response header from upstream" -
Django 3.0 App is not a registered namespace
I have the app_name as basicapp in the urls.py folder of my app but still when django says basicapp is not a registered namespace. here is my urls.py of basicapp from django.urls import path from basicapp import views from django.urls import include #template tagging app_label = 'basicapp' urlpatterns = [ path('relative/',views.relative,name='relative'), path('other/',views.other,name='other'), ] template file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Welcome to relative url</h1> <a href="{% url 'basicapp:other' %}"></a> </body> </html> Please let me know how to fix this mistake. -
Django channel not getting message
I am using django channel in my current project. From one of my django app, I am sending notification to the channel layer, so that websocket can broadcast the message. But problem is consumer is not getting my message. Utils in django app for sending notification to channel: from asgiref.sync import AsyncToSync from channels.layers import get_channel_layer import json def async_send(group_name, text): channel_layer = get_channel_layer() AsyncToSync(channel_layer.group_send)( group_name, { 'type': 'notify', 'text': json.dumps(text) } ) My consumer file is: from channels.generic.websocket import AsyncWebsocketConsumer class InformationConsumer(AsyncWebsocketConsumer): async def connect(self): self.channel_layer.group_add(str(self.scope['user']), self.channel_name) await self.accept() async def notify(self, event): await self.send_json( { "message": event['text'], }, ) print(event['text']) I am supposed to get the output of event['text'], but getting nothing :( -
ERROR 2026 - SSL connection error - Ubuntu 20.04
I've recently upgraded my local machine OS from Ubuntu 18.04 to 20.04, I'm running my MySQL-server on CentOS (AWS). Post upgrade whenever I'm trying to connect to MySQL server it is throwing SSL connection error. $ mysql -u yamcha -h database.yourproject.com -p --port 3309 ERROR 2026 (HY000): SSL connection error: error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol But if I pass --ssl-mode=disabled option along with it, I'm able to connect remotely. $ mysql -u yamcha -h database.yourproject.com -p --port 3309 --ssl-mode=disabled Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 22158946 Server version: 5.7.26 MySQL Community Server (GPL) Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> Queries: How to connect without passing --ssl-mode=disabled How to pass this --ssl-mode=disabled option in my Django application, currently I've defined it as shown below, but I'm still getting the same error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'yamcha', 'USER': 'yamcha', 'PASSWORD': 'xxxxxxxxxxxxxxx', 'HOST': 'database.yourproject.com', 'PORT': '3309', 'OPTIONS': {'ssl': False}, } -
how can I properly validate lesson modules per user rights?
I want to validate if my lesson material belongs to a xyz user with pro rights and each lesson has matched properly with the rights but if not it will display become a member , but however if I change the allowed_memberships id to pro only it doesnt work as expected it always goes to become member class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user.email id,stripe_customer_id,membership_id,user_id "1" "xxxxxx" "1" "63ce34cb8fe647a9bb1d28f61918e1bf" "3" "xxxxxx" "2" "c133546e6ed846c48a3938ccca8ffcbb" class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) def __str__(self): return self.membership_type id,membership_type,price,stripe_plan_id "1" "1" "Free" "0" "xxxxxxx" "2" "2" "Professional" "40" "xxxxxxx" class Lesson(models.Model): allowed_memberships = models.ManyToManyField(Membership) id,lesson_id,membership_id "1" "1" "1" "2" "2" "1" "3" "3" "1" "4" "4" "1" "5" "5" "1" "11" "6" "1" "64" "7" "2" views def get(self, request): template = loader.get_template(self.template_name) template_member = loader.get_template(self.template_payment) if UserMembership.objects.filter(user=request.user,membership_id=2).exists(): return HttpResponse(template.render()) else: return HttpResponse(template_member.render()) -
Getting one to many result
I am doing some trial and error in my django query. I'm trying to get a field with one column value beside it contains lists of elements. Basically I'm trying to figure out how to attain this result: { feed: {}, [{ id: 1, media_id: 11 }, { id: 2, media_id: 22 }] } I tried in python shell this query and it gave me this result: >>> query = Feed.objects.filter(Q(feedmedia__isnull=True)|Q(feedmedia__isnull=False)).values('message','feedmedia__id','feedmedia__media_id').distinct() >>> print(query) <FeedQuerySet [{'message': 'Classic motorcycles <3', 'feedmedia__id': 145, 'feedmedia__media_id': 152}, {'message': 'sample video', 'feedmedia__id': 147, 'feedmedia__media_id': 153}, {'message': 'Classic motorcycles <3', 'feedmedia__id': 146, 'feedmedia__media_id': 151}]> On the result I understand why the 'message' (one of the field in Feed table) is included, and the problem is that I don't know how I'm going to exclude it in order to get the desired output. These are the three models involved on this operation: class Media(models.Model): original_url = models.CharField(max_length=200, null=False, unique=False) small_url = models.CharField(max_length=200, null=True, unique=False) medium_url = models.CharField(max_length=200, null=True, unique=False) large_url = models.CharField(max_length=200, null=True, unique=False) uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "media" class Feed(models.Model): message = models.CharField(max_length=3000, null=True, unique=False) type = models.CharField(max_length=50, null=False, unique=False) category = models.CharField(max_length=50, null=False, unique=False) priority_level = models.IntegerField(default=0, null=False, unique=False) origin_location = models.CharField(max_length=100, null=True, … -
in Django, can I use a class only to group functions?
I am creating an application using Django. The application has user registration and login functionality. I have three functions related to user authentication as of now, login, registration, and email_check (which is called when the user types email address to see if it is available). I was trying to group these functions under a class for better organisation and easy accessibility. So I wrote a class and function like so: class user_auth: def check_email(email): with connection.cursor() as conn: conn.execute('select count(*) from user_info where email = %s', [email]) row = conn.fetchall() response = bool(row[0][0]) return(response) However, when I do this, I get a pylint error saying Method should have "self" as the first argument. If I save this and call it as user_auth.check_email('abc@xyz.com'), it works just fine. But if I add self as the first argument, it stops working. Am I using classes in an incorrect way? If yes, what is a better way to create a group of functions like this which can be easily imported using a single statement in other files? -
i am unable to list all data at once,is there any method like join or i need to use query method ...thank you in advance
models.py class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) def __str__(self): return self.first_name class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE, related_name='album_musician', null=True, blank=True) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() def __str__(self): return self.name serializer.py class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album # fields = ('id', 'artist', 'name', 'release_date', 'num_stars') fields = '__all__' class MusicianSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) instrument = serializers.CharField(max_length=30) album_musician = AlbumSerializer(many=True) def create(self, validated_data): albums_data = validated_data.pop('album_musician') musician = Musician.objects.create(**validated_data) for album_data in albums_data: Album.objects.create(artist=musician, **album_data) return musician def update(self, instance, validated_data): albums_data = validated_data.pop('album_musician') albums = (instance.album_musician).all() albums = list(albums) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.instrument = validated_data.get('instrument', instance.instrument) instance.save() for album_data in albums_data: album = albums.pop(0) album.name = album_data.get('name', album.name) album.release_date = album_data.get('release_date', album.release_date) album.num_stars = album_data.get('num_stars', album.num_stars) album.save() return instance views.py class MusicianView(generics.RetrieveUpdateDestroyAPIView): serializer_class = MusicianSerializer queryset = Musician.objects.all() -
Django CreateView Model Form not uploading File
the problem that I have is that my Model Form is not uploading a file, I had it working and after adding more code now is not working. It uploads all the other fields except for the file, the strange thing is that if I do it from the admin site it does work. models.py class Polizas(models.Model): nombre = models.CharField(max_length=30, blank=True, null=True) numero = models.CharField(max_length=30, unique=True) aseguradora = models.CharField(max_length=20, blank=True, null=True) carro = models.ForeignKey( Carros, on_delete=models.CASCADE, blank=True, null=True) inicio_poliza = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) fin_poliza = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) documento = models.FileField(upload_to='polizas/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Polizas" ordering = ['nombre'] def __str__(self): return self.nombre def get_absolute_url(self): return reverse('polizas') forms.py class PostPolizas(forms.ModelForm): class Meta: model = Polizas fields = ('nombre', 'numero', 'aseguradora', 'carro', 'inicio_poliza', 'fin_poliza', 'documento') widgets = {'inicio_poliza': forms.DateInput(attrs={'type': 'date'}), 'fin_poliza': forms.DateInput(attrs={'type': 'date'}) } views.py class PolizaCreate(LoginRequiredMixin, CreateView): login_url = '/login/' redirect_field_name = 'redirect_to' form_class = PostPolizas template_name = "add_insurance.html" Terminal [06/May/2020 22:32:17] "POST /insurance/add/ HTTP/1.1" 200 4557 [06/May/2020 22:32:25] "POST /insurance/add/ HTTP/1.1" 302 0 I have tried to validate the form and it is not working, this is error is happening in my other model forms that upload … -
django local variable 't' referenced before assignment
I saw this was a common error and I did look through other post, but they did not help me. I am getting the error Exception Value: local variable 't' referenced before assignment But my t variable is declared 3 lines above where it is saying it is not, inside my if validation. Scope should be fine for my return. function in question: def create(response): #response.user if response.method == "POST": form = CreateNewTrade(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = AssetList(name=n) t.save() response.user.assetlist.add(t) return HttpResponseRedirect("/userdash/%i" %t.id) #we fail at this t variable complete code: $ cat userdash/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import AssetList, Items from .forms import CreateNewTrade # Create your views here. #def index(response): # return HttpResponse("<h1>Hello Dark World!</h1>") def userdash(response, id): ls = AssetList.objects.get(id=id) if response.method == "POST": print(response.POST) if response.POST.get("save"): for item in ls.items_set.all(): if response.POST.get("c" + str(item.id)) == "clicked": item.sell_asset = True else: item.sell_asset = False item.save() elif response.POST.get("newItem"): txt = response.POST.get("new") if len(txt) > 2: #this validation is retarded and needs to be fixed ls.items_set.create(user_asset=txt, sell_asset=False) else: print("invalid") #items = ls.items_set.get(id=1) #return HttpResponse("<h1>User Dashboard!</h1><h2>%s</h2><br></br><p>%s</p>" %(ls.name, str(items.user_asset))) return render(response, "userdash/list.html", {"ls":ls}) def home(response): #pass return render(response, "userdash/home.html", {}) def …