Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Requested setting INSTALLED_APPS, but settings are not configured
When I try to run my scraper in Django I get the following error. This happened when I tried to put the scraped data into the database using the built-in Django models. traceback and error: /usr/bin/python3.6 /home/xxxxxx/Desktop/project/teo/movierater/scrap.py Traceback (most recent call last): File "/home/xxxxxx/Desktop/project/teo/movierater/scrap.py", line 7, in <module> from teo.movierater.api.models import * File "/home/xxxxxx/Desktop/project/teo/movierater/api/models.py", line 3, in <module> class Author(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) 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 put it in bin/activate: export DJANGO_SETTINGS_MODULE=mysite.settings Here is the code snippet from scraper.py: import django import os import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from teo.movierater.api.models import * os.environ['DJANGO_SETTINGS_MODULE'] = 'movierater.settings' django.setup() My project structure and the settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'movierater.api', ] wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'movierater.settings') application = get_wsgi_application() -
Axios POST request from Vuejs to Django rest framework
I create a rest api with vuejs and django rest framework. The probleme is when i made a post request. With a get request he works but not with a post request. axios .get('http://127.0.0.1:8000/api/users/') .then(response => (this.info = response.data)) axios .post('http://127.0.0.1:8000/api/users/', { params : { email : "test@gmail.com", username : 'test' } }) .then(response => (this.info = response.data)) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('', include(router.urls)), ] My get request works but not my post request. In my console i have : http://127.0.0.1:8000/api/users/?username=test&email=test@gmail.com 400 (Bad Request) And when i watch network i have {"username":["This field is required."]} I don't uderstand why i have this error. -
Passing Django Model to Javascript
I'm trying to pass my complete model with it fields because I need to use it on a Javascript function. I've tried everything I've seen (using json.dumps(), serializers..) and anything worked for me. I've donde the query this way: cancion = Cancion.objects.get(pk = cancion_id) The reason is because I need specific data depending on the id. Doing this, it throws me the following error: 'Cancion' object is not iterable So I don't find the correct way I have to do this stuff and use the model field in my javascript function. The field I want to use is a .mid file. If you have any doubts about the code feel free to ask anything -
How do I greet the user when they log into my website?
I'm trying to greet the user when they log into my django website, but using the django login has made it too difficult to send a message to my template and redirect to the new url behind the scenes. How can I greet the user(preferrably with that user's name) on the template of the url I redirect to? I've tried working with messages, but redirecting to the new url always overrides the message and it never appears. Regular logging in and out works fine, I'm just trying to figure out how to display welcome text to the user to let them know they have successfully logged in and are using their own account. views.py def loginPage(request): return render(request, "registration/login.html") def login(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: #Success! messages.success(request, "Welcome " + user) #NOT WORKING :( login(request, user) else: return HttpReponseRedirect("/DataApp/accounts/login/") settings.py LOGIN_URL = "/DataApp/accounts/login/" LOGIN_REDIRECT_URL = "/DataApp/search/" base.html <!-- This is nested in a div tag inside of the html class body --> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}" {% endif %}> {{ message }}</li> {% … -
How to fix django model manager to work with serializer
I have used model managers in my app to do the heavy lifting. Was able to use it well for the web version but having difficulty with the serialization of the Query to move data into a mobile app via an API. The model manager works fine for the web based interface. Trying to serialize so data can get into React Native for mobile app. The override of the queryset seems to be the way to go. here is the code in the serializer: class UserBeltsSerializer(serializers.ModelSerializer): class Meta: model = UserBelts fields = ('__all__') here is the code in .api: class SingleUserBeltViewSet(generics.ListAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserBeltsSerializer def get_queryset(self): beltlist = UserBelts.objects.all_belts(user=self.request.user) return beltlist error message is as follows: AttributeError at /api/singleuserbelts Got AttributeError when attempting to get a value for field `user` on serializer `UserBeltsSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'user'. -
How to combine Django forms, formsets, and formwizard for multi-step form
I'm looking to replicate the following form structures in a Django application. These are already coded in a PHP application. On the first page there are two separate forms for entry, where the top form is slightly different from the bottom form. At the moment they are two separate forms under forms.py, but could be combined together: forms.py: # forms.py from django import forms from .models import Data2, Data3 class ExampleEntryFormTop(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_top = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data3.objects, empty_label=None, widget=forms.RadioSelect) data4 = forms.MultipleChoiceField(choices=( ('alpha', 'Alpha'), ('beta', 'Beta'), ('gamma', 'Gamma')), widget=forms.CheckboxSelectMultiple ) class ExampleEntryFormBottom(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_bottom = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data2.objects, empty_label=None, widget=forms.RadioSelect) class ExampleEntryFormPage2(forms.Form): example_date = forms.DateField(widget=forms.HiddenInput()) data_top = forms.IntegerField() data_bottom = forms.IntegerField() data2 = forms.ModelChoiceField(Data2.objects, to_field_name="name", empty_label=None, widget=forms.RadioSelect) additional = forms.MultipleChoiceField(choices=( ('one', 'One'), ('two', 'Two'), ('three', 'Three')), widget=forms.CheckboxSelectMultiple ) data3 = forms.ModelChoiceField(Data2.objects, empty_label=None, widget=forms.RadioSelect) On the second page of the wizard I need to pre-load the next three days. I've been using the following to create the formset: forms.py: def get_example_set(): … -
Django - ORM - datetime field different formats
i am currently working on a Django app where every single DateTimeField should have the exact same format... to start with, this is my abstract model: from django.db import models class AbstractModel(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True Both created and updated field have the same format, like this: 2019-01-01 12:12:12.123456+00 # right BUT: When i add some other DateTimeField to any model, like: some_other_field = models.DateTimeField() and save it via django-admin, it gets this format in database: 2019-01-01 12:12:12+00 # wrong WHY ?! Right now i have two different DateTimeField formats in my database, which is conceptually very bad.. Can anybody help me out? I simply want one format (the upper one) in every single datetime field.. Settings: LANGUAGE_CODE = 'en-US' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True -
Reading and creating nested relation in single serializer django
I have two models Category and Products, and a classic one to many relatoin between them. Each product belongs to a category. I am using Django-Rest-Framework. I am using ModelViewSet as a ViewSet and ModelSerializer as a Serializer. I created the ProductViewSet which has the full CRUD opertions. What I am trying to achieve is to include the relation in the READ operations ( list , retrieve ). The response should look something like that. { "id" : 2, "name" : "foo product" , "category" : { "id" : 4, "name" : "foo relation" } } So I set the depth field in Meta equal to 1. class ProductSerializer(ModelSerializer): class Meta: model = Product exclude = ('createdAt',) depth = 1 What makes the category read only.But I want it to be writable in the other actions (POST , PUT). I know I can solve the problem using two serializes but this is a repetitive problem and I don't want to write two serializes for each model I have. I tried to add category_id field in the serializer but I had to override the create method to make it work correctly. And again I am trying to write less code. because … -
How can I convert this JSON request function to object orientated?
So I'm working on a ETL engine like application in Django and I've created a view that is very inefficient in that it doesn't follow D.R.Y principles and is really ugly. Can I get some help refactoring this to make it more object orientated in fashion? Here is a link to the full code: https://pastebin.com/At45Agcm I'm following along here: python turn giant function into Class but I'm still lost on how to instantiate a class where (as you can see from the pastebin code) you have a dynamic amount of variables to represent the individual JSON objects I want to extract. Here's a sample method that I want to convert to a more OOP like. Really struggling to figure this out since the number of parameters I'm extracting are variable amount. Thanks a ton for the help! def repositories(request): ''' Method that dynamically gets team members from a team given a team ID. Args: request: HTTP request payload Returns: POST string ''' parsed_list = [] parsed_data = [] if request.method == 'POST': # EXTRACTION PHASE repo_endpoint = request.POST.get('org_name') link = 'MY_GITHUB_URL' headers = {'Authorization': 'token MY_TOKEN_NUMERICAL'} response = requests.get(link + repo_endpoint, headers=headers) extraction_filename = datetime.now().strftime('repos_extraction_%Y-%m-%d-%H-%M-%S.json') transformed_file = datetime.now().strftime('repos_transformed_%Y-%m-%d-%H-%M-%S.json') with open(extraction_filename, … -
how to fix class ['classname'] has no object member in VSCode when running a populate file in django
I am populating a script in Django by running 'python populate_project_2_app.py' in the terminal. But I'm getting these errors 1- Unable to import 'faker'pylint(import-error) 2- Class 'Topic' has no 'objects' member pylint(no-member) Here is what displayed on my terminal after running 'python populate_project_2_app.py' C:\MyDjangoDev\Project_2>python populate_project_2_app.py python: can't open file 'populate_project_2_app.py': [Errno 2] No such file or directory C:\MyDjangoDev\Project_2>cd project_2 C:\MyDjangoDev\Project_2\project_2>python populate_project_2_app.py File "populate_project_2_app.py", line 6 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_2.settings') settings.configure() ^ SyntaxError: invalid syntax C:\MyDjangoDev\Project_2\project_2>python populate_project_2_app.py Traceback (most recent call last): File "populate_project_2_app.py", line 2, in from project_2_app.models import AccessRecord, Webpage, Topic File "C:\MyDjangoDev\Project_2\project_2\project_2_app\models.py", line 6, in class Topic(models.Model): File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\db\models\base.py", line 103, in new app_config = apps.get_containing_app_config(module) File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\conf__init__.py", line 79, in getattr self._setup(name) File "C:\Users\iam_xamuel\Miniconda3\lib\site-packages\django\conf__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) 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. Below is the populating script from project_2_app.models import AccessRecord, Webpage, Topic import random import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_2.settings') django.setup() # settings.configure() # Fake Population Script fake_generation = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] … -
Can I override __new__ in Django ModelForm?
I have a ModelForm with Django 1.11, and I'm moving a few fields to another model. Calling make_migrations causes an error because these fields don't exist in the current model. I added some of the fields to the form, but one of the fields is a TranslatedField and therefore there are currently 2 fields, and in the future there might be more, depending on the number of languages. The name of the field is city, and currently I get an error message "Unknown field(s) (city_en, city_he) specified for SiteProfile" (because I'm using 2 languages - "en" and "he") - but I want to create all the fields dynamically with a for loop over the languages we use in the project. Can I override (and is it a good programming method) the new method or is there another way? I prefer not to hard-code the specific field names (city_en and city_he) because they may change in the future, depending on how many languages we use. You can see my current commit (not working) on GitHub. And the current code of this branch. I would like to know what is the best programming method to define a dynamic list of fields (which … -
My existing Django project is being required by totally different, newly-created Django project
Hi I wanna ask about this strange behavior I've discovered just now in my PC when running a newly-created Django project. I have an existing and ongoing Django project pgadn_website that has its own virtual env, and I just created a fresh Django project called Blog which I intend to use for testing some stuff which is also has its own virtual env. So strange that when I execute runserver on Blog, it gives me this error: I'm suspecting I might have set something globally but I don't know where to look for it. P.S. the error also happens on pretty much every new project I create, not just the Blog one. -
Django: Make a GET Request to a URL that is advanced
So I have Chat Rooms and I have Messages. Then I have two urls: /messages and /rooms. And these display all your rooms and messages. Also a message can be assigned to a room. So in the Room API I have the messages assigned to that room. Let's say that the room is called 'Room1' and the messages are 'hey', 'yo' and 'wassup'. If I make a request to just /messages I will get all of the messages. Let's say that only two of the messages are assigned to 'Room1' and the other message is assigned to another room not named. I want a way to make a get request and only get those two messages assigned to 'Room1 with id = 3' (localhost:8000/rooms/3/messages) instead of: (localhost:8000/messages). This is an example of when I make a get request to /rooms/3/ { "id": 3, "name": "Room 1", "members": [ { "id": 1, "username": "william" }, { "id": 2, "username": "eric" }, { "id": 3, "username": "ryan" } ], "messages": [ { "id": 7, "content": "hej", "date": "2019-07-08", "sender": { "id": 1, "username": "william" } }, { "id": 8, "content": "yoyo", "date": "2019-07-08", "sender": { "id": 2, "username": "eric" } }, { … -
URL mapping not works as I want
Header section main-page By selecting 'About' from the main-page-options, /app1/about template is called, which is fine. However by selecting the Portfolio-drop-down items, I get an error. That is because the item is saved in mysite/app1/template folder and django is looking in the root of mysite. How can I map it? # Here is my mysite/app1/urls.py from django.urls import path from app1 import views urlpatterns = [ path('about/', views.about, name='about'), path('services/', views.services, name='services'), path('contact/', views.contact, name='contact'), path('portfolio1/', views.portfolio1, name='portfolio1'), ] # part of my views.py def portfolio1 (request): return render (request, 'portfolio1.html') 404 Error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='index'] app1/ ^static/(?P<path>.*)$ The current path, portfolio1.html, didn't match any of these. -
how to add fields dynamically with adding a new product to ManyToMany field
i'm trying create a Restaurant Order management system based on django when someone order some kinds of foods , it may order 3 Pizza with 2 sandwich , how to let the customer to define the quantities of each product , and then calculate with its prices class Restaurant(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Topping(models.Model): name = models.CharField(max_length=50) product_names = models.ManyToManyField(Restaurant, blank=True) quantity = models.PositiveIntegerField(default=1) #total price of orders , for one product for example : one pizza with one sandwich however they order more than one pizza and sandwich @property def total(self): return self.product_names.aggregate(Sum('price'))['price__sum'] i expected to provide a quantity field for each selected items : pizza : 3 , sandwich:2 , then calculate them (3*pizza price , 2*sandwich price) -
How to get an array with the counts of each field with the same parameter in Django in get_context_data?
I use a ListView for a template that displays all the Sensor in the database. Each Sensor can have more SensorViews and I'm trying to display in the same tempalte how many views each sensor has. The models are related to eachother by a field called "sensor_id". Any idea how I could do this in views.py? The line that works to an extent is the following context['number_of_sensor_views'] = SensorView.objects.filter(sensor_id = F('sensor_id')).count() However, this counts all SensorViews in the database and displays the same value for all entries. Any idea how I could count, store and display them individually? -
How to fix "dictionary update sequence element # 0 has length 104; 2 is required" error
I want to create a login page, when the username and password are incorrect there is this error "dictionary update sequence element # 0 has length ... is required". How to correct this error? forms.py class LoginForm(forms.Form): username = forms.CharField(max_length=250, required=False) password = forms.CharField(max_length=250, required=False) views.py class LoginView(View): template_name = 'login/index.html' form_class = LoginForm def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) next_var = request.GET.get('next') # redirect to url in next var else return to login home page return redirect('%s' % next_var) if next_var else redirect('%s' % settings.LOGIN_REDIRECT_URL) return render(request, self.template_name, {'form': form}) When the fields are not filled there is this error "dictionary update sequence element #0 has length 104; 2 is required" that appears. but when I log in and I go back to the login page to log in without anything filled in I'm reported that the fields are not filled -
ERRORS: book.Book.author: (fields.E300) book.Book.author: (fields.E307)
my English is poor , sorry this is my struct bookstore ---author(app1) ---book(app2) from django.db import models from author.models import Profile from django.contrib import admin class Book(models.Model): title = models.CharField(max_length = 150) page = models.IntegerField() price = models.IntegerField() author = models.ForeignKey( 'Profile', on_delete=models.CASCADE,) publish_date = models.DateField() class Meta(object): db_table = "book" class BookAdmin(admin.ModelAdmin): pass admin.site.register(Book, BookAdmin) mysql have some data , now I want to use them to show my web ,not to do that creat data in database thank you guys!!! I have a question My Django == 1.9 , python == 3 , windows10 I want to use mysql (my database contect is really do it) when I find some resource, I will see that "python manage.py sql [appname]" it is Django to SQL when I want to use Django to mysql Can I "python manage.py inspectdb"?? it will have a models.py "python manage.py sql [appname]" = "python manage.py inspectdb" ? ERRORS: book.Book.author: (fields.E300) Field defines a relation with model 'Profile', which is either not installed, or is abstract. book.Book.author: (fields.E307) The field book.Book.author was declared with a lazy reference to 'book.profile', but app 'book' doesn't provide model 'profile'. -
how to fix the following error regarding fetching url
i am not able to access those urls mentioned in program //urls.py from django.conf.urls import include, url from rest_framework import routers from imgstore.views import QueryImage from imgstore.views import ImageActionViewSet # this is DRF router for REST API viewsets router = routers.DefaultRouter() router.register(r'api/v1/imgaction', ImageActionViewSet, r"imgaction") router.register(r'api/v1/queryimage', QueryImage, r"queryimage") urlpatterns = [ url(r'', include(router.urls, namespace='imgaction')), url(r'', include(router.urls, namespace='queryimage')) ] Error occured while running server: Exception in thread django-main-thread: Traceback (most recent call last): File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/urls/resolvers.py", line 581, in url_patterns iter(patterns)TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/root/.pyenv/versions/3.5.7/lib/python3.5/threading.py", line 914, in _bootstrap_innerself.run() File "/root/.pyenv/versions/3.5.7/lib/python3.5/threading.py", line 862, in runself._target(*self._args, **self._kwargs) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapperfn(*args, **kwargs) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_runself.check(display_num_errors=True) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checksreturn checks.run_checks(**kwargs) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checksnew_errors = check(app_configs=app_configs) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolverreturn check_method() File"/root/.pyenv/versions/3.5.7/lib/python3.5/sitepackages/django/urls/resolvers.py", line 398, in checkfor pattern in self.url_patterns: File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/utils/functional.py", line 80, in get__res = instance.__dict[self.name] = self.func(instance) File "/root/.pyenv/versions/3.5.7/lib/python3.5/site-packages/django/urls/resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'image_storage.urls' does not appear to have any patterns in it. … -
Unable to display the list object retrieved from python dajngo -view to ajax autocomplete
I'm passing list object from view to ajax autocomplete in template but unable to show the no Cars found in the drop down list I'm passing a list object as 'No Cars Found' if no objects found in dB and if found the relevant objects are sent.But i Could see DB objects are shown in the dropdown but 'No Cars Found' is not shown in the Dropdown when no objects found. < script type = "text/javascript" > jQuery(function complete() { $(".basicAutoComplete").on('keyup', function() { var value = $(this).val(); $.ajax({ url: "{% url 'ajax_autocomplete' %}", data: { 'search': value }, dataType: 'json', success: function(data) { var carslist = data.list; list = carslist; $(".basicAutoComplete").autocomplete({ source: list, minLength: 2, }); } }); }); }); < /script> View def autocomplete(request): if request.is_ajax(): q=request.GET.get('search') queryset = Cars.objects.filter(car_model__istartswith=q).values('car_model') list = [] for i in queryset: list.append(i['car_model']) if not list: list.append('No Cars Found') data = { 'list': list, } return JsonResponse(data) I need No Cars Found to be displayed in the dropdown when no matching cars found in DB. -
Modifying queryset in changelist_view on Django Admin
I need to modify the final queryset used by the changelist in the django admin. I believe (correct me if I'm wrong) I can achieve this by overriding changelist_view(), but trying to change the queryset doesn't work, just original queryset loads in the admin. def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response response.context_data['cl'].queryset = qs.filter(pk__in=qs.order_by().values('pk').distinct('target')) return response I thought that changing the context data for the changelist would achieve this, but it didn't work. How can I do this, note I need to modify the final queryset after all other filters have been applied. -
Clear Cookies and Session data when user logs out from Django web app when using built-in logout url
I am having a problem with me Django web application. Every now and then I get Request Header Or Cookie Too Large nginx error message when I get the site. This is solved by me deleting cookies in inspect element > application > cookies > clear. Obviously I dont want nor expect users of the app to do that whenever this issue pops up. I am using the built-in logout url in the template of my Django application: <a href="{% url 'logout' %}">Log Out</a> And I want to clear the cookies created including some session data I added before when a user logs out. Session data added like : session = request.session session['claim'] = a_url Whether from within Django or using some onclick jquery event in the template that's fine. I prefer it to be done from Django as then I can also clear the cookies if a logged out users requets the page (as a user might simply close the app without logging in). If a logout function (ie path) needs to be created to clear cookies, then please include that in your answer. But JQuery is fine as well. Thanks in advance. -
With docker compose, how do I access a service internally and externally using the same address?
My problem boils down to this: I have two services in docker compose: app and storage. I'm looking for a way to access the storage service (port 9000) from inside app and from outside using the same address. app is a Django app using django-storages with S3 backend. storage is a minio server (S3 compatible, used only for development). From app, I can access storage using http://storage:9000. From outside docker, I can access storage at http://localhost:9000, or http://0.0.0.0:9000, or even at http://192.168.xxx.yyy (using a different device on the network). No surprises there. However, when the URL is generated, I don't know whether it's going to be used internally or externally (or both). docker-compose.yml services: app: build: backend/ ports: - "8000:8000" volumes: - ./backend/src:/app/src command: /usr/local/bin/python src/manage.py runserver 0.0.0.0:8000 storage: image: minio/minio:RELEASE.2019-06-19T18-24-42Z volumes: - storage:/data environment: MINIO_ACCESS_KEY: "DevelopmentAccessKey" MINIO_SECRET_KEY: "DevelopmentSecretKey" ports: - "9000:9000" command: minio server /data volumes: storage: I've looked into changing the backend to yield endpoint urls depending on the context, but that is far from trivial (and would only be for development, production uses external S3 storage, I like to keep them as similar as possible). I've played around with docker-compose network configs but I cannot seem to … -
How to use ModelChoiceField in DRF?
I am trying to convert my form that was written earlier to django rest serializer but it does't work. Could you help me to solve this problem please? this is my form: class TripSearchForm(forms.Form): departure = ModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) destination = ModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) How to built proper serializer? -
How to avoid repeating query in loop for fetching data
I am sending site list with some its fields. Where some fields (three types payment amount with different statuses) we are fetching from other tables. Right now for each iteration of loop three queries are executing. I have mentioned below lines which are executing for each iteration In below code I am trying to get all main payment amount and summing that amount. Also there are some statuses of payment like payment raised, payment approved, payment completed. main_payment_raised = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('quotation',flat=True)) main_payment_approved = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('quotation',flat=True)) main_payment_paid = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('quotation',flat=True)) partial_payment_raised = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('amount',flat=True)) partial_payment_approved = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('amount',flat=True)) partial_payment_paid = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('amount',flat=True)) extra_payment_raised = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('amount',flat=True)) extra_payment_approved = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('amount',flat=True)) extra_payment_paid = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('amount',flat=True)) This entire functionality is consuming more time. Is there any optimized way to get result in minimum complexity P.S. I am using Django 1.11 and Python 2.7