Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do remote authentication in dpahne server
Currently I am using Django channels, so to run the web server I have used daphne and run worker. How please help me how to do remote authentication ? or any reverse proxy Please help -
How to construct csrfmiddlewaretoken from a given csrftoken using javascript?
I'm working how to login to a django site with postman. Using Charles I can see that a csrfmiddlewaretoken token is created somehow. Given csrftoken=JDmmXqnLK35WCLha1PVOhFWITaKZs9eeAWBfuqXUxZEt3yDHmNoOyzMyJUQF5aQd the csrfmiddlewaretoken sent was v3I6Io9H8OoZcp4ATyszhAepdQAEp617mmXZfoJQVKXwDcq7ewVzyu4f3AGk27D6 Can v3I6Io9H8OoZcp4ATyszhAepdQAEp617mmXZfoJQVKXwDcq7ewVzyu4f3AGk27D6 be constructed from JDmmXqnLK35WCLha1PVOhFWITaKZs9eeAWBfuqXUxZEt3yDHmNoOyzMyJUQF5aQd using javascript? -
how to make left join in django?
this is my first model class DipPegawai(models.Model): PegID = models.AutoField(primary_key=True) PegNamaLengkap = models.CharField(max_length=100, blank=True, null=True) PegUnitKerja = models.IntegerField(null=True,blank=True) and this is my second model class DipHonorKegiatanPeg(models.Model): KegID = models.AutoField(primary_key=True) PegID = models.ForeignKey(DipPegawai, blank=True,null=True) KegNama = models.Charfield(max_length=100,null=True,blank=True) i want to make left join with this model, something like this in mysql query SELECT PegNamaLengkap, KegNama_id FROM karyawan_dippegawai AS k LEFT JOIN honorkegiatanpeg_diphonorkegiatanpeg AS h ON k.PegID = h.PegID_id WHERE PegUnitKerja = 3 GROUP BY k.PegID how to make left join with django orm same like mysql query above? -
Django does not appear to be sending disabled fields with POST data
I have the following in my forms.py class RegistrationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['amount_due'].widget.attrs['disabled'] = True This shows the field grayed out on the form. But from the Debug output, I see that the field is not being passed along with the POST data. Once I change it to 'readonly' from 'disabled', it works. What is the difference between readonly and disabled? -
Session auth_user_id not correct in django
In my views.py, in some view, i have uid = request.user.id this gives the id of the user that is logged in right now which i display on my template and is coming out to be correct. But the same id should also be sent to the session as auth_user_id which is according to sessions table /admin/sessions/ here is not getting displayed. No matter which user is logged in, it always shows {u'_auth_user_hash': u'ca7e738308ed261de83fe3c80c9a4657b37e8c81', u'_auth_user_id': u'2', u'_auth_user_backend': u'django.contrib.auth.backends.ModelBackend'}. uid=2 is the superuser(admin) in my table. I can't seem to figure out why this is happening? Any ideas? Also only one session is stored in the session table. -
django two model serializer in filter count
i want django serializer list in filtering count (Model <-> Foreign <-> Foreign(Count)) look my Model class Test(models.Model): item = CharField title = CharField class TestChild(models.Model): test = ForeignKey(Test) child_title = CharField class TestChildType(model.Model): child = ForeignKey(TestChild) type = BooleanField Test ChildType Model type field use filter(type=false).count() filter(type=true).count() testFalseCount in filtering false value testTrueCount in filtering true value and want serializer { item:'mouse', title:'goood Mouse' child:[ { child_title:'childGood' testFalseCount:4 testTrueCount:3 }, ... ] } -
Extract only used styles in html from style sheet
I am trying to increase the performance of my site by getting past render blocking css. Only one file seems to be a problem, and thats a minified bootstrap stylesheet I get from a CDN. I have tried multiple different approaches, but nothing has worked. I would like to have a copy of the Bootstrap CDN stylesheet in my project, and edit it so it only has the css I am currently using on my site. Is there a way to serialize your site, and remove any styles from a stylesheet that aren't being used ? I have read about several different takes on it, but most of them don't work in browsers besides Chrome, and break when hitting media queries in the stylesheet. -
Django CSRF verification failed even with {% csrf_token %}
POST requests to the Django view below result in (403) CSRF verification failed. I've confirmed that the hidden csrf token gets rendered in the page's source. I am also able to make POST requests without errors in other views. I'm unsure how to debug further. views.py: def email(request): if request.method == 'POST': email = request.POST['email'] fd = open('emaildb.csv','a') fd.write(email+',somefile\n') fd.close() return render(request, 'receipts/email.html', {'text':'Thanks, we''ll get back to you soon.'}) else: return render(request, 'receipts/email.html',) email.html: <form action="email" method="post" enctype="text/plain"> {% csrf_token %} E-mail:<br> <input type="text" name="email"> <input type="submit" value="Send"> </form> -
How to find User queryset matching self.request.user
How do we find User queryset matching self.request.user? logged_in_user = User.objects.filter(id=self.request.user.id) I wish there is much efficient way to doing this. (such as get_user_model(self.request.user)) ? Thanks! -
Django multiple schemas with foreign keys on each
So I have a database that has multiple schemas in django. One schema holds the api service end if you will, while the other schema has the cms and user information. How do I reference items from the other schema? postgres spits up a relation "" does not exist The trouble is that I need items on each schema for foreign keys. Any hacky solutions are welcome, as I believe I am dealing with a poorly put together project. -
docker is not running django server
I am new to docker and I'm trying to host a django project in docker. I tried to follow the tutorial from here but instead of postgresql, I use sqlite. I tried to run docker-compose up but docker was stuck at this: my Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ and my docker-compose.yml: version: '3' services: db: image: spartakode/sqlite3:latest web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Can anyone help me with this? Thank you -
Checkbox instead of boolean writting
models.py @python_2_unicode_compatible class Request(RequestProcess, FolderLinkMixin, TimeStampedModel): DENIED_AT_STATE_CHOICES = ( ('application', _('application')), ('documents', _('Documents')), ('validation', _('Validation')), ('evaluation', _('Evaluation')), ('signature', _('Signature')), ('deposit', _('Deposit')), ) folder_auto_create_childs = [] customer = models.ForeignKey('customers.CustomerProfile') request_type = models.CharField( _('Type'), max_length=15, choices=settings.LOANWOLF_REQUEST_TYPE_CHOICES) state = dxmodels.StateField(RequestWorkflow) validation = models.OneToOneField( 'core.ValidationData', blank=True, null=True) created_by = models.ForeignKey('users.User') rejection_reason = models.CharField( _('Reason of denial'), max_length=250, blank=True, null=True) expires_at = models.DateTimeField(_('Expires at'), blank=True, null=True) copied_from = models.OneToOneField( 'requests.Request', blank=True, null=True, default=None) delete = models.BooleanField(default=False) notes = GenericRelation(Note) contract = models.OneToOneField('contracts.Contract', on_delete=models.SET_NULL, blank=True, null=True, default=None) models.py class RequestsIndexView(StaffRestrictedMixin, FrontendListView): ... class Meta: ordering = ('-created', '-modified') sortable = ('created', 'state', 'modified') list_filter = ('state', 'request_type', created_at, modified_at, entered_state, entered_state_at, expired_at, expired_at_state, 'denied_at_state', rejected_or_denied_state, rejected_or_denied_state_at,) list_display = ( 'product', 'customer_menu', 'state', 'request_type', 'modified', 'created', 'delete_request' ) I put delete = models.BooleanField(default=False) in a my models.py file and I added delete in the Meta class from Request class view, and it showed me that picture instead of multiple checkboxes. How could I fix that so that it show me a checkbox? Please let me know if the question is unclear -
Django: Calling a model's function in my template - not working
I'm trying to call a function from my model (check_nick) in my template. It appears that the template is successfully hitting the function since the items in the function are printed. However I'm not getting the expected result (True) as the user.group I'm testing with is NICK which is part of the NICK_BRANDS list. MODEL.PY: NICK_BRANDS = ['NICK', 'NICKT', 'NICKN', 'NICKK', 'NICKA'] class User(): group = models.ForeignKey(Brand, null=True, blank=True) def check_nick(self): brand = self.group print brand //prints NICK print brand in NICK_BRANDS //prints False (should be True!) if brand in NICK_BRANDS: return True else: return False TEMPLATE: {% if user.check_nick %} //add some markup {% endif %} -
How could you get the local time in django?
I am trying to get the local time but I get the wrong time date all the time: from django.utils import timezone import datetime date = str(timezone.localtime(timezone.now()).now().strftime('%Y-%m-%d')) Local region: Europe/Prague -
Get list of objects with one object from m2m field pointing to self
I have Business model with m2m field holds branches. class Business(models.Model): order = models.IntegerField() branches = models.ManyToManyField('self') And I want to get list of ordered businesses with only one (top) branch from the chain. For example let's the first letter means belonging to the chain, and the number means the sort order: AA-0 AB-1 AC-2 AD-3 B-4 C-5 D-6 E-7 FA-8 FB-9 FC-10 The list I want to get is: AA, B, C, D, E, FA Is it possible to do it with Django ORM or PostgreSQL? -
Django Rest Framework TemplateDoesNotExist about Filter
I used Django 1.10 with django rest framework. I want to filter the url like http://127.0.0.1:8000/api/weathers/?school_id=nhsh And the page will show up all the datas about the nhsh school_id. So I filters_backends and filters_fields under the WeatherViewSet But I am confused why after adding the filters_fields then cause the TemplateDoesNotExist at api/weathers It will open the django_filters/rest_framework/form.html link urls.py from django.conf.urls import include, url from rest_framework import routers from weather import views router = routers.DefaultRouter() router.register(r'weathers', views.WeatherViewSet) urlpatterns = [ url(r'^api/', include(router.urls,namespace='api')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] view.py from rest_framework import viewsets from weather.serializers import WeatherSerializer from .models import Weather from rest_framework import filters class WeatherViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('time' ,'temperature','humidity' ,'uv' ,'light','rainfall','school_id') queryset = Weather.objects.all() serializer_class = WeatherSerializer lookup_field = "school_id" serializers.py from .models import Weather from rest_framework import serializers class WeatherSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Weather fields = ('time' ,'temperature','humidity' ,'uv' ,'light','rainfall','school_id') -
ValueError at / Missing staticfiles manifest entry for ''
I'm trying to migrate from Django 1.9.7 to Django 1.11.5. I have three different django apps, and they are pretty much the same regarding packages and settings. I have deployed all three of them to a web server and two apps are working without any problems, but third one gives me headache - i get this error all the time: ValueError at / Missing staticfiles manifest entry for '' Here are the most relevant settings from settings.py: # -*- coding: utf-8 -*- from settings import * SECRET_KEY = '***' SITE_ID = 3 ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', '.example.com', '.example.com.', ] INSTALLED_APPS += ( 'storages', 'example', 'example2', 'el_pagination', 'debug_toolbar', ) ROOT_URLCONF = 'example.urls' WSGI_APPLICATION = 'example.wsgi.application' DEFAULT_FROM_EMAIL = 'web@example.com' MANAGERS = ADMINS CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'DEFAULT_MIDDLEWARE_ALIAS': 'default', 'DEFAULT_MIDDLEWARE_SECONDS': '300', 'DEFAULT_MIDDLEWARE_KEY_PREFIX': '', } } PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.SHA1PasswordHasher', ) #AWS_HEADERS = { # see http://developer.yahoo.com/performance/rules.html#expires # 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', # 'Cache-Control': 'max-age=94608000', #S } # AMAZON S3 & CLOUDFRONT SERVING MEDIA FILES AWS_S3_HOST = 's3.eu-central-1.amazonaws.com' AWS_STORAGE_BUCKET_NAME = '***' AWS_CLOUDFRONT_DOMAIN = '***.cloudfront.net' AWS_ACCESS_KEY_ID = "***" AWS_SECRET_ACCESS_KEY = "***" MEDIAFILES_LOCATION = 'example/media' MEDIA_ROOT = '/%s/' % MEDIAFILES_LOCATION MEDIA_URL = '//%s/%s/' % (AWS_CLOUDFRONT_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE … -
How can I serve a webpack'ed (Vue) app through Django without recompiling for every change?
I set up a Django project and want to develop a Vue frontend to go along with it. To set up the Vue app, I used vue init webpack myproject-frontend. Developing both separately is pretty straight-forward, using python manage.py runserver and npm run dev, respectively. Putting the app inside one page of my Django project is easy as well; if I build the Vue app using npm run build first. Obviously, that has the downside of being slow, plus I have to take care of the hash-containing file names (which can be automated, of course). Regarding npm run dev, I'm not too satisfied with only being able to see just the Vue app in the browser. I can still communicate with my API (taking care of CORS), but that's not how the website is going to look in the end. I plan to have multiple Vue components on the same page, and different components on different pages at one point, and that's not reflected by dev. How can I achieve the quickness of not having to rebuild constantly, while retaining the fidelity of not omitting the Django part of the application? I tried to look at what is served by … -
printing a factory error message in terminal django
I am getting an error message in django and I want to print it in the terminal to see wha tthe actual error is and figure out how to fix the error. can anyone help me. this is the error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/omarjandali/Desktop/yap/opentab/tab/views.py", line 1207, in loginAccountSynapse authorizeLoginSynapse(request, form) File "/Users/omarjandali/Desktop/yap/opentab/tab/views.py", line 1223, in authorizeLoginSynapse synapseUser = SynapseUser.by_id(client, str(user_id)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/models/users/user.py", line 132, in by_id response = client.users.get(id, full_dehydrate=full_dehydrate) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/api/users.py", line 54, in get response = self.client.get(path, **params) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/http_client.py", line 58, in get return self.parse_response(response) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/synapse_pay_rest/http_client.py", line 86, in parse_response raise ErrorFactory.from_response(response) synapse_pay_rest.errors.NotFoundError The thing i want to print is the following: packages/synapse_pay_rest/http_client.py", line 86, in parse_response raise ErrorFactory.from_response(response) Here is the code that is creating the issue, it is an api call to SynapsePays api. user_id = currentProfile.synapse_id synapseUser = SynapseUser.by_id(client, str(user_id)) print(synapseUser) bank_id = 'synapse_good' bank_pw = 'test1234' bank_code = 'fake' print(bank_code) print(bank_id) print(bank_pw) bank_type = 'ACH-US' args = { 'bank_name':bank_code, 'username':bank_id, … -
limiting a decimal value to only 2 decimal places in django
This is how I get average marks of a bunch of schools def get_clu_average(self): clu_strength = 0 clu_total = 0 for school in self.school_set.all(): clu_strength = clu_strength + school.strength clu_total = clu_total + school.get_average() * school.strength return clu_total / clu_strength So the value will be a decimal number. When I directly use that in template I am getting a lot of decimal places. How do I restrict the value to only 2 decimal places? -
Bypassing Django GenericKey using a property? Good or bad idea?
I have a model where an operator can be a Convive or a Manager. Instead of using a Generic Foreign Key field with operator attribute, is there something wrong doing the following: operator_convive = models.ForeignKey(Convive, blank=True, null=True) operator_manager = models.ForeignKey(Manager, blank=True, null=True) @property def operator(self): return self.operator_convive or self.operator_manager def save(self, *args, **kwargs): # ... override here to prevent operator_convive and operator_manager to be both None, or both not None. -
Checkbox instead of boolean writting
I put delete = models.BooleanField(default=False) in a my models.py file and I added delete in the Meta class from Request class view, and it showed me that picture instead of multiple checkbox. How could I fix that so that it show me a checkbox? -
Python - Max retries exceeded with url (only on production server)
I'm trying to connect to one webpage. This is my code: class AddNewSite(): def __init__(self, url, user=None, email=None, category=None, subcategory=None, date_end=None): self.url = url self.user = user self.email = email req = Request(self.url, headers={'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 \ Safari/537.36'}) self.page = urlopen(req).read() self.soup = BeautifulSoup(self.page) self.meta = self.soup.find_all('meta') In my views.py (It is a Django project) I have: try: page = AddNewSite(siteurl, user) except Exception as e: print(e) messages.add_message(request, messages.ERROR, 'ERROR') return render(request, 'mainapp/subcategory.html', context) Everything works fine on localhost. It connects to site without eny errors. On production server I get an exception. Below I paste error from logs. HTTPConnectionPool(host='exeo.pl', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x80897ff98>: Failed to establish a new connection: [Errno 60] Operation timed out',)) HTTPConnectionPool(host='exeo.pl', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x80940aeb8>: Failed to establish a new connection: [Errno 60] Operation timed out',)) HTTPConnectionPool(host='exeo.pl', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x80949fdd8>: Failed to establish a new connection: [Errno 60] Operation timed out',)) <urllib.request.Request object at 0x808b92048> Why problem exists only on production server? -
Django include static loaded html file
I'm writing a web app that requires a template to load an HTML file in a block that has been uploaded by a user and stored somewhere in the media directory, along with any images or other media referenced by the HTML file using relative paths. Is there some way to do this given the HTML file path is unknown? I want something like.... {% extends 'parent.html' %} {% block content %} {% include {{ htmlpath }} %} {% block content %} to fill the parents content block with a loaded version of the HTML file. -
Django - Inline formset - storing only the last row of the child model (in 1 to many relationship)
Python :3.6.2 Django : 1.11.4 We are trying to use foreignkey across apps. Address is consumed by both customer and agent. We are also using inline formset. Form showing up correct. Please see below for the picture. Create Agent Screen However, when you save it, it saves just the just last of address. Also please note that in edit, a blank line is added which I think should not added by default. Please see below for the pic. Edit Agent screen Folder structure apps (Folder) agent (app) models.py views.py customer (app) models.py views.py sharedmodels(app) models.py forms.py agent/views.py from django.shortcuts import render # Create your views here. from django.db import transaction from django.urls import reverse_lazy from django.views.generic import CreateView, UpdateView, ListView from apps.agent.models import Agent from apps.sharedmodels.forms import AgentAddressFormSet from multiApps.logger import log class AgentList(ListView): model = Agent class AgentCreate(CreateView): model = Agent fields = ['first_name'] #log.info(fields) class AgentAddrLocArefCreate(CreateView): model = Agent fields = ['first_name'] success_url = reverse_lazy('agent-list') def get_context_data(self, **kwargs): data = super(AgentAddrLocArefCreate, self).get_context_data(**kwargs) log.info('i m here 1') if self.request.POST: log.info('i m here 2') #data['location'] = LocationFormSet(self.request.POST) data['address'] = AgentAddressFormSet(self.request.POST) #data['agentreferal'] = AgentReferalFormSet(self.request.POST) else: #data['location'] = LocationFormSet() data['address'] = AgentAddressFormSet() #data['agentreferal'] = AgentReferalFormSet() return data def form_valid(self, form): context = …