Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django server error with mod_wsgi and apache
I'm really struggling to get my django server working and after setting everything up properly and removing mod_wsgi with apt and installing with pip as I'm getting this error. I don't know how to solve this now. [Thu Jan 23 08:49:40.400113 2020] [mpm_event:notice] [pid 3387:tid 139670994029504] AH00491: caught SIGTERM, shutting down [Thu Jan 23 08:49:40.510765 2020] [mpm_event:notice] [pid 10825:tid 139717113150400] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Thu Jan 23 08:49:40.510898 2020] [core:notice] [pid 10825:tid 139717113150400] AH00094: Command line: '/usr/sbin/apache2' [Thu Jan 23 08:49:43.484391 2020] [mpm_event:notice] [pid 10825:tid 139717113150400] AH00491: caught SIGTERM, shutting down [Thu Jan 23 08:49:43.588711 2020] [mpm_event:notice] [pid 10932:tid 139798046383040] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Thu Jan 23 08:49:43.588984 2020] [core:notice] [pid 10932:tid 139798046383040] AH00094: Command line: '/usr/sbin/apache2' [Thu Jan 23 09:01:32.076606 2020] [mpm_event:notice] [pid 10932:tid 139798046383040] AH00491: caught SIGTERM, shutting down [Thu Jan 23 09:01:43.669965 2020] [mpm_event:notice] [pid 11462:tid 139656475659200] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Thu Jan 23 09:01:43.670110 2020] [core:notice] [pid 11462:tid 139656475659200] AH00094: Command line: '/usr/sbin/apache2' [Thu Jan 23 09:12:30.018940 2020] [mpm_event:notice] [pid 11462:tid 139656475659200] AH00491: caught SIGTERM, shutting down -
Django Error - unsupported operand type(s) for -: 'str' and 'int'
I have a Django code that must do some math, but I continuously get the following error: unsupported operand type(s) for -: 'str' and 'int' Here is the code: from django.shortcuts import render from django.http import HttpRequest def index(request): nor = request.GET.get('nor') mc = request.GET.get('mc') repaired = request.GET.get('repaired') if isinstance(nor, int): if repaired == 'yes': if mc == 'yes': summary = nor*20000+30000 else: summary = nor*20000 else: if mc == 'yes': summary = nor*20000-20000 else: summary = nor*20000-50000 else: summary = 'Try again' return render(request, 'index.html', {'summary':summary}) -
CSS file not found when attempting to overwrite bootstrap with sass?
I have an issue with bootstrap. I’m attempting to customise my bootstrap theme by using Sass. I’ve installed it Sass and created two files called main.scss and main.css In my main.scss file i’ve imported bootstrap via @import "node_modules/bootstrap/scss/bootstrap"; As seen in the bootstrap documentation on theming To overwrite the main.css file with the bootstrap package I run sass main.scss main.css I then add main.css as the stylesheet in my html head and delete the bootstrap stylesheet, as everything is now in the main.css file. When I try to run my program, it keeps telling my it can’t be found. My html file is located: /User_testing_v10/user_testing/templates/base.html My main.css file is located here: /User_testing_v10/main.css In the html.file i’ve asked it to fetch the main.css file here: <link rel= "stylesheet" href="/User_testing_v10/main.css”> Not Found: /User_testing_v10/main.css [23/Jan/2020 11:02:30] "GET /User_testing_v10/main.css HTTP/1.1" 404 2350 What am I doing wrong? Do I need to add static or something? Thanks for reading this -
How do you persist session cookies for your tests in Django with selenium
I am setting up tests for both chrome and firefox using seleniumgrid.I am using docker images selenium-hub and selenium node-chrome and node-firefox as below. app: build: . command: gunicorn --reload --capture-output --log-level debug --access-logfile - -w 3 -b 0.0.0.0 app.wsgi restart: always volumes_from: - initialize ports: - "8000:8000" links: - db - rabbitmq - selenium_hub env_file: secrets.env volumes: - ./app/:/code/ selenium_hub: image: selenium/hub ports: - 4444:4444 expose: - 4444 tty: true environment: - GRID_MAX_SESSION=20 - GRID_NEW_SESSION_WAIT_TIMEOUT=60000 - GRID_BROWSER_TIMEOUT=300 - GRID_TIMEOUT=300 - TIMEOUT=300 node_1: image: selenium/node-chrome depends_on: - selenium_hub environment: - HUB_HOST=selenium_hub - HUB_PORT=4444 - NODE_MAX_SESSION=3 - NODE_MAX_INSTANCES=2 shm_size: 2GB node_2: image: selenium/node-firefox environment: - HUB_HOST=selenium_hub - HUB_PORT=4444 - NODE_MAX_SESSION=3 - NODE_MAX_INSTANCES=2 shm_size: 2GB depends_on: - selenium_hub When I try to run the tests I am always running into this error InvalidCookieDomainException: Message: invalid cookie domain. I have already set domain to self.live_server_url. below is the full traceback with the test setup. Traceback (most recent call last): File "/code/frontend/tests/test_user_auth.py", line 75, in setUp "port": "8082", File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 894, in add_cookie self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict}) File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidCookieDomainException: Message: invalid cookie domain (Session info: chrome=77.0.3865.75) Test reference … -
Celery: communicating between tasks (and clients) with kombu
This is frustrating me some and costing me a great deal of time in research, and reverse engineering for lack of Celery docs on internals. There is a beautiful, tutorial here: https://ask.github.io/celery/tutorials/clickcounter.html that does just this, uses kombu to communicate between a Django view and a Celery task. But it's for Celery 2.6 and well, it's 2020 and we're using 4.4 and this in particular: from celery.messaging import establish_connection is long deprecated. It also leans on kombu.compat when I think kombu natives would work fine here and we don't need to lean on carrot compatibility which that module provides. But that is a side issue. My main problem is bringing this example up to date, and I find no Celery docs to help and still cannot after hours of code reading and tracing still put my finger on an analog to this in Celery 4.4. I find hints and clues all over the celery code base, just haven't nailed an answer. I would be pleased, grateful and excited if a more experienced voice wandered along and shed light on this, helped getting such an example as this tutorial working using Celery 4.4 methods. To illustrate I found this: COMPAT_MODULES = … -
How to tell my template to print only certain cells of my table (Django)
I am developing an app in Django. I have on my template: {% for row in query_result %} <tr> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} </tr> {% endfor %} Let's suppose I want my template to print only the first and the third column of my matrix, how can I indicate to my template a specific cell? I tryed with {% for row in query_result %} <tr> <td >{{ cell[0] }}</td> <td >{{ cell[2] }}</td> </tr> {% endfor %} but it does not work. -
Django "NotADirectoryError at /" error when deploying to heroku
https://myheroku-projectmanager.herokuapp.com This is the link of the app and error. Can you please help me to check as I don't know how to fix the error. -
Getting 403 for unsafe methods | DRF React Production
I'm getting 403 forbidden error for the unsafe methods (PUT, POST, DELETE) in the deployed Django project. I'm using react as front-end. I'm using axios to send the request to the DRF view. I've included the below lines to send the csrf token with the header as X-CSRFToken. axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; In my local everything is working fine. I've deployed this project with NGINX and Gunicorn in a Linux server. There I'm facing an issue while sending the request with unsafe methods. I'm not sure why its not working when it is deployed in the Linux server. Can anyone please help me on this. Please :( -
Adding field to Profile when creating User
I have a signup form that looks like this: class SignUpForm(UserForm): username = forms.CharField(max_length=32, min_length=1) initials = forms.CharField(max_length=3) password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput())' ... I'm creating the user like this: class SignUpView(FormView, LoginErrorView): form_class = SignUpForm template_name = "website/sign_up.html" def form_valid(self, form): User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password']) .... The Profile model looks like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) initials = models.CharField(max_length=3) .... I'm creating the profile like this: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() What I would like to do is to save initials (in the Profile-model) from the SignUpForm when I'm creating the Profile object, but I can't figure out any simple way of doing this. Any ideas? -
What are the types of method parameters in data migrations?
When creating data migrations with Django, you create a function like combine_names(apps, schema_editor). What are the types of the parameters apps and schema_editor in this case? -
Vue-apollo. Queries don't work return 400 Bad Request
I am building a frontend with Vue cli and backend with Django with Graphene. The mutation works fine but not the queries. When I run the same query from GraphiQL, works fine. Frontend @vue/cli 4.1.2 vue-apollo 3.0.2 Backend python 3.8 django 3.0.2 graphene-django 2.8.0 django-graphql-jwt 0.3.0 queries.js import gql from 'graphql-tag' export const ME_QUERY = gql` query me { me { username is_active } } ` Home.vue <script> import { ME_QUERY } from '@/graphql/queries' export default { name: 'home', async mounted () { await this.$apollo .query({ query: ME_QUERY }) .then((result) => { console.log(result) }) .catch(({ graphQLErrors }) => { graphQLErrors.map(({ message, locations, path }) => console.log(`Error Message: ${message}, Location: ${locations}, Path: ${path}`)) }) } } </script> schema.py from django.contrib.auth import authenticate, login, get_user_model import graphene from graphene_django import DjangoObjectType import graphql_jwt from graphql_jwt.decorators import jwt_cookie class UserType(DjangoObjectType): class Meta: model = get_user_model() class ObtainJSONWebToken(graphql_jwt.JSONWebTokenMutation): user = graphene.Field(UserType) @classmethod def resolve(cls, root, info, **kwargs): return cls(user=info.context.user) class Query(graphene.ObjectType): me = graphene.Field(UserType) def resolve_me(root, info): print("Entrando en me") user = info.context.user if user.is_anonymous: raise Exception('Authentication failure!!') return user class Mutation(graphene.ObjectType): # token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() revoke_token = graphql_jwt.Revoke.Field() log_in = ObtainJSONWebToken.Field() schema = graphene.Schema(query=Query, mutation=Mutation) Thanks for … -
Cannot load static files in production after trying numerous solutions
I have moved my django project from development to my production server. After deployment I cannot view static files on my pages. I know that django does not serve static files once debug is turned off and have tried using whitenoise to serve my static files. Attempt 1- WhiteNoise These are the changes that I made to settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] and wsgi.py: from whitenoise.django import DjangoWhiteNoise ... application = get_wsgi_application() application = DjangoWhiteNoise(application) and then running collectstatic. However my webpages still were not loading any of the static files. Attempt 2- Apache- mod_wsgi With the second attempt, I tried using apache+ mod_wsgi To be specific I connected to my VPS using terminal in cpanel installed apache2 and followed a tutorial. sudo apt-get install apache2 created my conf file sudo nano new_config.conf added this to it <VirtualHost *:80> ServerName 127.0.0.1 ServerAlias localhost Alias /static /var/gradientboostmvp/static/ WSGIScriptAlias / /var/gradientboostmvp/django_school/wsgi.py <Directory /var/gradientboostmvp/> Order deny,allow Allow from all </Directory> DocumentRoot /var/gradientboostmvp </VirtualHost> enabled the newly created virtual host conf file sudo a2ensite new_config.conf sudo /etc/init.d/apache2 restart added my WSGIPythonPath in apache2.config WSGIPythonPath /var/gradientboostmvp saved the changed, but still couldn't load my static files Attempt … -
How to compare values of two for loops and use if statement in django template?
This might be a confusing question. I have three tables in sqllite: 1) Events 2) Delegates 3) EventDelegate 1st one stores all events, 2nd one stores all delegates, 3rd one contains the eventid and delegateid to show that the particular delegate is attending that particular event. In my event details page i only want to show the delegates whose id are present in the event_delegate table along with that event id. Currently im using this code but not working views.py def event_det(request, eid): data = Event.objects.filter(id=eid) //SELECTING ONLY THE CLICKED EVENT data2 = Delegate.objects.all() // SELECTING ALL THE DELEGATES FROM DB data3 = EventDelegate.objects.filter(event_id=eid) //SELECTING RECORDS FROM EVENT_DELEGATE WHERE eventid is eid return render(request, 'event_details.html', {'event': data, 'delegates': data2, 'selectdelegates': data3}) template <tbody> {% for del in delegates %} {% for sd in selectdelegates %} {% if del.id == sd.delegate_id %} <tr> <td>{{ del.id }}</td> <td>{{ del.first_name }} {{ del.last_name }}</td> <td>{{ del.email }}</td> <td>{{ del.phone }}</td> <td>{{ del.company }}</td> <td>{{ del.designation }}</td> <td><a href="{% url 'delegate' dataset_id=del.dataset_id %}">View</a></td> </tr> {% endif %} {% endfor %} {% endfor %} </tbody> i can share more details if required... -
django, travsersing multiple tables (models) in a filter
I have a functioning search function shown below, it works without issue. We are redesigning the system, the area_easting value now sits in its own table (model). To get to the area_easting he route is as follows: Trench.trench_id --> Context.context_id --> Sample.sample_id (I know this is non-standard notation). So how would I traverse these joins? Something like: qs = qs.filter(sample_id__context_id__trench_id__area_easting__icontains=easting_query) Which returns Unsupported lookup 'context_id' for AutoField or join on the field not permitted. def CeramicFliterView(request): qs = Sample.objects.all() easting_query = request.GET.get('area_easting') if easting_query != '' and easting_query is not None: qs = qs.filter(area_easting__icontains=easting_query) ... -
Python (Django) framework for interactive Entity Relationship Model (ERM)
I'm looking for a way to basically display a bunch of tables (entities), which are related. E.g. table 1 holds a bunch of attributes and is linked to table 2 and both of them might have a link to table 3. The data used to build this view is one django-model with all entities and another django-model with the relationship between the entities (source -> target) On the webpage I want to have an interactive representation (mouseover tooltips) of those tables. all tables should arrange themselves based on the data It should look comparable to this: https://dbdiagram.io/home (it's not necessary to be able to drag them around) I already looked into a bunch of frameworks like plotly or bokeh, but it seems like they are more suited for diagram style representation of networks. Any help would be appreciated! -
Does Django use per-page or per-session CSRF?
I'm wondering what is the default Django policy for CSRF generation? Are they created per page or per session? And if it is per session, why is it chosen? Isn't it less secure than per-page CSRF? -
Django image-kit resize to fit whole image within div without losing part of the image
I'd like to use django image-kit to resize a whole image to fit within a div without cutting off part of the image. Right now I have this: image_post = ImageSpecField(source='image', processors=[ResizeToFill(700, 600)], format='JPEG', options={'quality': 100}) But using these exact specs would cut the image off to look like this: When the original image is this: How I could use django image-kit to resize the whole image to fit into the div without losing any of the image? Cheers -
setting LANGUAGE_CODE in template based on page setting
In Django / Wagtail I can set the language of a single page. With my custom instance method {{ page.get_language }} this language is available in the template. But I want all dates and hard-coded texts translated in the set language. So I would like to to set LANGUAGE_CODE with page.get_language. Any ideas what the best practice is? -
Django Form Submit Retain Selection Criteria
New to Django / HTML. I have a form on my home page. The form takes inputs from the user and upon clicking submit, the form retrieves data and displays it below the form. The problem is that after submit is clicked, the form selection values reset to the default values. I would like to retain the values selected by the user. Any help is appreciated. -
Django querysets optimization - preventing selection of annotated fields
Let's say I have following models: class Invoice(models.Model): ... class Note(models.Model): invoice = models.ForeignKey(Invoice, related_name='notes', on_delete=models.CASCADE) text = models.TextField() and I want to select Invoices that have some notes. I would write it using annotate/Exists like this: Invoice.objects.annotate(has_notes=Exists(Note.objects.filter(invoice_id=OuterRef('pk')))).filter(has_notes=True) This works well enough, filters only Invoices with notes. However, this method results in the field being present in the query result, which I don't need and means worse performance (SQL has to execute the subquery 2 times). I realize I could write this using extra(where=) like this: Invoice.objects.extra(where=['EXISTS(SELECT 1 FROM note WHERE invoice_id=invoice.id)']) which would result in the ideal SQL, but in general it is discouraged to use extra / raw SQL. Is there a better way to do this? -
Django is not rendering data when using ajax
I have a simple code in my template.html: <div> <input type="button" id="buttonId" value="Show Data"> </div> <script> $('#buttonId').click(function() { $.ajax({ method: 'POST', data: { csrfmiddlewaretoken: csrf_token, click: true }, success: function(response){ console.log(response) // it is a HTML, not my data } }); }); </script> {{results}} And in my views.py: if request.POST.get('click', False): ... #here I get finalresults return render(request, 'template.html', context={ 'results': finalresults }) When I push the Button, the script runs. So I know that after pushing the button, finalresults has content, but this content does not arrive to the HTML template. What am I doing wrong? -
Django : Problem with Django-allauth urls
I just started with a Django project using django-allauth, I configured the basic settings, without using any 3rd party provider. I have set up the urls.py of my project and urls.py of my app. But on going to http://localhost:8000, it takes you to the following page. The following is the urls.py of my project : from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('ckeditor/',include('ckeditor_uploader.urls')), path('',include('blog.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And this my urls.py of app : from django.urls import path, include from . import views urlpatterns = [ path("", views.PostListView.as_view(), name = 'post_list'), path("post/add", views.CreatePostView.as_view(), name = "create_new_post"), ] -
Login is not working in my project in django?
I am newbie to django I am having login page in my project I wrote the url and view for the login page but the url is not working properly when I click on login this error is coming My urls.py: urlpatterns = [ path('login/', views.login,name='login'), ] My views.py: @login_required def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return HttpResponseRedirect(reverse('modsy:dashboard')) else: messages.error(request,'Invalid Credentials') # return render(request,'dashboard.html') ## removed 1 # else: ## removed 2 return render(request, 'login.html') # This is a dashboard view def dashboard(request): if request.user.is_superuser: messages.error(request,'Invalid Credentials') return HttpResponseRedirect(reverse('modsy:login')) return render(request, 'index1.html') The error is attached below please help me out -
No result found in django rest framework in filtering option
Here is my model class : class Product(models.Model): SKU = models.IntegerField() price = models.IntegerField() status = models.IntegerField() And the serializers is: class ProductSerializer(serializers.Serializer): class Meta: model = Product fields = '__all__' In my view I used this logic to filter Product by Status and Price. class ProductFilter(filters.FilterSet): class Meta: model = Product fields = { 'status': ['icontains'], 'price': ['iexact', 'lte', 'gte'], } @api_view(['POST']) def productview(request): queryset = Product.objects.all() serializer_class = ProductSerializer filterset_class = ProductFilter serializer = serializer_class() return Response(serializer.data) It gives the output like this { "SKU": null, "price": null, "status": null } Now how can I get all the Product list(Index) according the filter ? Where I am giving the filter value as JSON like this. { "price": 200, "status": 2 } It will filter according to price== 200 and status==2. And also, can I used function based view for this kind of filtering??? -
DJANGO: keep pagination & filters after form save
I am struggling with trying to render the existing page view (with the selected filters and pagination) after saving the form. It has worked prior to pagination implementation, but now i got a little bit stuck. I am using Django, with django_filters and Paginator. This is my code: views.py def save_item_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True user_list = item.objects.all() user_filter = UserFilter(request.GET, queryset=user_list) user_list = user_filter.qs page = request.GET.get('page', 5) paginator = Paginator(user_list, 50) try: post_list = paginator.page(page) except PageNotAnInteger: post_list= paginator.page(1) except EmptyPage: post_list= paginator.page(paginator.num_pages) context = { 'paginator': paginator, 'page':page, 'post_list': post_list, 'filter':user_filter } data['html_item_list'] = render_to_string('items/includes/partial_item_list.html', context) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def item_list(request): user_list = item.objects.order_by('-nom_projet').all() user_filter = UserFilter(request.GET, queryset=user_list) user_list = user_filter.qs paginator = Paginator(user_list, 50) #50 posts in each page page = request.GET.get('page') try: post_list = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page post_list = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results post_list = paginator.page(paginator.num_pages) context = { 'paginator': paginator, 'page':page, 'post_list': post_list, 'filter':user_filter } return render(request, 'items/item_list.html', context) …