Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving static images in Django development
this is a commonly asked question so I am not sure why I can't get this to work. Foremost, here is the file structure of my project: -blog -templates - - about.html -media -static - -css - -img - - profile_pic - -js ... I have gone through the process of configuring my settings.py to serve static files during development by adding the following: STATIC_URL = '/static/' and STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static',), ] into my settings.py file. In my about.html, I place the {% load static %} tag at the top of the page, then I attempt to load my image by calling the tag like so: <img class = "card-img-top" src="{% static 'img/profile_pic'%}" alt="My profile picture"> Nothing appears. The logs state "GET /static/img/profile_pic HTTP/1.1" 404 1671 So the file isn't loading at all. Could this be a problem with my filepaths? -
How to specify the user in the blog post in django?
I'm quite new in django, and here is my question: I have a django model (like posts in blog with a form) -> class Product(models.Model): asset_name = models.CharField(verbose_name='Название актива', max_length=50) asset_sector = models.CharField(verbose_name='Отрасль', max_length=50) asset_price = models.DecimalField(verbose_name='Цена', max_digits=10, decimal_places=2) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and here is field called author, I have an authorization and i need the next: when the user add his post, the post would automatically choose the author (current user) Now my model don't add anyone, just give the possibility to choose here to see the screenshot of django admin imports: from django.db import models from backend import settings model of User class CustomUser(AbstractUser): balance = models.DecimalField(max_digits=10, decimal_places=1, null=True, default=0) email = models.EmailField(blank=True, null=True) username = models.CharField(unique=True, max_length=150) USERNAME_FIELD = 'username' def __str__(self): return self.username form of adding the post class ProductForm(ModelForm): class Meta: model = Product fields = ['asset_name', 'asset_sector', 'asset_price', ] widgets = { "asset_name": TextInput(attrs={ 'class':'form-control', 'placeholder': 'Название актива', }), "asset_sector": TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Отрасль', }), "asset_price": NumberInput(attrs={ 'class': 'form-control', 'placeholder': 'Цена', }), } -
Building django web app which uses algorithms running on google colab
i wanted to create a Django web application on where i will put some ML algorithms and a user interface to make easy to upload pictures and videos ,and these algorithms gonna run on google colab. but the problem is that i don't know how to make my app interacts with google colab mostly that there is no api for this google service. if you have any idea which can help me , please don't hesitate -
Nginx https not redirecting on iphone and macos's browser chrome
I just screwed up with this problem for last 4 days and i posted about it on stackoverflow 3 times, no one couldn't solve the problem. I dont know if it is possible to solve. My server is working very well with https and redireting http to https when i type example.com. it is working on all devices except ios/macos. I don't know whats wrong with my configuration. Can anyone help me to fix this. this is my current configuration server { listen 443 ssl; server_name example.com www.example.com; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; ssl_certificate /etc/certs/example_com.crt; ssl_certificate_key /etc/certs/definesys.key; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://backend:80; } } # Redirext https server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by ssl server_name example.com; listen 80; return 301 https://$host$request_uri; } The isue only ios/macos. But if i try with this: https://www.example.com it works but i want whenever user type example.com it should always redirected to https and this is working very well on all device except apple device. My app is django and running on docker, with nginx and gunicorn. Can anyone help me to fix this? -
Celery Tasks in Chain Starting Out Of Order
I am trying to implement some celery chains/groups/chords using django 3.0, celery 4.3, redis and python 3.6. From the documentation, I thought tasks in a group run in parallel, and tasks in a chain run sequentially, but I am not observing that behavior. I have this chain of task signatures: transaction.on_commit(lambda: chain(clean, group(chain(faces_1, faces_2), folder, hashes), change_state_task.si(document_id, 'ready')).delay()) where I expect the change_state_task to wait for all the other tasks to complete before it starts. This did not work, in that the change_state_task started before hashes finished. All the tasks ran and completed successfully. I then tried this chain: transaction.on_commit(lambda: chain(clean, faces_1, faces_2, folder, hashes, change_state_task.si(document_id, 'ready')).delay()) where all the signatures are in a long chain. However, the change_state_task is still starting before the hashes task finishes. I even tried using change_state_task.s(document_id, 'ready') (replaced si with s), thinking that the change_state_task could not start without the output of the hashes task. But it still starts before hashes ends. I then tried using task.s versus task.si for all the task signatures, and the change_state_task still started before the hashes task ended. What am I missing? Thanks! Mark -
How to create user status active deactivate toggle button in Django?
I want something like this in my Django . enter image description here Can anyone tell me how should I code in html template and views.py ? -
TemplateSyntaxError: Could not parse the remainder: '${id}' from '${id}'
I am trying to pass javascript variables into the URL template in my ajax call within my script tag but it keeps telling me that it could not parse the remainder. Any idea how it should be? $.ajax({ type: 'POST', url: `{% url 'posts:toggle-reaction' object_id=${id} object_type=${type} %}`, data: serializedData, success: function (response) { }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) -
Site matching query does not exist even. Everything is set, site domain defined
So i just want my sitemap.xml to work in production. I have included this module in INSTALLED_APPS: 'django.contrib.sites', I have declared SITE_ID: SITE_ID = 1 I defined domain name 'mydomain.com' in sites model which is exacly the domain my site running on. I restarted the server And i still get 'django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist' error I don't get this error when i run on localhost. -
django.core.exceptions.ImproperlyConfigured after using reverse()
I'm new in Django. Here is my issue. I'm trying to use reverse() function to add 'data-url' attribute to my form in my forms.py file in order to use it in my JavaScript then. But I run into the following exceptions: django.core.exceptions.ImproperlyConfigured: The included URLconf 'orthodontist.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import The thing is reverse() with the same url name works fine in my view.py file. Here is my code: forms.py class OrderByForm(forms.Form): order_by = forms.ChoiceField(required=False, choices=ORDER_BY, label='Сортировать по', widget=forms.Select(attrs={ 'class': 'form-control', 'data-url': reverse('ask:question_ajax') })) project urls from django.contrib import admin from django.urls import path, include from index import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index), path('signup/', views.signup, name='signup'), path('login/', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('user/<int:pk>/', views.UserView.as_view(), name='user'), path('user/<int:pk>/popular/', views.UserViewPopular.as_view(), name='user_popular'), path('user/<int:pk>/update/', views.UserViewUpdate.as_view(), name='update'), # path('user/<int:pk>/update_post', views.user_update_post, name='update_post'), path('admin/', admin.site.urls), path('search/', views.SearchResults.as_view(), name='search'), path('question/', include('ask.urls')), ] if bool(settings.DEBUG): urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app urls from django.urls import path from . import views app_name = 'ask' urlpatterns = [ path('', views.AskView.as_view(), name='index'), path('<int:pk>/', views.QuestionDetail.as_view(), name='question'), path('ask/', views.AskQuestionView.as_view(), name='ask_question'), path('<int:pk>/delete_question/', views.delete_question, name='delete_question'), path('<int:pk>/delete_answer/', … -
Custom @property used as APIField is displayed correctly but can't be used for ordering the results
I have a model for a Normal Wagtail page, which has two fields, and a custom property like this: class DetailPage(AbstractSitePage): total = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) additional_amount = models.DecimalField( max_digits=12, decimal_places=2, null=True, blank=True, default=Decimal("0.00") ) content_panels = [ FieldPanel("additional_amount"), ] + AbstractSitePage.content_panels api_fields = [ APIField("additional_amount"), APIField("total"), APIField("new_total") ] class Meta: ordering = ("-total",) @property def new_total(self): if self.additional_amount: return str(self.total + self.additional_amount) return str(self.total) doing so makes the following URL works just fine and displays the new_total values correctly /api/v2/pages/?type=sitepages.DetailPage&fields=additional_amount,new_total&order=-total but if I try to order with the new_total property /api/v2/pages/?type=sitepages.DetailPage&fields=additional_amount,new_total&order=-new_total isn't it supposed to work since it's already displayed and computed correctly?? and what can I do about this? -
Django wrong directories
My project has a core/template folder to place submit.html. I need to display some images. My project structure is like bellow: myproject static/images (my images) core/template (html files) I've also tryied core/template/images (jpg or png files) I've put some commands like these in settings file STATIC_URL = '/static/' MEDIA_URL = 'templates/images/' But it won't show up on submit.html page. I've tryied 3 ways for showing images but none will show them. This is what my terminal shows [21/Apr/2021 05:48:34] "POST /submit HTTP/1.1" 200 1054 [21/Apr/2021 05:48:34] "GET /static/images/coxinha.jpg HTTP/1.1" 404 1682 [21/Apr/2021 05:48:34] "GET /static/images/mini_coxinha.jpg HTTP/1.1" 404 1697 Not Found: /images/coxinha.png [21/Apr/2021 05:48:34] "GET /images/coxinha.png HTTP/1.1" 404 2230 -
Django problems loading static files
I am trying to add external JS file to my Django project. Unfortunately it doesn't work while I am trying to add it in many ways: In my template.html I have specified direct path: {% load static %} < script> src="{% static 'commerce/static/js/test.js' %}" < /script> it doesn't work. My settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] my layout.hmtl: {% load static %} <script src="{% static 'js/test.js' %}"></script> Depending on sources combination, I receive various output in terminal regarding status of loaded files: "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 304 0 "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 200 0 "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 404 0 Even if my 'test.js' is loaded correctly (HTTP status 200 or sometimes no information regarding test.js load status), my javascript functions doesn't work. In order to check if other static files are loaded I even tried to remove my CSS file from static folder and surprisingly (or not), after re-running my app it is still formatted. Although I left source for CSS unchanged in my layout.html: {% load static %} <link href="{% static 'css/styles.css' %}" rel="stylesheet"> Summarizing: I cannot manage … -
Django: No ReverseMatch. How to reverse to the previous URL?
I have a model class Client and the URL for this model object is <local_server>/object_id/ Where object_id is the id of the object of model Client. Now, when I am at this URL, there is a button on the page called Add Installment to add the installment for that particular Client. When I click on this button it takes me to the following URL: <local_server>/object_id/add_installment Now if I add the new installment, it works fine. But the Add Installment page has two buttons, Add and Cancel. I want that If I click on Cancel it should get back to the following URL: <local_server>/object_id/ And for that I have the following template for adding installment, where you can see the Cancel button. installment_form.html {% extends "client_management_system/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content_section"> <form method="post"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Add New Installment</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-success" type="submit">Add Installment</button> <a class="btn btn-outline-danger" type = "submit" href="{% url 'client_details' object.id %}" >Cancel</a> </div> </form> </div> {% endblock %} In the Cancel button, client_details is the name of the URL <local_server>/object_id. I have written the object.id in that line, but when … -
Django only accepts base URL after deployed but not on local machine
My django URLs work just fine on local development, but only the base URL works deployed on a godaddy server. I'm running the django application through the cPanel Python Web Applications on Python 3.7.8 I know django is working and my code reaches a method in my views.py file when the URL is just www.mysite.com, for example wwww.mysite.com/page would yield a 500 error Views.py def index(request, *args, **kwargs): print("views.py in index()", request) return render(request, 'index.html') I use this method to route URLs through a react app I have, all of which works on local development. urls.py file for the project from django.contrib import admin from django.urls import path, include, re_path from django.conf.urls import url, include from rest_framework import routers from app import views from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import refresh_jwt_token from rest_framework_jwt.views import verify_jwt_token from django.views.generic import TemplateView router = routers.DefaultRouter() router.register(r'app', views.SessionView, 'app') router.register(r'project', views.ProjectView, 'project') urlpatterns = [ path('admin/', admin.site.urls), path('token-auth/', obtain_jwt_token), url(r'token-renew/', refresh_jwt_token), url(r'token-verify/', verify_jwt_token), path('api/', include(router.urls)), path(r'', include('app.urls')), path('', TemplateView.as_view(template_name = 'index.html')), #re_path('.*', TemplateView.as_view(template_name = 'index.html')), ] urls.py file for the app from .views import current_user, UserList, index from django.conf.urls import url from app import views urlpatterns = [ url(r'ViewSession/(?P<pk>[0-9]+)', index), path('ViewSessions', index), url(r'ViewProject/(?P<pk>[0-9]+)', index), … -
React JS: problem in receiving cookie with axios, which is received from JWT Django
First of all, I had made a POST APIView function using Django and added JWT token in it. This api is basically made for the login purpose. I can transfer all the details in it and recieve a cookie in return. class LoginView(APIView): def post(self, request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('user not found') if not user.check_password(password): raise AuthenticationFailed('Incorrect password') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'jwt': token } return response I used POST request using axios in react js and trying to recieve cookie too with the help of "withCredentials: true" yet unable to get the cookie. import React, { Component } from 'react'; import axios from 'axios'; class Login extends Component { state = { email: '', password: '', }; handleSubmit(event){ event.preventDefault(); axios({ method: 'post', url: 'http://127.0.0.1:8000/user/login ', withCredentials: true, data: { email: this.state.email, password: this.state.password } }) .then(data => console.log(data)); } handleChange(event){ const target = event.target; const value = target.value; const name = target.name; this.setState({[name]:value}) } render() { return ( <div> <h1>LOGIN</h1> <form onSubmit={this.handleSubmit.bind(this)}> <div> <label>Email: </label> <br … -
How to upload multiple images in a django model WITHOUT using a form?
I'm tryign to upload multiple images in a django model WITHOUT usign forms. I need to "populate" my db with images so I can show them in my frontend. These images are storage in a folder inside my project but I couldn't find a way to send them to my model. Any ideas about how I can make it? -
How to pre-populate django forms at CreateView
how can i prepopulate fields in django forms at create an instance with the fields from my profile model. say if my Profile model has a Charfield residence and in the registration i named a certain user's residence as say 'Cairo', I would like to know how i can go to fill in a form say a PostCreateForm and have the residence of a user get auto filled with Cairo and also make it non-editable. Such that if a form is asking for Post body and residence of the owner of the post, this logged in user will be able to just enter the post body details and at the post details view, he can view his posts with his residence attached to them. I have tried implementing the form = PostForm(initial={"residence": "Cairo"}) kind of approach as per the documentation but i'm still getting it wrong. I tried it in my Views and in my form definition but seems i did it wrong. I need help on how i can implement this on the get requests of the CreateView or in the forms.py model definition. Any help will be greatly appreciated. -
Django Rest Framework Filtering an object in get_queryset method
Basically, I have a catalog viewset. In the list view I want to make a few filtering and return accordingly. Relevant Catalog model fields are: class Catalog(models.Model): name = models.CharField(max_length=191, null=True, blank=False) ... team = models.ForeignKey(Team, on_delete=models.CASCADE, editable=False, related_name='catalogs') whitelist_users = models.JSONField(null=True, blank=True, default=list) # If white list is null, it is open to whole team Views.py class CatalogViewSet(viewsets.ModelViewSet): permission_classes = (IsOwnerAdminOrRestricted,) def get_queryset(self): result = [] user = self.request.user catalogs = Catalog.objects.filter(team__in=self.request.user.team_set.all()) for catalog in catalogs: if catalog.whitelist_users == [] or catalog.whitelist_users == None: # catalog is open to whole team result.append(catalog) else: # catalog is private if user in catalog.whitelist_users: result.append(catalog) return result So this is my logic; 1 - Get the catalog object if catalog's team is one of the current user' team. 2 - Check if the catalog.whitelist_users contains the current user. (There is also an exception that if it is none means it s open to whole team so I can show it in the list view.) Now this worked but since I am returning an array, it doesn't find the detail objects correctly. I mean /catalog/ID doesn't work correctly. I am new to DRF so I am guessing there is something wrong here. How … -
Django prevent run command dbbackup invoke other command
I got a Django server and I want to backup the database everyday(using sqlite3), so I install django-dbbackup to do the job. I also install the django-apscheduler to do some scheduler task. So I got a command file runscheduler.py which I call from start of the views.py using other thread with management.call_command. When I test dbbackup python manage.py dbbackup in CMD Prompt, the backup command invoke the scheduler . How can I prevent that? -
Django Rest Framework - Account Verification Email: send_mail() works in console but not using SMTP
I have looked around StackOverflow and other places but I am not able to find a solution to my problem. I am using Django Rest Framework and Django Knox for user authentication and I want to send an account verification email to newly registered users. I am using Gmail. My email settings in my settings.py file are as below: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #Using this for testing EMAIL_USE_TLS = True EMAIL_HOST = os.getenv('EMAIL_HOST') EMAIL_PORT = os.getenv('EMAIL_HOST_PORT') EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') DEFAULT_FROM_EMAIL = os.getenv('EMAIL_HOST_USER') When I use EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend', I am able to see the email printed on the server. However when I use EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend', I don't get the email every time. I have to try sending an email multiple times to receive 1 email. Because I am receiving emails a few times, I think my credentials are right. I don't see any errors printed on the server either. Is this a Gmail issue considering I am receiving emails sometimes? An additional thing I noticed while working on this was that any code after send_mail is not executed in my API view. I am using a custom user model and my Register API … -
Could not parse remainder error while using ternary operator?
users.html <td><div class="form-group"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="user-{{i.id}}" {{(i.status) ? 'checked' : ' '}} onclick="changeUserStatus(event.target, {{ i.id }});"> <label class="custom-control-label pointer"></label> </div> </div> </td> why this error is showing? Could not parse the remainder: '(i.status=='True') ? 'checked' : ''' from '(i.status=='True') ? 'checked' : ''' any help will be appreciated? -
Django Nested Serializer Error: "The serializer field might be named incorrectly and not match any attribute or key"
I'm trying to get a json out similar to this: { name: Barry Bonds, playerListing: { best_buy_price: 69,420 } } Here is the serializer.py. class PlayerListingForProfileSerializer(serializers.ModelSerializer): class Meta: model = PlayerListing fields = ( 'best_buy_price', ) class PlayerProfileSerializer(serializers.ModelSerializer): PlayerListingField = PlayerListingForProfileSerializer() class Meta: model = PlayerProfile fields = ( 'PlayerListingField', 'card_id', 'name', ) Here is the model.py: class PlayerProfile(models.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) name = models.CharField(max_length=120, null=True) class PlayerListing(models.Model): player_profile = models.OneToOneField( PlayerProfile, on_delete=models.CASCADE, #db_constraint=False null=True) name = models.CharField(max_length=120, null=True) best_buy_price = models.IntegerField(null=True) I've had this working before but I can't figure out why it's throwing the error this time; Got AttributeError when attempting to get a value for field `PlayerListingField` on serializer `PlayerProfileSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `PlayerProfile` instance. Original exception text was: 'PlayerProfile' object has no attribute 'PlayerListingField'. -
Get API result when sending SparkPost email from Django?
Django has built-in support for sending mail via sparkpost, if you set MAIL_BACKEND in settings.py: EMAIL_BACKEND = 'sparkpost.django.email_backend.SparkPostEmailBackend' SPARKPOST_API_KEY = 'something' Once it's set up, you can use the standard Django ways to send mail (the send_mail() function or the EmailMessage class). If I send a message via the SparkPost API directly, it returns a result that looks like this: {'total_rejected_recipients': 0, 'total_accepted_recipients': 1, 'id': '1234567890'} Does Django offer a way to access this API result? -
Git file problem when migrating in Django
I have the following structure in my Django project The gitignore is the one suggested by https://www.toptal.com/developers/gitignore/api/django The steps to initialize GIT were: Create the project with apps/A and apps/B, create the .gitignore file and run git init. Then I ran makemigrations and migrate The problem occurs when, starting from master, a new branch called Z is created with an apps/ZApp, a new model is created and makemigrations and migrate are executed from that branch. Thus: $ git checkout -b Z $ cd apps $ django-admin startapp Z $ cd .. Then I apply makemigrations and migrate and return to master... When I'm in master, I see those files that should be ignored and I can't find the reason for this ... They shouldn't be there ... All files should be in their respective branch I don't understand ... someone to help me -
The git push heroku master command failed while trying to deploy my django app
i did the git add command the commit command and all then when i wanted to deploy using 'git push heroku master' it failed alot cause i kept retrying it , then i added a Procfile and runtime.txt file to the project directory cause i didnt earlier and it still didnt work. these are the logs from the termina Counting objects: 100% (76/76), done. Delta compression using up to 4 threads Compressing objects: 100% (67/67), done. Writing objects: 100% (76/76), 467.03 KiB | 9.73 MiB/s, done. Total 76 (delta 15), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Installing python-3.9.4 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting absl-py==0.11.0 remote: Downloading absl_py-0.11.0-py3-none-any.whl (127 kB) remote: Collecting alabaster==0.7.12 remote: Downloading alabaster-0.7.12-py2.py3-none-any.whl (14 kB) remote: Collecting altair==4.1.0 remote: Downloading altair-4.1.0-py3-none-any.whl (727 kB) remote: ERROR: Could not find a version that satisfies the requirement anaconda-client==1.7.2 (from -r /tmp/build_39bafa76/requirements.txt (line 4)) (from versions: 1.1.1, 1.2.2) remote: ERROR: No matching distribution found …