Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a browser send notification when you change the windows or tabs
So, I want to make a web app for tests. Usually students try to cheat so they change the tabs or open other apps and search for their info.So, I use fiverr, and you can take skill tests on fiverr and if you tried to change the browser, for example ALT + TAB the test would stop.How can I implement a function like that with django or js? -
I am getting a No such table error in Django
I have read lot's of questions/answers trying to solve this. I am currently working on a website. The problem I am getting is the following: All my website was working Then I added two new models and changed 2 models name's After that I did 'python manage.py makemigrations' And 'python manage.py migrate' Everything seemed okay, but when I went to admin page (after adding the models to admin) the two new models and the models that I have changed names are not working. When I click on them in the admin page I get 'No such table: <table_name>'. I am going to show you... models.py theme = models.CharField(max_length=100) def __str__(self): return f'{self.theme}' class Question(models.Model): title = models.CharField(max_length=30, default="Title") theme = models.ForeignKey(Theme, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) content = models.TextField() post_date = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.title}' class UpVote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post = models.ForeignKey(Question, on_delete=models.CASCADE) class Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post = models.ForeignKey(Question, on_delete=models.CASCADE) comment = models.TextField() post_date = models.DateTimeField(default=timezone.now) # ARTICLES___________________________________________________________________________________________ class ArticleTheme(models.Model): theme = models.CharField(max_length=20) def __str__(self): return f'{self.theme}' class Article(models.Model): title = models.CharField(max_length=30) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) theme = models.ForeignKey(ArticleTheme, on_delete=models.CASCADE) pdf = models.FileField(upload_to='pdf', null=True) date_posted = models.DateTimeField(default=timezone.now) date_altered = models.DateTimeField(default=None, … -
How to filter and displayed 'many to many' elements in Django
I'm learning django and in my project can't figure out how properly get and displayed elements from many to many relation on deck detail page. model.py class Card(models.Model): def upload_path(self, filename): return os.path.join('cards/', filename) image = models.ImageField(upload_to=upload_path) card_num = models.CharField(max_length=20, default='') name = models.CharField(max_length=500, default='') desc = models.TextField(max_length=500, default='') card_class = models.OneToOneField(CardClass, on_delete=models.DO_NOTHING, default='') cost = models.OneToOneField(Cost, on_delete=models.DO_NOTHING, default='') card_type = models.OneToOneField(CardType, on_delete=models.DO_NOTHING, default='') rarity = models.OneToOneField(Rarity, on_delete=models.DO_NOTHING, default='') resource = models.IntegerField(default=None) attack = models.IntegerField(default=None) defence = models.IntegerField(default=None) def __str__(self): return self.name def get_absolute_url(self): return reverse('card:cardPageDetail', args=[self.name]) class Deck(models.Model): def upload_path(self, filename): return os.path.join('decks/', filename) image = models.ImageField(upload_to=upload_path) user = models.ForeignKey(User, on_delete=models.CASCADE) cards_list = models.ManyToManyField(Card, related_name='cards_list') deck_id = models.CharField(max_length=10, default='') name = models.CharField(max_length=500, default='') desc = models.CharField(max_length=500, default='') price = models.CharField(max_length=500, default='') def __str__(self): return self.name def get_absolute_url(self): return reverse('card:deckPageDetail', args=[self.name]) views.py def deckPageDetail(request, name): deck=get_object_or_404(Deck, name=name) cards_all = Card.objects.all() queryset = cards_all.objects.filter(cards_list__in=deck.deck_id) print(queryset) context = { 'deck': deck, 'cards_in_deck': queryset, } return render(request, 'landing/deck_detail.html', context) I tried few solutions based on stackoverflow and uncle google, but without results.I will be grateful for help. -
NoReverseMatch at /add_post
I have been working on a blog site using django and I made a way to add post within the home page without going to the admin page but when I post using the new way I get this error NoReverseMatch at /add_post Reverse for 'article-view' with arguments '('3', '0')' not found. 1 pattern(s) tried: ['article/(?P<pk>[0-9]+)$'] This is my models.py file from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=3500) def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("article-view", args=(str(self.id))) This is the views.py file from django.views.generic import ListView, DetailView, CreateView from .models import Post class HomeView(ListView): model = Post template_name = "home.html" class ArticleDetailView(DetailView): model = Post template_name = "detail_view.html" class AddPostView(CreateView): model = Post template_name = "add_post.html" fields = "__all__" This is the polls/urls.py from django.urls import path from .views import HomeView, ArticleDetailView, AddPostView urlpatterns = [ path('', HomeView.as_view(), name='home'), path('article/<int:pk>', ArticleDetailView.as_view(), name='article-view'), path('add_post', AddPostView.as_view(), name='add_post'), ] This is the add_post.html file {% extends 'base.html' %} {% block content %} <head> <title>Adding Post</title> </head> <h1>Add Blog Posts</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} … -
Django, ElasticBeanstalk, SES and Celery not working when I load to AWS
I have a django application with celery using AWS SES as a broker. When I run celery from my PC using the SES service it works fine. But when I try and load to AWS via ElasticBeanstalk I'm getting the following error in my eb-activity.log file [include] files: uwsgi.conf celery.conf celerybeat.conf [inet_http_server] port = 127.0.0.1:9001 celerybeat: available celeryd: available celeryd: added process group celerybeat: added process group celeryd: stopped celeryd: ERROR (abnormal termination) celerybeat: stopped celerybeat: ERROR (abnormal termination) I'm trying to set celery running using this config file (which I copied/modified from another stackoverflow answer I cannot now find) files: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash # Create required directories sudo mkdir -p /var/log/celery/ sudo mkdir -p /var/run/celery/ # Create group called 'celery' sudo groupadd -f celery # add the user 'celery' if it doesn't exist and add it to the group with same name id -u celery &>/dev/null || sudo useradd -g celery celery # add permissions to the celery user for r+w to the folders just created sudo chown -R celery:celery /var/log/celery/ sudo chown -R celery:celery /var/run/celery/ # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/%/%%/g' | … -
how can i get the uploaded file in Django template?
in this template: {% block content %} <form method="post" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple="multiple" /> <p class="container" style="margin-top: 10px"> <input type="submit" value="upload" class="btn btn-primary" /> </p> </form> {% endblock%} how can I get the uploaded file in the views.py I want to get the file, edited it, and render the edited file to another template. -
Why do I get this error in Admin Page Not Found [closed]
I finished my project and I am trying to upload in Production, my website works correctly but I am having an error PAGE NOT FOUND when I try to add/save a blog in Django Admin. It throws an error Page not found. What can I do? -
django static files error 400 - aws lightsail
I followed amazon docs on how to Deploy A Django Project My settings.py DEBUG = False ALLOWED_HOSTS = ['X.XXX.XXX.XXX'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'HOST': 'localhost', 'PORT': '5432', 'USER': 'postgres', 'PASSWORD': 'mypass' } } STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'cms/static') ] I used 'Host': 'localhost' because 'HOST': '/opt/bitnami/postgresql/', gives me this error which I have asked a question about here: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/opt/bitnami/postgresql/.s.PGSQL.5432/.s.PGSQL.5432"? and python manage.py collectstatic --noinput works fine just like in my laptop. I added static root in urls.py: urlpatterns = [ path('', include('myapp.urls')), . . ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) under /opt/bitnami/apache2/conf/vhosts I created two files: cms-http-vhost.conf : <IfDefine !IS_CMS_LOADED> Define IS_CMS_LOADED WSGIDaemonProcess cms python-home=/home/bitnami/py37-venv/ python-path=/home/bitnami/project/cms </IfDefine> <VirtualHost 127.0.0.1:80 _default_:80> ServerAlias * WSGIProcessGroup cms Alias /robots.txt /home/bitnami/project/cms/static/robots.txt Alias /static/ /home/bitnami/project/cms/static/ <Directory /home/bitnami/project/cms/static> Require all granted </Directory> WSGIScriptAlias / /home/bitnami/project/cms/cms/wsgi.py <Directory /home/project/cms/cms> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> and cms-https-vhost.conf: <IfDefine !IS_CMS_LOADED> Define IS_CMS_LOADED WSGIDaemonProcess cms python-home=/home/bitnami/py37-venv/ python-path=/home/bitnami/project/cms </IfDefine> <VirtualHost 127.0.0.1:443 _default_:443> ServerAlias * SSLEngine on SSLCertificateFile "/opt/bitnami/apache2/conf/bitnami/certs/server.crt" SSLCertificateKeyFile "/opt/bitnami/apache2/conf/bitnami/certs/server.key" WSGIProcessGroup APPNAME Alias /robots.txt /home/bitnami/project/cms/static/robots.txt Alias … -
Mysql key specification on ALTER TABLE
I have this code that was handed down to me with engine.connect() as con: con.execute('ALTER TABLE `mystuff` ADD PRIMARY KEY (`index`);') But I get the following error '(1170, "BLOB/TEXT column 'index' used in key specification without a key length")' [SQL: CREATE INDEX ix_mystuff_index ON mystuff (index)] -
How do I add users to access to the postgres apart from the admin using django
How to add users to the postgres users in pgadmin4 on django server, beside the admin user? Example: A website is created where there is a login button to enter into the website. The admin has the access to it by creating a python manage.py createsuperuser but If I want to add another users to access to the site how should i add them ? -
How to limit Simultaneous logins in Django Rest auth
I have a project that has a custom user model extended by AbstractBaseUser and for login I'm using an endpoint provided by django rest auth (rest-auth/login). So my question is how can prevent same user is login with another device. I need to display somethin like "You have already logged in" when a user tries to login with another device while he logged into the system Thanks! -
How to get data dictionary based on Django models?
Just wonder how to get the whole data dictionary(markdown or html or text) based on the all Django models. Like this #### payinfo | field | type | default | comment | | --- | --- | --- | --- | | id | int(11) | None | id | | school | varchar(32) | None | school | | com_id | varchar(32) | None | com_id | | remark | varchar(50) | None | remark | | status | int(11) | None | status | | company_id | int(11) | None | company_id | | php_path | varchar(32) | None | php_path | -
getting error while postgres connecting to Django
madhu@DESKTOP-9CAUDPK:/mnt/f/backup/PycharmProjects/Ecommerce/ecommerce$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/home/madhu/.local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/madhu/.local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/madhu/.local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/madhu/.local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/madhu/.local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/home/madhu/.local/lib/python3.8/site-packages/psycopg2/init.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "madhu" FATAL: password authentication failed for user "madhu" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/madhu/.local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/madhu/.local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/madhu/.local/lib/python3.8/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 49, in init self.build_graph() File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/home/madhu/.local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/madhu/.local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, … -
NoReverseMatch at / Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['posts/(?P<pk>[0-9]+)/$']
I'm building a django blog app. But, when I'm trying to build detail pages for blog posts, I'm getting this error: NoReverseMatch at / Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['posts/(?P<pk>[0-9]+)/$'] This is my post_detail view function: def post_detail(request,post_id): post = get_object_or_404(Post, id=post_id) return render(request, 'blog/detail.html',{'post':post}) My url route: path('posts/<int:post_id>/',views.post_detail,name='detail'), And the line that links to detail page: <p class="lead my-3"><a href="{% url 'blog:detail' post.id %}" class="text-white font-weight-bold">{{ latest_post.title }}</a></p> I don't think I should have any error in this. Where am I going wrong? -
how to use django-import-export in DRF?
The result of installing import-export and importing from the admin page I got the following error How can I fix it? error : Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\import_export\resources.py", line 639, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\ProgramData\Anaconda3\lib\site-packages\import_export\resources.py", line 334, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\ProgramData\Anaconda3\lib\site-packages\import_export\resources.py", line 322, in get_instance self.fields[f] for f in self.get_import_id_fields() File "C:\ProgramData\Anaconda3\lib\site-packages\import_export\resources.py", line 322, in self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' enter code here admin.py from django.contrib import admin from .models import Country from import_export.admin import ExportActionModelAdmin, ImportExportMixin, ImportMixin @admin.register(Country) class CountryAdmin(ImportExportMixin, admin.ModelAdmin): list_display = [ "country_ID", "iso_code", "cname_en" ] -
How can I get the Django auth SetPasswordForm to display errors?
I am using Django's SetPasswordForm to allow the user to reset their own password.They will have been sent an email and clicked on a link which directs them to: /users/new-password/uid/token urls.py path('new-password/<uidb64>/<str:token>/', views.NewPassword.as_view(), name='new-password'), views.py class NewPassword(View): url = 'users/new_password.html' def get(self, request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is None or not account_activation_token.check_token(user, token): text = 'Your password cannot be reset. Please contact support.' messages.error(request, text) return HttpResponseRedirect(reverse('account')) password_form = SetPasswordForm(user=user) context = { 'password_form': password_form, 'uidb64': uidb64, 'token': token, } return render(request, 'users/new_password.html', context) def post(self, request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) password_form = SetPasswordForm(user=user) if not password_form.is_valid(): context = { 'password_form': password_form, 'uidb64': uidb64, 'token': token, } return render(request, self.url, context) messages.success(request, 'Your password has been reset. You may now sign in.') return render(request, reverse('login'), context) new_password.html <form method="post" action="{% url 'new-password' {{ uidb64 }} {{ token }} %}"> {% csrf_token %} <h1>Set New Password</h1> <table> {% for field in password_form %} <tr> <td>{{ field.label_tag }}</td> <td>{{ field }}</td> {% if field.errors %} {% for error in field.errors %} <td style="color: red">{{ error }}</td> {% endfor %} {% endif %} </tr> … -
Synchronize Django DB with Ionic Client
I have a model in my django project hosted on Google Cloud Projects. Which looks like the one below. class License(models.Model): PLATFORM_CHOICES = ( ("ios", "iOS"), ("android", "Android"), ) LICENSE_CHOICES = ( ("prod", "Production"), ("dev", "Development"), ) license = models.TextField() created_dt = models.DateTimeField(auto_now_add=True) expiration_dt = models.DateTimeField() license_type = models.CharField(max_length=11, choices=LICENSE_CHOICES) platform_type = models.CharField(max_length=7, choices=PLATFORM_CHOICES) I am using this model with a serializer to retrieve the data using an Ionic+Angular client. This license is used to activate a service, and this licenses change every X days. I do not want to check on every request whether the key is not expired or fetch the key everytime the service is being used. I want to save this key on local storage, and save automatically on local storage every time a new value is created or updated in the database. How can I make this possible? I am trying to avoid to do something like this: this.sharedService.getLicense().subscribe(licenses => { var todaysDate = new Date(); licenses.map(license => { if (this.platform.is('ios') && todaysDate <= new Date(license.expiration_dt)) { this.licenseKey = license; } }); }) Any ideas will be much appreciated. -
Django Rest Framework Datatables DELETE
Issue I would like to send a list of ID's to the Django Rest Framework API url (which is the rest_framework routers default). So far everything is working up to the point of sending the ID's. When I click the delete button the DELETE call goes to 127.0.0.1:8000/api/entries/_id_/ and does not add the proper ID's that are selected for deletion. Error Message From Server I'm sure this was more or less obvious: {detail: "Not found."} detail: "Not found." entry_list.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} <style> table.dataTable tbody tr.odd.selected { background-color:#acbad4 } table.dataTable tbody tr.even.selected { background-color:#acbad5 } </style> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2> <a role="button" class="btn btn-success" href="{% url 'import' %}"><i class="fas fa-plus-circle"></i> Import New Entires</a> </div> <button id="countbutton">Count rows</button> <button id="deletebutton">Delete rows</button> <!-- Content Row --> <div class="row"> <div class="col-md-12"> <table id="entrytable" class="table-hover table display table-bordered" align="center" style="width:100%"> <thead> <tr role="row"> <th>id</th> <th>date</th> <th>amount</th> <th>price</th> <th>fee</th> <th>entry_type</th> <th>reg_fee</th> <th>transaction_id</th> <th>trade</th> <th>symbol</th> <!-- <th>created_by</th>--> </tr> </thead> </table> </div> </div> {% endblock %} {% block js %} <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css"/> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css"/> <!--https://datatables.net/examples/server_side/select_rows.html--> <!--<link rel="stylesheet" type="text/css" … -
Django Websockets Data going to the wrong Socket
Using Django Websockets + Channels, I create a (One) group and the message back and forth works just fine. Lets call this Group A The problem starts when I open a SECOND group and a SECOND (Lets call this group B) WebSocket connection in a different browser. The messages that I am trying to send to group A (first WebSocket connection), are going to group B (second WebSocket connection). All the messages that belong to group A go to the second WebSocket and the group B messages also go to the second socket. Here's my consumer.py import json from asgiref.sync import async_to_sync import logging LOG = logging.getLogger(__name__) from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer class EventConsumer(AsyncWebsocketConsumer): async def connect(self): self.id = self.scope['url_route']['kwargs']['id'] self.group_name = f'enl_events_log_{self.id}' # Join room group await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): # text_data_json = json.loads(text_data) # message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.group_name, { 'type': 'send.message', 'message': "Message received" } ) # Receive message from room group async def send_message(self, event): message = event['message'] # Send message to WebSocket await … -
how to send and retrive image in django with ajax?
I need to upload an image in the server without using the django models.and also i needs to do with the help of ajax. My html code: <form id='imform' action="#" method="GET" role="form" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img" multiple> <input type="submit" value='submit'> </form> My ajax code: $("#imform").submit(function (event) { event.preventDefault() var idata=new FormData(); idata.append('one','one'); console.log(idata['one']); $.ajax({ type:'GET', url: 'imageupload', data:{ one:'one', img:idata, }, contentType:false, success: function (e) { console.log('success') }, }); }); In views.py: def imageupload(req): ???????????? How to get the image in the function?Is there any way to get the image and save in a specific folder in the server. -
I want to run my django app from my own computer's server. How can I do that?
Suppose my public IP address is x.x.x.x.x If I want to access my django app with that IP address how can I do that? -
Not able to add value to Foreign Key using Django models
I have created 2 models, Customer and Room. class Customer(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) age = models.IntegerField() sex = models.CharField(max_length=10) phoneno = models.IntegerField() emailid = models.CharField(max_length=25) address = models.CharField(max_length=50) children = models.IntegerField() adults = models.IntegerField() roomtype = models.CharField(max_length=10) aadharno = models.CharField(max_length=15) roomno = models.OneToOneField(Room,on_delete=models.CASCADE) daysstayed = models.IntegerField() date_visited = models.DateTimeField(default=timezone.now) emp_id = models.ForeignKey(Employee,on_delete=models.SET_NULL,blank=True,null=True) class Room(models.Model): roomno=models.IntegerField(default=0) roomtype=models.CharField(max_length=15) vacancy=models.BooleanField(default=False) current_user=models.OneToOneField('customer.Customer',on_delete=models.SET_NULL,blank=True,null=True) I am using the following code to insert values in the Customer model. customer = Customer(firstname=firstname,lastname=lastname,age=age,emailid=emailid,address=address,phoneno=phoneno,children=children, adults=adults,roomtype=roomtype,aadharno=aadharno,daysstayed=daysstayed,sex=sex,roomno=i.roomno.id) customer.save() All the values are obtained using a form except for roomno. I get the following error when i use roomno=i.roomno.id 'int' object has no attribute 'id' when i use roomno=i.id I get the error Cannot assign "7": "Customer.roomno" must be a "Room" instance. where i is an instance of room and 7 is the value to be added. -
Django: Annotate with field from another table (one-to-many)
Good day. I wish to annotate my model with information from a different table. class CompetitionTeam(models.Model): competition_id = models.ForeignKey('Competition', on_delete=models.CASCADE, to_field='id', db_column='competition_id') team_id = models.ForeignKey('Team', on_delete=models.CASCADE, to_field='id', null=True, db_column='team_id') ... class Team(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) teamleader_id = models.ForeignKey('User', on_delete=models.CASCADE, to_field='id', db_column='teamleader_id') ... class Competition(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) ... Looping through my competitions, I wish to retrieve the list of competitionteam objects to be displayed with the relevant team's name. I tried: CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=...) -where instead of the ellipses I put Subquery expressions in. However, I'm unsure of how to match the team_id variable. eg. *.anotate(name=Subquery(Team.objects.filter(id=competitionteam.team_id)).values('name')) Related is the question: Django annotate field value from another model but I am unsure of how to implement that in this case. In that case, in place of mymodel_id, I used team_id but it only had parameters from the Team object, not my competition team object. I didn't really understand OuterRef but here is my attempt that failed: CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=Subquery(Team.objects.get(id=OuterRef('team_id')))) "Error: This queryset contains a reference to an outer query and may only be used in a subquery." -
Installation failed of resume-parser 0.6 Package in system
I tried to install this package but it didn't install on my system. Then trying from virtual environment but same things happen. -
Group object has no attribute user_set
I'm using a custom User created with AbstractBaseUser and I tried to add users to a specific group using the django admin. But there were no option to add users to a group. So I found a solution from the stack overflow and It gave me the capability to add users to the group I created. But after saving the user It gives me an error saying Group object has no attribute user_set My User Model class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have an username") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=80, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) phone_no = models.CharField(max_length=12,null=True) date_joined = models.DateField( verbose_name='date joined', auto_now_add=True) last_login = models.DateField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return …