Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django let's me save a model correctly via admin but not form/shell
I am having difficulty saving a Django model instance into my db. The instance consists of a FileField, which I think is what is causing the difficulty. My model is as follows: class initial_settings(models.Model): name = models.CharField(max_length=30, unique=True) epsilon = models.FloatField(default = 0.3) document = models.FileField(upload_to='documents/') def __str__(self): return self.name And when I open up a shell, create an instance, and save, I then run the command test = initial_settings(name = 'test1234', epsilon = 3, document = 'doc.csv').save() pd.DataFrame(csv.reader(open(test.document.path, 'r'))) Gives me an error, No such file or directory . But, if I open up the admin console and create an instance, it saves correctly and I am able to load it from shell. In the admin console, I can see that the instance created in shell is not being saved to the correct location ('media/documents') but instead direct to root dir, but I am not sure why. Any assistance is appreciated! P.S: Settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
How to make a button send data to a django function with ajax
What I am trying to do is create an html button that grabs data from the page and sends it to a django function. The button is not linked to a form or anything. I am relatively new to django and I have tried a billion different approaches to this problem with no success. Any suggestions would be greatly appreciated. -
Django - Fastest way to query multiple primary keys in order to create a list of model attribute and uuid to return?
So I have a functionality that should return a list of a user's followers, with the uuid and follower username. The reason the User username isn't the PK is because I'm using amplify and it returns a UUID for user id. As you can see below I'm just querying for all followers of a user then doing a for loop to get each followers user name and creating a dict with uuid and username that goes into a list. I have concerns this will be pretty slow. Is there a quicker way to do this? Model.py class AbstractBaseModel(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) class Meta: abstract = True def __repr__(self): return f'<{self.__class__.__name__} {self.uuid}>' class User(AbstractBaseModel): username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) class FollowUser(AbstractBaseModel): follower_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower_following") followee_id = models.OneToOneField(User, on_delete=models.CASCADE, related_name="followee_followed_by") View.py @api_view(['GET']) def get_followers(request, followee_id): try: followers = FollowUser.objects.filter(followee_id=followee_id).values_list('follower_id', flat=True) followers_list = list(followers) data = list() for follower_uuid in followers_list: try: username = User.objects.get(pk=follower_uuid).username except User.DoesNotExist: return Response(dict(error=f'follower id: {follower_uuid} does not exist in User model'), status=status.HTTP_400_BAD_REQUEST) data.append(dict(username = username, id = follower_uuid)) response_data = dict(followers=data) return JsonResponse(response_data, status=status.HTTP_200_OK) except FollowUser.DoesNotExist: return … -
Static files like JS not loading on Elastic Beanstalk Python 3.8
I am currently leaning to code and am trying to deploy a Django project using elastic beanstalk. I have added these lines of code to .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myapp.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /media: /media /static: /myapp/static And container commands container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true 02_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic" option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: myapp.settings I have already created superuser, so I removed the line that creates one. I deployed with these files, but my app on production server is ugly because static files are not loading. This screenshot is the login page of django admin. And these are error messages that say it couldn't find any static files. Here's my configuration on EB console Thank you in advance. -
Django Unique Key on M2M Table
Is there a way to tell Django to create unique key based on a M2M relation? I have the following table and I want the host_id and hostname_id pair to be unique. Table (app_host_names) id host_id hostname_id models.py class Hostname(models.Model): name = models.CharField(max_length=150, unique=True, blank=False, null=False) class Host(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) names = models.ManyToManyField(Hostname) -
Why can't I use projectname.file to import
I add a custom_site.py in my project, But I can't import it in admin.py and urls.py. I try to use sys, and use Pycharm to mark them as Sources Root, but it still can't import! It always Report an error like: from typeidea.custom_site import custom_site ModuleNotFoundError: No module named 'typeidea.custom_site' Why typeidea.custom_site can't import? I wonder. My project directory and my code are here: admin.py urls.py custom_site.py Project directory NEED HELP!!! Please help me as much as possible! The sooner the better! THANK YOU VERY MUCH! -
Creating a Jira issue through OAuth 2.0 (3LO) app fails with the error {"code":401,"message":"Unauthorized"}
I’m an intern developer and I’m integrating a product with the Jira software (cloud). I’m using python and Django web frameworks for development. I followed the https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/ documentation and successfully received the access token. The steps I followed are: Created an OAuth 2.0 (3LO) app in the developer console. Configured permissions for ‘Jira platform REST API’ and ‘User identity API’. I selected the rotating refresh tokens option. Added the callback URL as ‘http://localhost:8000/callback’ Direct user to authorization URL to get the authorization code. In the Authorization URL scope is defined as follows: scope = ['write:jira-work read:jira-user read:me read:jira-work'] As the response receives the code and state variables. Exchanged the code value to the access token. The received response is as follows: {"access_token":"token value appears here","scope":"write:jira-work read:jira-work read:jira-user read:me","expires_in":3600,"token_type":"Bearer"} Successfully received the clould_id using the access token. header = {'Authorization': 'Bearer {}'.format(client.token['access_token']), 'Accept': 'application/json'} response = requests.get('https://api.atlassian.com/oauth/token/accessible-resources', headers=header) Retrieved the public profile of the authenticated user successfully. response = requests.get('https://api.atlassian.com/me', headers=header) When I tried to create an issue, it ends up with the following error: {"code":401,"message":"Unauthorized"}. I’m referring to https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issues/#api-rest-api-3-issue-post I am using email (logged-in user email) and API token to authorize. Is there any problem with my auth parameter? It … -
why is django running extra queries (session, auth, time)
I'm trying to optimize my django queries using django-debug-toolbar My actual query is just a simple getter as you can see as the 4th one in this list: QUERY = 'SELECT SYSDATETIME()' - PARAMS = () 15.89 QUERY = 'SELECT TOP 21 [django_session].[session_key], [django_session].[session_data], [django_session].[expire_date] FROM [django_session] WHERE ([django_session].[expire_date] > %s AND [django_session].[session_key] = %s)' - PARAMS = (datetime.datetime(2021, 8, 21, 2, 24, 45, 234137), 'xx') QUERY = 'SELECT TOP 21 [auth_user].[id], [auth_user].[password], [auth_user].[last_login], [auth_user].[is_superuser], [auth_user].[username], [auth_user].[first_name], [auth_user].[last_name], [auth_user].[email], [auth_user].[is_staff], [auth_user].[is_active], [auth_user].[date_joined] FROM [auth_user] WHERE [auth_user].[id] = %s' - PARAMS = (30,) 15.87 QUERY = 'SELECT [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type]' - PARAMS = () However, just for that getter it's taking 50ms because of the first 3 queries. The individual time taken are: 15ms 16ms 15ms 8ms Is there some setting I can use to optimize this or remove these queries? -
NotImplementedError: `create()` must be implemented
If you see here, please stay. Thank you very much report errors:NotImplementedError: create() must be implemented. this's my class: class BookCreateView(CreateModelMixin, GenericAPIView): serializer_class = BookSerializer def post(self, request): return self.create(request) But there are already crate() out of CreateModelMixin So why does it report an error? -
Multiple processes spawning by Supervisorctl and stopping is not killing all of them
My supervisor config to start the django process is- [program:school] command=/usr/bin/python3 /home/pranavtotala48/blue_mountain/manage.py runserver 0.0.0.0:80 stdout_logfile=/home/pranavtotala48/supervisor_logs/logs.log directory=/home/pranavtotala48/blue_mountain user=root autostart=true autorestart=true stopsignal=QUIT On Starting the Supervisor school program, two python processes are started. And stopping the supervisor program only kills one process. Page up pranavtotala48@instance-2:~$ ps aux | grep 80 root 80 0.0 0.0 0 0 ? I< Aug20 0:00 [kblockd] root 324 0.0 0.4 280208 17996 ? SLsl Aug20 0:06 /sbin/multipathd -d -s systemd+ 421 0.0 0.1 26612 7480 ? Ss Aug20 0:00 /lib/systemd/systemd-networkd daemon 590 0.0 0.0 3800 2292 ? Ss Aug20 0:00 /usr/sbin/atd -f root 733 0.0 0.4 928352 18028 ? Ssl Aug20 0:04 /usr/bin/google_guest_agent _chrony 1325 0.0 0.0 4696 180 ? S Aug20 0:00 /usr/sbin/chronyd -F -1 root 9013 0.0 0.2 13808 9040 ? Ss 00:46 0:00 sshd: pranavtotala48 [priv] pranavt+ 9250 0.0 0.0 8168 732 pts/0 R+ 01:13 0:00 grep --color=auto 80 pranavtotala48@instance-2:~$ pranavtotala48@instance-2:~$ sudo supervisorctl start school school: started pranavtotala48@instance-2:~$ ps aux | grep 80 root 80 0.0 0.0 0 0 ? I< Aug20 0:00 [kblockd] root 324 0.0 0.4 280208 17996 ? SLsl Aug20 0:06 /sbin/multipathd -d -s systemd+ 421 0.0 0.1 26612 7480 ? Ss Aug20 0:00 /lib/systemd/systemd-networkd daemon 590 0.0 0.0 3800 2292 … -
Utilizing a Django slug, getting a no reverse path error
My apologies if you've already read a previous post I made about my Django slug problem. I cleaned up my old code, and perhaps have a better understanding of what I'm doing but I'm still lost as how to get a URL generated from a slug to work on my main landing page. I'm working on a portfolio. I have a landing page where I'm going to link out to individual detail pages. I'm using get_absolute_url in my models to do this. When testing this out, I can get the link to work on the individual project detail page, but not on the main landing pages. Which is funny, because I don't need these links to work on the individual project pages. My guess is that something in my views is not set up correctly. My views.py is set up like this: from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import Project def home(request): projects = Project.objects.all() return render(request, 'portfolio/home.html', {'projects': projects}) def individual_project_view(request, project_id): projectpage = get_list_or_404(Project, slug=project_id) return render(request, 'portfolio/project_detail.html',{'projectpage':projectpage}) def project_home(request): portfolioprojects = get_list_or_404(Project) return render(request, 'portfolio/project_detail.html', {'portfolioprojects':portfolioprojects}) And here is my urls.py for the individual landing pages, which are in a separate app. from django.contrib import … -
Django builtin url 'logout' reverse URL is returning a relative path
Been searching but can't find this specific issue. I created a separate app for my user authentication (name: user) and included the URLS using django.contrib.auth.urls. Login works. Logout fails. When using the named view {% url 'login' %} the path is absolute, and works fine (i.e. http://host/user/login). When using the named view {% url 'logout' %} in the same template, it gets a relative path to my displayed app. (i.e. http://host/app1/user/login) Django Directory: - djangoProject - djangoProject - app1 - user Django app settings (djangoProject/settings.py): INSTALLED_APPS = [ 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'user', 'app1', ] Django app URLS (djangoProject/urls.py) urlpatterns = [ path('app1/', include('app1.urls')), path('admin/', admin.site.urls), path('user/', include("django.contrib.auth.urls")), path('user/', include("user.urls")) // in case I add custom pages ] User App URLS (user/urls.py - nothing added, as using from django.contrib.auth.urls): urlpatterns = [ ] User App Views (user/views.py - nothing added. using built in django.contrib.auth): Now, in app1/templates/base.html, I use the following: {% url 'login' %} - which generates the URL - http://host/user/login/ {% url 'logout' %} - which generates the URL - http://host/app1/user/logout If I manually enter the URL http://host/user/logout I get logged out and redirected correctly. Any thoughts? Thanks so much! -
Django Need help no such table: network_profile
I am currently working on a Django Project and having the error as in operational error as no such table network_profile. I have tried everything run syncdb and make migrations and run migrate and so on but I am still having this error is there anyway someone can help me. Picture 1 Picture 2 Let me know if you want any information below. Thank You! -
Unregister a viewset from drf router
I have two separate apps Product and Tag which i used another app Product_tags to connect them together. in this way, if one of them don't exists, another one will work fine. inside Product_tags, I created a new TagProductSerializer which inherits ProductSerializer and I just added a new field named tag in fields list. product_tags/serializers.py: class TagProductSerializer(ProductSerializer): tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all()) class Meta: model = Product fields = [ 'title', 'tags', ] #... and I did the same with Product viewsetproduct_tags/views.py class TagProductViewset(ProductViewset): serializer_class = SocialProductSerializer and in my product_tags/urls.py I imported my Product router and i wanted to register my product viewset again for router. and there is my problem: product/urls.py router = routers.DefaultRouter() router.register('product', ProductViewset) urlpatterns = [ path('', include(router.urls)), ] product_tags/urls.py (PROBLEM) from product.urls import router from .views import TagProductViewset router.unregister('product') # I'm looking for something like this router.register('product',TagProductViewset) NOTE: I want to show the tags when getting product and because of that, I don't want to use different url for getting tag (e.g "api/product/tags/") First Try:I tried to register the 'product' again (router.register('product',SocialProductViewset)) but it doesn't works -
Forbidden error When deploying Django App with Apache
I'm trying to deploy my Django project using Apache + mod-wsgi, but it occurred a 403 error which I'm unable to solve. I've substituted the 000-default.conf file to a custom file named Qxt_project.conf in /etc/apache2/sites-available/ Alias /static /home/scodasso/Qxt_project/static <Directory /home/scodasso/Qxt_project/static> Require all granted </Directory> Alias /media /home/scodasso/Qxt_project/media <Directory /home/scodasso/Qxt_project/media> Require all granted </Directory> <Directory /home/scodasso/Qxt_project/django_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/scodasso/Qxt_project/django_project/wsgi.py WSGIDaemonProcess django_app python-path=/home/scodasso/Qxt_project python-home=/home/scodasso/Qxt_project/venv> I've checked and everything points towards the right folder. When I check apache2 errors.log with "sudo tail -100 /var/log/apache2/error.log" I get: import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/scodasso/Qxt_project/venv' sys.base_exec_prefix = '/home/scodasso/Qxt_project/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/scodasso/Qxt_project/venv' sys.exec_prefix = '/home/scodasso/Qxt_project/venv' sys.path = [ '/home/scodasso/Qxt_project/venv/lib/python39.zip', '/home/scodasso/Qxt_project/venv/lib/python3.9', '/home/scodasso/Qxt_project/venv/lib/python3.9/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fb0b30a9d40 (most recent call first): <no Python frame> [Fri Aug 20 22:05:49.134562 2021] [wsgi:warn] [pid 1495344:tid 140396894788928] (13)Permission denied: mod_wsgi (pid=1495344): Unable to stat Python home /home/scodasso/Qxt_project/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for the whole of the path. Python path … -
Querying a Parent object based on a Child M2M's own M2M relationship
I have two types of objects, one is a parent and one is a child: class Parent(models.Model): children = models.ManyToMany(Child) class Child(models.Model): compatable_children = models.ManyToMany("self") I use the Parent object to display in my application, but I need to filter it based on the existence of a child within the compatable_children field. So something like: filter_child = Child.objects.filter(id=blah) queryset = Parent.objects.filter(children__compatable_children__contains=filter_child) How can I achieve something like this query? -
Django application on AWS ECS Fargate keeps restarting after several hours of running successful
I am hosting a Django app on AWS ECS Fargate and I noticed it keeps on restarting after a random number of hours. It runs between 4- 48 hours before restarting. When I check the Event logs of the ECS Task I can see that it is due to health check failure. I have tried everything I know to stop it from restarting, it seems health check failure happens at random after the application has already passed health checks.what can I do to resolve this. Note: The Django app is not running with Nginx reverse proxy, it uses gunicorn wsgi and whitenoise to serve static files. The gunicorn uses one worker with the gthread worker type I also have a similar set on flask but the flask seems to have no issues so I am thinking it’s a Django related issue The Django app also logs a lot of 404 Not Found errors to the cloud watch logs. Any help on this would be appreciated. -
AttributeError: 'ManyToManyDescriptor' object has no attribute 'remove'
I'm trying to make a liking system with LikeView and BlogDetails such as if I like it and then click again I disliked it def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): Post.likes.remove(id=request.user.id) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse_lazy('blog-detail', args=[str(pk)])) class BlogDetails(DetailView): model = Post template_name = 'blog_details.html' def get_context_data(self, *args, **kwargs): categories = Category.objects.all() context = super(BlogDetails, self).get_context_data(*args, **kwargs) context['categories'] = categories liked = False stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() context['likes'] = total_likes if stuff.likes.filter(id=self.request.user.id).exists(): Liked = True context['liked'] = liked return context and it shows an AttributeError: 'ManyToManyDescriptor' object has no attribute 'remove' -
Dockerized Django APP with PostgreSQL does not work
As in title i have an issue, my dockerized app does not work. There is problem with the port. PostgreSQL works fine during development and creating models. I have no idea it changes something but I develop this app in python virtual env. DB settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fitshop', 'USER': 'fitshopuser', 'PASSWORD': 'fitpass', 'HOST': 'localhost', 'PORT': '5432', } } Dockerfile: FROM python:3 RUN adduser --system --no-create-home django ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /django/app RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r ./requirements.txt COPY . . EXPOSE 8000 USER django CMD ["python", "manage.py", "runserver"] ERROR: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? -
How Can I Sum Django Models Field by Dates and Display Totals base on Current Month and Year
I am a novice in python Django framework and I wish someone should please help on some piece of code I have been struggling with hours. I have an Expenditure Model with date and amount Fields among others, and I want to calculate total amount for the current month and display in django template through the views using the context dictionary. Here is my Expenditure model code: class Expenditure(models.Model): amount = models.PositiveIntegerField(null=False) date = models.DateField(auto_now_add=False, auto_now=False, null=False) Views.py codes here: from django.db.models import Count, Sum from django.db import connection def index(request): truncate_month = connection.ops.date_trunc_sql('month','day') total_income = Income.objects.extra({'month': truncate_month}).values('date').annotate(Sum('amount')) context = { 'total_income':total_income, } return render(request, 'dashboard/index.html', context) This is how I am trying to display the Sum Total of amount for the current month and year in Django template. {% for income in total_income %} {{income.date}}{{income.amount}} {% endfor %} The result of my code above is displaying the months of dates from the Expenditure Model on the template. Your kind assistance would help a lot. Thanks -
Select multiple rows from database in views.py and send it as array to html page - Django
I want to select multiple rows in database in Django view and send it as an array to my html page. views.py def report_template(request, pk): template_list = AddScore.objects.filter(template_name=pk) context = {'Template': template_list} return render(request, 'myapp/report_template.html', context) models.py class AddScore(models.Model): score = models.CharField(max_length=100, primary_key=True, default='', blank=True) client_name = models.CharField(max_length=300, blank=True) template_name = models.CharField(max_length=100, blank=True) I want the result like - data = [ ['client_name1', '37.54'], ['client_name2', '33.54'] ]; -
How do I enable the 'trimmed' policy in Jinja2?
I am trying to enable the trimmed keyword for all {% trans %} blocks in Jinja2. I have added env.policies['ext.i18n.trimmed'] = True (found here: https://jinja.palletsprojects.com/en/3.0.x/api/#policies) in my environment configuration, but nothing happens. In my project I am using Babel with Jinja2 and Django to extract messages. Here is my environment configuration: def environment(**options): env = Environment( **options, extensions=[ 'compressor.contrib.jinja2ext.CompressorExtension', 'jinja2.ext.autoescape', 'sass_processor.jinja2.ext.SassSrc', 'jinja2.ext.i18n', ] } env.policies['ext.i18n.trimmed'] = True env.install_gettext_callables(gettext=gettext, ngettext=ngettext) env.globals.update(globals) env.filters.update(filters) return env -
How do I fix a 504 gateway timeout error?
My web application (Django + Nginx) calls another url in the backend. As it takes time like 15-20 minutes to get whatever from the other site, I am running into the 504 Bad Gateway error. Before I encrypted my website, I added the following commands to /etc/nginx/nginx.conf and it worked. proxy_connect_timeout 1800; proxy_send_timeout 1800; proxy_read_timeout 1800; But now my website is transferred from http to https. It does not work any longer. I googled but did not find a solution. Can anybody kindly help with this? Thanks. -
Registration form not saving new users in django
I am following a tutorial and I made my user registration view but it's not saving the user either giving any error. Below is my view file from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('waqart-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) -
xhtml2pdf using border-radius css
I'm looking to create a PDF through xhtml2pdf python package on a Django environment but it seems not possible to add a border-radius to a div :( Do you know other packages in python to do this job ?