Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to send many requests asynchronously with Python
I'm trying to send about 70 requests to slack api but can't find a way to implement it in asynchronous way, I have about 3 second for it or I'm getting timeout error here how I've tried to t implement it: import asyncio def send_msg_to_all(sc,request,msg): user_list = sc.api_call( "users.list" ) members_array = user_list["members"] ids_array = [] for member in members_array: ids_array.append(member['id']) real_users = [] for user_id in ids_array: user_channel = sc.api_call( "im.open", user=user_id, ) if user_channel['ok'] == True: real_users.append(User(user_id, user_channel['channel']['id']) ) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(send_msg(sc, real_users, request, msg)) loop.close() return HttpResponse() async def send_msg(sc, real_users, req, msg): for user in real_users: send_ephemeral_msg(sc,user.user_id,user.dm_channel, msg) def send_ephemeral_msg(sc, user, channel, text): sc.api_call( "chat.postEphemeral", channel=channel, user=user, text=text ) But it looks like I'm still doing it in a synchronous way Any ideas guys? -
CAS Server url configuration raising a 403
After my last question I managed to figure out how to setup django-mama-cas and django-cas-ng for the most part. Had to port django-cas-ng to work on Django 1.11 and my setup. Now, I think my MAMA_CAS_SERVICES setting might be wrong for the services url. Lets say I got to seconddomain.com/accounts/login. This sends me to mycasserver.com/cas/login where I can login. Upon logging in there it adds a query to the url but I get a 403 (permission denied) on urls of this form. Example: mycasserver.com/cas/login?next=ticket....... This happens when one domain is still logged in but the other isn't (the one I'm logging into) since I'm not forcing the signout to propagate between the domains. My MAMA_CAS_SERVICES setting: { 'SERVICE': '^https?://mydomain1.herokuapp.com/', 'CALLBACKS': [ 'mama_cas.callbacks.user_name_attributes', ], 'LOGOUT_ALLOW': True, 'LOGOUT_URL': 'https://mycasserver.herokuapp.com/cas/logout', }, { 'SERVICE': '^https?://mydomain2.herokuapp.com/', 'CALLBACKS': [ 'mama_cas.callbacks.user_name_attributes', ], 'LOGOUT_ALLOW': True, 'LOGOUT_URL': 'https://mycasserver.herokuapp.com/cas/logout', }, -
Django: How to handle duplicate form submission
How to handle second submission duplicate request If user was trying to refresh the page, When the first submission is not finished yet because of server lag. client side disabling submit button to avoid multiple submits. and handled Post/Redirect/Get pattern after form submit redirect to success view I believe both are handled well. class SomeView(View): def post(self, request, *args, **kwargs): if form.is_valid() if request_exists(request): # here I can raise the exception also # But How I redirect the customer to sucess page # If 1st submission got success response. else: # here I have called internal api to get/post some data. # user refreshes before this call has completed. ... # once getting respose its ALWAYS redirect to new page return HttpResponseRedirect('/thanks/') But how to handle the case If delay from getting a response from API call. I need to delay until the first submission finishes. Then I have to send the user to the thanks page. -
Can we retrieve image properties from image after uploading in server?
I want to know the image properties like image pixels and dpi etc after uploading image in server using Python language. what is the best possible approach/technique to use.Thanks for your help. -
Get the values from one app to another in Django
I am working on creating shopping cart. I am still in learning phase. I need to know how I can pass/use values from shop's models.py to cart's cart.py. shop/models.py class Product(models.Model): delivery_price = models.DecimalField(max_digits=10, decimal_places=0,default=0) support_price = models.DecimalField(max_digits=10, decimal_places=0,default=0) cart/cart.py : I think this is the file where I need to get delivery_price and support_price. I dont know how I can get these two values. I want to add these prices and multiply it by quantity (something like Product.delivery_price + Product.support_price * item.quantity -> not sure about the way this is being done) How is this flow working? If anyone help me understand, it would be great. class Cart(object): def __init__(self, request): def add(self, product, quantity=1,update_quantity=False, support_req=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] … -
Django queryset filter weekday is different in database
I'm using Django 1.10 with Postgres. I have a class defined as : class Availability(models.Model): profile = models.ForeignKey(Profile) date = models.DateField() And I'd like to get all the availabilities which date is a monday. In my database, I have a availibity which date is a monday. I used : Availability.objects.filter(profile=profile, date__week_day=2) as defined in the Django doc, 2 being monday : https://docs.djangoproject.com/en/1.10/ref/models/querysets/#week-day But it returns no objects. I then tried to change the week_day and the queryset returns the right object when I used date__week_day=4. I tried with other week days, and it appears that their is always a gap of 2 weekdays between the query_set and the database. Is there a configuration to set which day should be the start of the week ? -
Django Trunc data to 15 minutes
I am currently using the Truc function of Django to aggregate some data within the day and hour. I would like to do the same but over 15 minutes, instead of an hour or just a minute but I can't figure it out. Here is an example of my current query: data_trunc = data_qs.annotate( start_day=Trunc('date_created', 'minute', output_field=DateTimeField())) .values('start_day', 'content', 'device') The problem lies with the 'minutes' argument that can be passed to Trunc. As far as I get it, there is no choice inbetween 'hour' and 'minutes'. How can I group my data over 15 minutes and have a larger time span for the data grouping ? I know that I could do this by hand afterward but I'd really like to have the database do this for me since there is a large dataset to compute and this way is the most efficient one I have yet. If this is the only way though I am opened to suggestions to the most efficient ways to get around this. Thanks for your help -
405 on Exporting CSV file in django
I'm trying to export some data to downloadable csv file. When I click "Export" button on my website everything works up to a point when I get 405 response. The post method works as expected, in response I see all expected data. The filtering ptocess below works as expected as well. Here is the view class: class ExportInvoicesToCsvView(View, IsSuperuserMixin): http_method_names = ['post', 'get'] def post(self, request, *args, **kwargs): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = ( 'attachment; filename=raport.csv' ) writer = csv.writer(response, delimiter=';') filters = json.loads(self.request.body.decode('utf8')) data = Data.objects.filter(filters) writer.writerow([ 'data.a', 'data.b', 'data.c', 'data.d', 'data.e' ]) return response The url config is as follows: url( r'^invoices-csv/$', ExportInvoicesToCsvView.as_view(), name='invoices-csv' ), And html template: <a href="{% url 'accountant:bills:invoices-csv' %}" type="button" class="btn btn-sm btn-default" ng-click="getSelected()"> <i class="fa fa-files-o fa-2x pull-left"></i> &nbsp;{% trans 'Exportuj do csv' %} </a> -
Signal Handler Issue
First off I'm using LDAP authentication with Python 3.6 and Django 1.11, if a user is verified with AD it will create the username, password in my User table. Then I have a pre-populated table which is not to be modified or changed called AllEeActive that has a primary key of employee_ntname which I made a OneToOneField using the following class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) 40 other fields @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: AllEeActive.objects.create(employee_ntname=instance) AllEeActive.objects.get(employee_ntname=instance).save() @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: AllEeActive.objects.create(employee_ntname=instance) AllEeActive.objects.get(employee_ntname=instance).save() class Meta: managed = False def __str__(self): return self.employee_ntname I combined my create and save into one signal call, but for some reason it gives me the error message that accounts.models.DoesNotExist: AllEeActive matching query does not exist. Any idea as to why this is the name of the database table and my model? -
Connect Django with existing remote MySQL schema
Im trying the get data from an existing remote MySQL table with raw SQL in Django. In other words I do not have to create tables (models in Django) - just read data in a table in a 1st step. The following class is working on the localhost class Person(models.Model): first_name = models.CharField(20) last_name = models.CharField(20) for p in Person.objects.raw('SELECT * FROM myapp_person'): print(p) The result: John Smith Jane Jones How can I define a class or function to get data out of an existing database.table, based on raw SQL, without generating first a class for creating the table ? Many thanks ! -
In Django how to get this pandas dataframe to a template?
django newbie question: Documentation with django and pandas focuses on models. I need to understand better how to trace the model, view and template where pandas is involved. Here is an application problem: I am trying to display mobile telephone allowances in an app. For example, each mobile connection has a mandatory tariff and also four optional, value added services ('VAS'). Tariffs cannot be VAS, but you could have the same VAS four times to boost your allowances. There is a single table 'Tariff' for managing the details of all tariffs and VAS. For each call line identifier (mobile phone connection), we need to read the call minutes, data megabytes and text count allowances that sum from the associated tariff and four VAS columns. # models.py class Tariff(models.Model): tariff_name = models.CharField(max_length=200, unique=True, db_index=True) minutes = models.IntegerField(blank=True, null=True,) texts = models.IntegerField(blank=True, null=True,) data = models.FloatField(null=True, default=0) is_tariff_not_VAS = models.BooleanField(default=True) class CallLineIdentifiers(models.Model): mobile_tel_number = models.CharField(max_length=11, blank=False, null=False, db_index=True) tariff = models.ForeignKey(Tariff, related_name = 'tariffName' ) vas_1 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_2 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_3 = models.CharField(max_length=100, blank=False, null=False, default=0,) vas_4 = models.CharField(max_length=100, blank=False, null=False, default=0,) So far, so good. I can render an html page displaying allowances for … -
Dockerizing DJango app error: ModuleNotFoundError: No module named 'django'
I am trying to Dockerize a DJango app that is already complete (and working). To do so, I am following this link here: https://docs.docker.com/compose/django/ problem When running docker-compose up Removing intermediate container 401e0a3db63c Step 12/14 : RUN DATABASE_URL=none /venv/bin/python manage.py collectstatic --noinput ---> Running in 6dcffbe27155 Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? here is the Dockerfile I am using FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN set -ex \ && apk add --no-cache --virtual .build-deps \ gcc \ make \ libc-dev \ libffi-dev \ zlib-dev \ freetype-dev \ libjpeg-turbo-dev \ libpng-dev \ musl-dev \ linux-headers \ bash \ pcre-dev \ postgresql-dev \ python3-dev \ && pyvenv … -
Django multiple active item carousel
I am pulling the products from database and trying to display them in multiple frames/items of carousel on a screen rather than a single item using for loop. This is what my carousel looks like at present, as you will notice only one item is displayed, but i want it to display 4 items at one slide and next four on clicking arrow button and so on. click here to see my carousel image. my Django code looks like this-- <div id="recommended-item-carousel" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for prod in pro %} <div class="item{% if forloop.first %} active{% endif %}"> <div class="col-sm-3"> <div class="product-image-wrapper1"> <div class="single-products"> <div class="productinfo text-center"> <!--sample image, same for all--><img src="{% static 'header/images/home/2508__14291.1437672247.200.200.jpg' %}" alt="" /> <h2>{{prod.productname}}</h2> <p>{{prod.producttype}}</p> <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a> </div> </div> </div> </div> </div> {% endfor %} </div> <a class="left recommended-item-control" href="#recommended-item-carousel" data-slide="prev"> <i class="fa fa-angle-left"></i> </a> <a class="right recommended-item-control" href="#recommended-item-carousel" data-slide="next"> <i class="fa fa-angle-right"></i> </a> </div> -
Upgraded from Django 1.8 to 1.1 and TemplateDoesNotExist error
I upgraded my Django version from 1.8 to 1.10 and I had to remove the patterns() in various files in my site_packages folder. I was getting errors like this: File "C:\Python27\lib\site-packages\import_export\admin.py", line 266, in get_urls my_urls = patterns( NameError: global name 'patterns' is not defined So, per the depreciation guidelines, I changed the code to this in the admin.py file. my_urls = [ url(r'^process_import/$', self.admin_site.admin_view(self.process_import), name='%s_%s_process_import' % info), url(r'^import/$', self.admin_site.admin_view(self.import_action), name='%s_%s_import' % info), ] return my_urls + urls I repeated this 3 times in the site_packages folder. However I'm now getting a TemplateDoesNotExist error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/view_shifts/ Django Version: 1.10.8 Python Version: 2.7.13 Installed Applications: ['django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'bootstrapform', 'pinax_theme_bootstrap', 'account', 'metron', 'pinax.eventlog', 'table', 'import_export', 'django_tables2', 'django_filters', 'wordcloud', 'mathfilters', 'capes_mantle', 'shift', 'usereval', 'finance'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine : This engine did not provide a list of tried templates. Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 42. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
AttributeError: module 'django.contrib.auth.views' has no attribute 'login'
I got error on my django rest framework, I am running it on windows 10 OS. this is the entire error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "c:\django\django\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "c:\django\django\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\django\django\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "c:\django\django\django\core\management\base.py", line 332, in execute self.check() File "c:\django\django\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "c:\django\django\django\core\management\commands\migrate.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "c:\django\django\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "c:\django\django\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "c:\django\django\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "c:\django\django\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "c:\django\django\django\urls\resolvers.py", line 385, in check for pattern in self.url_patterns: File "c:\django\django\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\django\django\django\urls\resolvers.py", line 524, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "c:\django\django\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\django\django\django\urls\resolvers.py", line 517, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen … -
Exclude one choice in a dropdown
Currently I have a drop down list, that is accessible for staff/admin personnel, as part of a ticketing system. In this list however, I'd like to deactivate one of the attributes ("needs review"), if the ticket is already "dealt with". My initial thoughts were to somehow solve this by setting in the settings.py (as a flag), but this is not advised. views.py formOrder_minimal = OrderModelForm_minimal_partII(request.POST) # allows change status, staff-only #formOrder_minimal = OrderModelForm_minimal(instance=order) # allows change status forms.py ''' def get_choices_needsReview(): order = Order.objects.get(id=id) print "order: {0}".format(order) if order.status == 2: # "erledigt" print "order is erledigt, now somewhere else" class OrderModelForm_minimal_partII(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderModelForm_minimal_partII, self).__init__(*args, **kwargs) self.fields['my_choice_field'] = forms.ChoiceField( choices=get_choices_needsReview() class Meta: model = Order exclude = ('nrVoting','created', 'deadline', 'customer') ''' class OrderModelForm_minimal(forms.ModelForm): """ mmh. dirty. allows status-edit in frontend. """ class Meta: model = Order exclude = ('nrVoting','created', 'deadline', 'customer') models.py class Order(models.Model): from .CHOICES import STATUS_CHOICES, dSTATUS_CHOICES, STATUS_CHOICES_ALREADY_DEALT, dSTATUS_CHOICES_ALREADY_DEALT customer = models.ForeignKey(Customer) created = models.DateTimeField(blank=True) lastUpdate = models.DateTimeField(blank=True, editable=False) user = models.ForeignKey(User,editable=False,blank=True,null=True) ip = models.CharField(editable=False,blank=True, max_length=78, verbose_name='IP') version = models.IntegerField(default=1, editable=False) deadline = models.DateField(blank=True,null=True) nrVoting = models.IntegerField(default=0) if settings.DISABLE_NEEDSREVIEW_ON_STATUS_PLANNING==True: status = models.IntegerField(choices=STATUS_CHOICES_ALREADY_DEALT, default=-1) else: status = models.IntegerField(choices=STATUS_CHOICES, default=-1) CHOICES.py STATUS_CHOICES = (-10, 'still not assigned'), … -
How to add version controlling functionality in a blog made with Django?
It will be a shared blog, many people can contribute to each blog post, i want to add a version controlling functionality, whenever anyone make any changes there would be a little line saying who edited that.like bottom: Sample Header by Alpha, Beta, Gama, omega This is a sample body text, this is cool, this is awesome. ----added by alpha on 27/10/17 : 6.05 Stackoverflow is awesome, it helped me a lot. ----added by beta blockers on 27/10/17: 8.09 Like this..is it possible? -
Filter on JSONField array
I have a book model class Book(): ... tags: JSONField() I have some records: Book(..., tags: ['Tech', 'Business']) Book(..., tags: ['Marketing']) I want to filter out the books those have tag 'Tech' or 'Business' query = Q ( Q(tags__contains='Tech') | Q(tags__contains='Business') ) I've tried to used contains, contained_by, has_key, has_any_keys but got no luck. The result is always empty. -
Does not match background image url on s3 with django
My django project was integrate with AWS S3, It perfectly working on my project, but that was in COMPRESS_ENABLED = False state, Issue: my style.css have lot of images set in background url property in classes, and finally collectstatic and compressed those files, the problem starting from there, if enabled compress. Then we get the files from cache folder, so the background image url was wrong, because the url under cache folder. Example: True - https://domain1.s3.amazonaws.com/img/location/location.jpg False - https://domain1.s3.amazonaws.com/css/style/img/location/location.jpg path of style.css - https://domain1.s3.amazonaws.com/css/style/style.css Regards, AJayan c -
create object with one to one attribute django
I want to create object with set attributes in create function. This is my profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile') employees = models.ManyToManyField(User, blank=True, null=True, related_name='boss') FatherName = models.CharField(max_length=20,default='',blank=True) NationalCode = models.CharField(max_length=20, default='') birth_date = jmodels.jDateField(null=True, blank=True) PhoneNumber = models.CharField(max_length=20,default='',unique=True) and when I create object emp = User.objects.create(first_name=FirstName, last_name=LastName, username=phonenumber,user__PhoneNumber=phonenumber) error is invalid keyword argument for this function. How can I set PhoneNumber value in Profile model when I try to create User model? tanks all -
How can I authenticate user both in websockets and REST using Django and Angular 4?
I would like to authenticate user both in websockets and REST using Django and Angular 4. I have created registration based on REST API. User after creating an account and log in can send messages to backend using websockets. My question is how can I know that the user authenticated by REST API (I use Tokens) is the same user who sends messages? I don't think that sending Token in every websocket message would be a good solution. Do you have any ideas? consumers.py: Something like this? def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) channel_session_user_from_http def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) @channel_session_user def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Next message' }) }) @channel_session_user def ws_disconnect(message): Group("chat").discard(message.reply_channel) -
docker compose cannot connect postgresql database with django
my django app cannot connect to postgresql. I'm using Dockerfile for django and build using docker-compose with postgres official image. docker-compose.yml version: '2' services: db: image: eg_postgresql expose: - 5432 environment: - POSTGRES_PASSWORD=docker - POSTGRES_USER=docker - POSTGRES_DB=postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/test_application ports: - "8000:8000" links: - "db:db" environment: - DATABASE_URL=postgres://docker:docker@db:5432/postgres - DJANGO_SECRET_KEY=x7-g-xu^h5k%h8860!7ksn=@)7q9frn9_l6tmefvf)y=0)d!uh output: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? docker-compose ps ubuntu@ip-172-31-7-117:~/dj1/helloworld$ sudo docker-compose ps Name Command State Ports ---------------------------------------------------------------------------------- helloworld_db_1 /usr/lib/postgresql/9.3/bi ... Up 5432/tcp helloworld_web_1 python3 manage.py runserve ... Up 0.0.0.0:8000->8000/tcp in app settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'docker', 'PASSWORD': 'docker', 'HOST': 'db', 'PORT': '5432', } } I tried in many ways to connect but the issue is same... -
Django Oauth2 Toolkit read access token from request body not headers
I have setup an OAuth2 provider using Django Oauth Toolkit, and it works fine. The issue is that the Client which is making requests to my API does not pass the access token in the headers (No "AUTHORIZATION : BEARER XXXXXXX"). Instead, the access token is passed in JSON data. How can I change the toolkit's behaviour to read the access token from the data ? -
Does pm2 support Django to make it forever application
I was trying to use pm2 to make the Django application run forever however I was unable to do that. Can any one help me out. Does pm2 really supports django -
How to apply filter after the retrieve methods?
I'm currently overriding the list method of the ModelViewSet and using filter_fields but I realized that the filter is applied before the list, so my list method is not being filtered by the query param. Is it possible to apply this filter after the list method? class AccountViewSet(viewsets.ModelViewSet): serializer_class = AccountSerializer filter_fields = ('country__name') filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) queryset = Account.objects.all() def list(self, request): if request.user.is_superuser: queryset = Account.objects.all() else: bank_user = BankUser.objects.get(user=request.user) queryset = Account.objects.filter(bank=bank_user.bank) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) When I do request using this URL http://localhost:8000/api/account/?country__name=Germany, it returns all the accounts filtered by bank but not by country.