Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'django.contrib.static'
Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 141, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.6/site-packages/six.py", line 693, in reraise raise value File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__ response = response or self.get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.6/site-packages/six.py", line 693, in reraise raise value File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__ response = response or self.get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.6/site-packages/six.py", line 693, … -
URL in the Django REST API
Serializer looks like this: class Require_assistanceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=Require_assistance fields=('id', 'url', 'title','description') REST API works well without the 'url' field. Some tutorials show that HyperlinkedModelSerializer must generate that url but I get the error. I think it is written that there is no detail view for the 'url'. ImproperlyConfigured at /en/buyers_apprest_apiRequire_assistance/ Could not resolve URL for hyperlinked relationship using view name "require_assistance-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. urls.py from django.conf.urls import url from django.urls import include, path from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('Require_assistance', views.Require_assistanceView) app_name = "buyers_app" urlpatterns=[ path('rest_api',include(router.urls)), ] views: from django.shortcuts import render from .models import Require_assistance from django.views import generic from rest_framework import viewsets from .models import Require_assistance from .serializers import Require_assistanceSerializer class Require_assistanceView(viewsets.ModelViewSet): queryset=Require_assistance.objects.all() serializer_class=Require_assistanceSerializer Do you have any idea how to display the URL for the detailed view without this error? -
Django/Celery 4.3 - jobs seem to fail randomly
These are the tasks in tasks.py: @shared_task def add(x, y): return x * y @shared_task def verify_external_video(video_id, media_id, video_type): return True I am calling verify_external_video 1000+ times from a custom Django command I run from CLI verify_external_video.delay("1", "2", "3") In Flower, I am then monitoring the success or failure of the jobs. A random number of jobs fail, others succeed... Those that fail, do so because of two reasons that I just cannot understand: NotRegistered('lstv_api_v1.tasks.verify_external_video') if it's not registered, why are 371 succeedings? and... TypeError: verify_external_video() takes 1 positional argument but 3 were given Again, a mystery, as I quit Celery and Flower, and run them AGAIN from scratch before running my CLI Django command. There is no code living anywhere where verify_external_video() takes 1 parameter. And if this is the case... why are SOME of the calls successful? This type of failure isn't sequential. I can have 3 successful jobs, followed by one that does not succeed, followed by success again, so it's not a timing issue. I'm at a loss here. -
Django timezone struggles
I am having difficulty getting queryset results in my own timezone. for example: model field definition: some_datetime_field= models.DateTimeField(null=True) Query: MyModel.values_list("some_datetime_field",flat=True).first() returns datetime.datetime(2019, 11, 5, 14, 56, 16, tzinfo=<UTC>) instead of returning datetime.datetime(2019, 11, 5, 6, 56, 16, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>) I am working with python V3.7.5, Django V2.2.7 and PostgreSQL V12 as my database. In my setting I have: TIME_ZONE = "America/Los_Angeles" USE_TZ = True USE_I18N = True USE_L10N = True From the documentation it says with regard to the "TIME_ZONE" settings: (https://docs.djangoproject.com/en/2.2/ref/settings/#time-zone) When USE_TZ is True and the database supports time zones (e.g. PostgreSQL), it is an error to set this option. so I tried to remove the TIME_ZONE from my setting: USE_TZ = True USE_I18N = True USE_L10N = True but that didnt work either, even worse, when I try to localize it with timezone.localtime(datetime_example) i get the time in Chicago time: datetime.datetime(2019, 11, 5, 8, 56, 16, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>) How can I get my query set to return DateTime in my chosen timezone instead of UTC? -
Django: annotate QuerySet with number of seconds since object created
I have a model, call it Foo, which has an attribute created_at which notes the time (UTC) when an instance was created. I would like to annotate a query set over this model with the number of seconds since each item returned was created. (to be more precise, I would like to "discount" items based on the time they have been open, with a configurable stale-out time, but I can do that computation if I can get the number of seconds since create) I have tried some obvious things like Foo.objects.annotate(time_since_create=now-F('created_at')) and Foo.objects.annotate(time_since_create=now.timestamp()-F('created_at')) but these get me AttributeError: 'float' object has no attribute 'tzinfo', which suggests that DB arithmetic on dates is a little more complex than I'm thinking it ought to be. Obviously, I can do this arithmetic in python, ie, [(id, now-created_at) for id, created_at in Foo.objects.values_list("id", "created_at")] but it would be nicer if I could get this back in the queryset. -
WebDriverException at / Service /usr/bin/chromium-browser unexpectedly exited. Status code was: 127
I'm trying to run my crawler using selenium, webdriver and xvfb on pythonanywhere server (if it can help). I also tried to use pyvirtualdisplay instead of xvfb to create a browser window for webdriver. But I keep receiving error "Message: Service /usr/bin/chromium-browser unexpectedly exited. Status code was: 127" Traceback: File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/Sayn0toWar/parser_test/parser_test/main/views.py" in index 13. main(int(iterations)) File "/home/Sayn0toWar/parser_test/parser_test/main/parser_script.py" in main 111. b = Bot(iterations) File "/home/Sayn0toWar/parser_test/parser_test/main/parser_script.py" in init 24. self.driver = webdriver.Chrome(executable_path='/usr/bin/chromium-browser', chrome_options=options) File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py" in init 73. self.service.start() File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/selenium/webdriver/common/service.py" in start 98. self.assert_process_still_running() File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/selenium/webdriver/common/service.py" in assert_process_still_running 111. % (self.path, return_code) Exception Type: WebDriverException at / Exception Value: Message: Service /usr/bin/chromium-browser unexpectedly exited. Status code was: 127 My code: from bs4 import BeautifulSoup from selenium import webdriver from webdrivermanager import ChromeDriverManager from xvfbwrapper import Xvfb from pyvirtualdisplay import Display from time import sleep class Bot: def __init__(self, iterations): display = Display(visible=0, size=(800, 600)) display.start() cdm = ChromeDriverManager() chromedriver_path = cdm.download_and_install() options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') self.driver = webdriver.Chrome(executable_path='/usr/bin/chromium-browser', chrome_options=options) self.navigate(iterations) self.close() display.stop() I am sorry for my code, i'm not good at … -
Count number of attributes of a class
I want to make a fully dynamic table which adjusts its self number of columns depending on which type of object I'm passing in the view. What I tried is: from Food.models import Food for field in Food: # Count how many fields do my class Food has. But PyCharm is showing the following error: Expected 'collections.Iterable', got 'Type[Food]' instead. Pretty obvious since it's not an actual initialized object. But how can I achieve this? Thanks! -
How to use field value as a label in Django formsets? E.g. datagrid where one field's value is a label for another field (changeable)
I'm trying to display piece of a data-grid (product specifications table) as a form, but can't figure out how to use value of one column as a label for another column. E.g: Feature name (as label) .. Feature value (as an input). so far my code is this: models.py class ProductSpecs(models.Model): sku = models.CharField(max_length=30, blank=False) f_feature = models.CharField(max_length=100, blank=False) f_value = models.TextField(blank=True) f_unit = models.CharField(max_length=20, blank=True) ic_feature_name = models.CharField(max_length=50, blank=True) ic_feature_id = models.SmallIntegerField(blank=True) ic_feature_type = models.CharField(max_length=30, blank=True) ic_value = models.CharField(max_length=100, blank=True) last_update = models.DateTimeField(default=timezone.now, blank=True) status = models.CharField(max_length=20, blank=True) def __repr__(self): return str(self.sku) views.py def product_specs(request, pk): obj = BrandMainData.objects.get(pk=pk) prod_specs = ProductSpecs.objects.filter(sku=obj.sku).all() if prod_specs: spec_formset = modelformset_factory(ProductSpecs, fields=('ic_feature_name', 'ic_value',), widgets={'ic_feature_name': TextInput(attrs={'readonly': True, 'disabled': True, 'border':'none'})}) if request.method == 'POST': formset = spec_formset(request.POST) formset.save() return HttpResponseRedirect('') else: formset = spec_formset(queryset=prod_specs) context = { 'formset': formset, 'main_prod': obj, } return render(request, 'imports/product_specs.html', context=context) else: return render(request, 'imports/404.html') HTML template <form action="" method="POST" name=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {% for field in form %} {% if field.value %} {% if field.label == 'Ic feature name' %} <div style="float:left; width:450px; padding-left:40px; margin-bottom:0px"> {{ field }}</div> {% else %} <div>{{ field }}</div> {% endif %} {% … -
Modal popup with single field rendering and functional, but not submitting?
I have a form that keeps track of when a user enters/leaves an area and whenever there is a time discrepancy, it prompts the user for an estimate of a time. Currently the main parts of the form work, and the modal shows up when it needs to, but when you try to submit the "edited timestamp" the modal just gets stuck on loading and nothing happens until you refresh the page, and even when you do, nothing has been submitted to the database for the edited timestamp. It just stays with the loading symbol moving over the submit button like shown below: What could be causing this to get stuck? Looking through the code (I'm not too familiar with python) I believe it has to do with not having a .save()/.update() for the field being modified (edited_timestamp), or maybe the redirection after modal "submit" is not set (not sure how to go about this either). views.py def enter_exit_area(request): form = WarehouseForm(request.POST or None) enter_without_exit = None exit_without_enter = None if form.is_valid(): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in request.POST: new_entry = form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) # … -
django login error "Account with this Email already exists"
Django login error is being shown that "Account with this Email already exists". I'm trying to login but it is showing this error. I tried some previously given solutions but it's not getting resolved. What's the problem? Please have a look at it, help me resolve this isssue. Thanks in advance. . I'm adding my code below: This is my forms.py- ''' from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate from account.models import Account class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text='Required. Add a valid email address') class Meta: model = Account fields = ("email", "username", "password1", "password2") class AccountAuthenticationForm(forms.ModelForm): #always use (forms.Form) here, instread of (forms.ModelForm) password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = Account fields = ('email', 'password') def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login") ''' This is my views.py- ''' from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, AccountAuthenticationForm def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password') account = authenticate(email=email, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: #GET request form = RegistrationForm() context['registration_form'] = … -
Django how to make family relations
I wonder how can we make a relations between 2 users, which can be applied in reverse. The goal is when creating an object via django admin to add relation between 2 users and create the opposite of it in the second user, the sex of the user is very important for the reverse connection. I have tried to create the reverse of it when creating the object but then it crashes because it tries to recreate the object again and again. models.py SEX = ( ('m', 'Male'), ('f', 'Female'), ) class User(models.Model): first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) sex = models.CharField(max_length=1, choices=SEX) def __str__(self): return f"{self.first_name} {self.last_name}" RELATIONS = ( ('mother', 'Mother'), ('daughter', 'Daughter'), ('father', 'Father'), ('son', 'Son') ) RELATIONS_REVERSE = { 'mother':{ 'm':'son', 'f':'daughter' }, 'father':{ 'm':'son', 'f':'daughter' }, 'son':{ 'm':'father', 'f':'daughter' }, 'daughter':{ 'm':'father', 'f':'mother' } } class UserRelation(models.Model): User_1 = models.ForeignKey(User, related_name="User_1", null=False, blank=False, on_delete=models.CASCADE) User_2 = models.ForeignKey(User, related_name="User_2", null=False, blank=False,on_delete=models.CASCADE) relation = models.CharField(max_length=30, choices=RELATIONS, null=False, blank=False) #THIS DOES NOT WORK! # def save(self): # UserRelation.objects.create( # User_1= self.User_2, # User_2= self.User_1, # relation= RELATIONS_REVERSE[str(self.relation)][self.User_2.sex] # ) admin.py from django.contrib import admin # Register your models here. from .models import User, UserRelation … -
Django: Problem with Understanding Super Save Function
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. Right now, I am facing a problem understanding this code: def save(self): super(Review, self).save() self.slug = '%i-%s' % ( self.id, slugify(self.game.title) ) super(Review, self).save() It comes from models.py: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tag(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tag) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = models.DateField(auto_now=True) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.review def save(self): super(Review, self).save() self.slug = '%i-%s' % ( self.id, slugify(self.game.title) ) super(Review, self).save() It looks like the save function is saving the slug. But I don't understand it completely. Does it converting integer to string? What is super doing here? Would you please give me a complete explanation about the save function? -
Django validation error messages only showing in admin page
I have a SignUp form that interacts with Django's user model to create new users. If both password fields are different, the user is not created, so I guess validation is working. But somehow, a validation error message is not shown, the form page is just rendered again. When I go to Django's admin page, the error messages pop up there! Why is it not popping in my template?! This is my form: class SignUpForm(forms.ModelForm): password = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'placeholder':'Password', 'class':'form-control', 'type':'password'}),) password2 = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'placeholder':'Confirm Password', 'class':'form-control', 'type':'password'}),) class Meta: model = User widgets = {'first_name': forms.TextInput(attrs={'placeholder':'First Name', 'class':'form-control'}), 'last_name': forms.TextInput(attrs={'placeholder':'Last Name', 'class':'form-control'}), 'email': forms.TextInput(attrs={'placeholder':'Email', 'class':'form-control', 'type':'email'}), 'username': forms.TextInput(attrs={'placeholder':'Username', 'class':'form-control'}), 'password': forms.TextInput(attrs={'placeholder':'Password', 'class':'form-control', 'type':'password'}) } fields = {'first_name', 'last_name', 'email', 'username', 'password'} def clean(self): cleaned_data = super(SignUpForm, self).clean() password = cleaned_data.get('password') password2 = cleaned_data.get('password2') if password != password2: raise forms.ValidationError('Passwords do not match!') And this is my view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) form.save() user = authenticate(username=username, password=password) login(request, user) messages.add_message(request, messages.SUCCESS, 'Account created successfully!') return HttpResponseRedirect('/') else: messages.add_message(request, messages.ERROR, "There's an error in the form! Please fill it again.") return render(request, … -
Django admin download data as csv
I want to download data from django admin as .csv file. I followed tutorial https://www.endpoint.com/blog/2012/02/22/dowloading-csv-file-with-from-django. I didn't see download csv option. How can I solve my problem? I am using Python3, migration created. This is my code models.py from django.db import models from django.contrib import admin class Stat(models.Model): code = models.CharField(max_length=100) country = models.CharField(max_length=100) ip = models.CharField(max_length=100) url = models.CharField(max_length=100) count = models.IntegerField() class StatAdmin(admin.ModelAdmin): list_display = ('code', 'country', 'ip', 'url', 'count') def download_csv(self, request, queryset): import csv f = open('some.csv', 'wb') writer = csv.writer(f) writer.writerow(["code", "country", "ip", "url", "count"]) for s in queryset: writer.writerow([s.code, s.country, s.ip, s.url, s.count]) admin.site.register(Stat, StatAdmin) -
Developing a dashboard using Django?
Apologies in advance as this question is quite broad. My overall goal is to create a web application that allows for interactive analysis of NOAA model output data. For now, let's say the project will consist of two different dashboards: The first dashboard will take current output model data from NOAA based on user inputs (e.g., location) and display the data using interactive plotly plots. The second dashboard will be for displaying historical data from archived NOAA data. My background is more in chemistry and science, so while I have a good understanding of data analysis packages like Pandas, I'm much newer to web dev tools such as Django. I was originally able to create my two dashboards using Plotly Dash. I saved some sample data to my local computer and used Pandas to select subsets of data that were then plotted with plotly. However, I'd like to scale this to a fully-functioning webpage and therefore need to migrate this project to a Django framework. This is where I need help. Basically I'm trying to determine how the big-picture flow of this project would need to look. For example, below I give the workflow for a specific example in which … -
Django-cms Content Creation Wizards Custom Text Editor Implementation
I am learning Django-CMS and now I am trying to add content creation wizards. Currently, it is working nice but the problem is: it doesn't have a rich text editor. I am not getting how to implement this in content creation wizards. This is models.py : class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=500) this is my forms.py file class PostForm(ModelForm): class Meta: model = Post fields = ['title', 'content',] exclude = [] and this is my cms_wizers.py file: from cms.wizards.wizard_base import Wizard from cms.wizards.wizard_pool import wizard_pool from blog.forms import PostForm class BlogWizard(Wizard): pass blog_wizard = BlogWizard( title="Create Content", weight=200, form=PostForm, description="Create a new Content", ) wizard_pool.register(blog_wizard) Can anyone help me to implement rich text editor here? I know Django-cms uses CKEditor in page creation but I am not getting how to bring/implement this in my content creation wizards. It would be much appreciated if anyone can help me to implement this. -
Creating youtube playlist with python
i had implemented the following code from the google docs ... -- coding: utf-8 -- Sample Python code for youtube.playlists.insert See instructions for running these code samples locally: https://developers.google.com/explorer-help/guides/code_samples#python import os import google_auth_oauthlib.flow import googleapiclient.discovery import googleapiclient.errors scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"] def main(): Disable OAuthlib's HTTPS verification when running locally. DO NOT leave this option enabled in production. os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" api_service_name = "youtube" api_version = "v3" client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json" Get credentials and create an API client flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( client_secrets_file, scopes) credentials = flow.run_console() youtube = googleapiclient.discovery.build( api_service_name, api_version, credentials=credentials) request = youtube.playlists().insert( part="snippet,status", body={ "snippet": { "title": "Sample playlist created via API", "description": "This is a sample playlist description.", "tags": [ "sample playlist", "API call" ], "defaultLanguage": "en" }, "status": { "privacyStatus": "private" } } ) response = request.execute() print(response) if name == "main": main() after going to the link, they were asking for some authorization code...... this error is coming whats the issue... ERROR: redirect_uri_mismatch..... -
XML Parse error django-saml2-auth SSO when trying to authenticate through okta
This error started after rebuilding my docker container with the same compose file and dockerfile. Nothing has changed. django_gunicorn | Internal Server Error: /saml2_auth/acs/ django_gunicorn | Traceback (most recent call last): django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner django_gunicorn | response = get_response(request) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response django_gunicorn | response = self.process_exception_by_middleware(e, request) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response django_gunicorn | response = wrapped_callback(request, *callback_args, **callback_kwargs) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view django_gunicorn | return view_func(*args, **kwargs) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/django_saml2_auth/views.py", line 159, in acs django_gunicorn | resp, entity.BINDING_HTTP_POST) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/client_base.py", line 714, in parse_authn_request_response django_gunicorn | binding, **kwargs) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/entity.py", line 1194, in _parse_response django_gunicorn | response = response.verify(keys) django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/response.py", line 1051, in verify django_gunicorn | if self.parse_assertion(keys): django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/response.py", line 937, in parse_assertion django_gunicorn | if not self._assertion(assertion, False): django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/response.py", line 817, in _assertion django_gunicorn | if not self.condition_ok(): django_gunicorn | File "/usr/local/lib/python3.7/site-packages/saml2/response.py", line 616, in condition_ok django_gunicorn | raise Exception("Not for me!!!") django_gunicorn | Exception: Not for me!!!``` -
Django rest framework raw queries select not working
I want to use a raw query in order to make a JOIN in a many to many relationship, and show it in the Django Rest Framework. But the "SELECT" part of the query is not working, and it shows whatever the serializer has in "fields" and thus the JOIN is also not working. serializers.py: class UserTestSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" views.py: class UserTestQuery(viewsets.ModelViewSet): queryset = User.objects.raw('SELECT * ' + 'FROM users_user ' + 'INNER JOIN sysadmin_works_as ON users_user.user_id = sysadmin_works_as.employee_id;') serializer_class = UserTestSerializer I want to show a join in the API with these 3 models, so I must use raw SQL. Why is it not working? And the models I'm using are: class User(AbstractUser): first_name = None last_name = None username = None user_id = models.AutoField(primary_key=True) email = models.EmailField(_('email address'), unique=True) national_id_number = models.CharField(max_length=30) f_name = models.CharField(max_length=100) l_name = models.CharField(max_length=100) star_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True,null=True) is_superuser = models.BooleanField(default = False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True,null=True) deleted_at = models.DateTimeField(blank = True, null=True) date_joined = models.DateTimeField(auto_now_add=True,null=True) app_role = models.ForeignKey(App_roles,related_name='employee',on_delete=models.SET_NULL,blank=True,null=True) #Un Rol_de_Aplicacion le pertenece a muchos usuar class Works_as(models.Model): work_id = models.AutoField(primary_key=True) started_at = models.DateTimeField(auto_now_add=True) updates_at = models.DateTimeField(auto_now=True) r_created_at = models.DateTimeField(auto_now_add=True) r_updated_at … -
Django: Problem with Understanding Objects in For Loop
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have managed to do some protion of the app. Right now, I am a bit confused with a line of code. I have a code like this in one of my template files: {% extends 'gamereview/base.html' %} {% block title%} Detail {% endblock %} {% block content %} <h3>This is the review for {{game.title}} </h3> <ul>{% for review_item in game.review_set.all %} <li>{{ review_item.review }}</li> {% endfor %} </ul> {% endblock %} I don't understand this portion: <ul>{% for review_item in game.review_set.all %} What does this line mean? Here are the codes in models.py: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tag(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tag) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = models.DateField(auto_now=True) slug = models.SlugField(max_length=150, default='null') … -
Django count in annotation
I have a profile model with a ManyToMany field called that relates to a Stock. In my admin dashboard I'm trying to show the number of watchlists each stock is in. The annotation query I have is: return qs.annotate(watchlist_count=Count('profile__watchlist__symbol', distinct=True)) But it's returning incorrect results Here are the models: class Profile(models.Model): user = OneToOneField(User, on_delete=models.CASCADE) watchlist = ManyToManyField(Stock, blank=True) def __str__(self): return self.user.email class Stock(models.Model): symbol = CharField(max_length=15, unique=True) name = CharField(max_length=100) category = CharField(max_length=30, choices=CATEGORY_CHOICES, blank=True) about = TextField(help_text='About this company') def __str__(self): return f'{self.symbol} - {self.name}' What is wrong with my annotation query? -
Rename Model from app A that is used as a superclass in app B
I have a class in one app (we'll call app A) that I need to rename from FirstName to SecondName. class FirstName(models.Model): pass # stuff In app B, I import this class to use as a base for another model. from first_app.models import FirstName class ProxyModel(FirstName): pass # stuff What I did is update the model name and all references to it. class SecondName(models.Model): pass # stuff class ProxyModel(SecondName): pass # stuff operations = [ migrations.RenameModel( old_name='FirstName', new_name='SecondName', ), ] When I run makemigrations I get an error: django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'app_b.ProxyModel'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; It seems I cannot import the renamed base model before migration, but I cannot migrate until I resolve the base class issue... I did already try using the previous model name for the Proxy base class, but get model not found error. I also tried to comment out the proxy model, but still got the error (I think because of the migrations already run for that proxy model). How can I get around this rename dependency loop? Python 2.7, Django 1.11 -
Angular 6 cannot download pdf with greek characters from Django 2.2?
I am using Angular 6 and Django 2.2 and Ι am trying to request a pdf containing greek chars. here is my angular side code: service: getUserGuide() { return this._httpClient.post("association-rules/user-guide/", { headers: new HttpHeaders({ 'Content-Type': 'application/pdf', 'Accept' : 'application/pdf' }), responseType: 'blob', }) } component: getUserGuide() { this._targetProductService.getUserGuide() .subscribe( (response: any) => { var blob = new Blob([response], { type: 'application/pdf' }); saveAs(blob, 'report.pdf'); }); } Here is my django side code: class user_guide_view(APIView): permision_classes= [IsAuthenticated] def post(self, request): try: requestedFile= 'user_guide.pdf' folder= 'services_static_files/association_rules/' with open(folder+'/'+requestedFile, 'r', encoding="ISO-8859-1") as myfile: response = HttpResponse(myfile, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=stockitems_misuper.pdf' return response except (IOError,KeyError): return HttpResponse('no such file', status=status.HTTP_404_NOT_FOUND) Here you can see my request: It is obvious that: 'Content-Type' & 'Accept' of the request headers are wrong 'Content-Type' of response headers is right What I have done: After several suggested workarounds I came across online, I have tried combinations such as: responseType: 'blob', responseType: 'blob' as 'blob', responseType: 'blob' as 'json', responseType: ResponseContentType.Blob by adjusting the headers accordingly. Question 1 Why I cannot set properly ('Content-Type'-> 'application/pdf' and 'Accept'-> 'application/pdf') -
dynamic prices in django-oscar
I was looking how to implement dynamic prices (based on amount in basket, in my case) in my django-oscar e-shop. In the source of AbstractStockRecord (see here), I read about the price field: It is NULLable because some items don't have a fixed price but require a runtime calculation. So it seems possible, but how? Strategies and policies ahead, I dont really know where to start (also, the dynamic price calculation would happen before tax/strategy, etc..?) Any insights were to hook in or whater welcome! -
Django celery thows error when I import django model or function using one
I have a problem with the configuration of celery with django. When I attempt to import function like this into the celery file: def add_proxy(): proxy = ProxyList(timezone.now()) proxy.save() running command: celery -A estatefilter_backend worker -l info causes error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I'm using python 3.7.5 and django 2.2.7