Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, Django : Foreignkey accross apps is not working
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 frameset. If I put all this in one app, it is working fine including inline frameset. If I split into multiple apps, I have this error. Please see the pictures below. Foreignkey error Project folder structure Please note the apps the above folder structure. sharedmodels/models.py from django.db import models #from apps.agent.models import Agent class ContactInfo(models.Model): mobile_no = models.CharField(max_length=8) phone_no = models.CharField(max_length=10) class Location(models.Model): location_name = models.CharField(max_length=50) city = models.CharField(max_length=20, blank=True, null=True) state = models.CharField(max_length=20, blank=True, null=True) class Address(models.Model): #agent = models.Foreignkey(Agent) address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100) agent/models.py from django.db import models from apps.sharedmodels.models import Location, Address, ContactInfo class Agent(models.Model): first_name = models.CharField(max_length=20) location = models.ManyToManyField(Location) address = models.Foreignkey(Address) contactinfo = models.OneToOneField(ContactInfo) customer/models.py from django.db import models #from apps.agent.models import Agent, Address from apps.sharedmodels.models import ContactInfo, Address class Customer(models.Model): first_name = models.CharField(max_length=10) #address = models.OneToOneField(Address) contactinfo = models.OneToOneField(ContactInfo) address = models.Foreignkey(Address) Settings.py - installapps section # Application definition INSTALLED_APPS = [ 'apps.customer', 'apps.agent', 'apps.sharedmodels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
In Django, how can we get all cache keys stored in database (MySQL)
I am using per-view cache in Django and I want to refresh the cache whenever it get's stale. In the documentation I see no information on refreshing stale cache and after going through several threads I decided to use django-signals to send a signal to a function which will delete the cache records from DB. So my problem is how do we retrieve the keys and delete it? I see the default implementation provides a way to give an expiration time to cache (as in @cache_page(60 * 15) and it refreshes whenever we call the view after expiration time. Is there any way to refresh stale cache not based on predefined time? -
Multiple group by and join statements in Django
I have a following query in raw SQL and I want to rewrite it using Django ORM. SELECT id, username, COALESCE(total, 0) as total, COALESCE(sum1, 0) as sum1, COALESCE(sum2, 0) as sum2, COALESCE(sum3, 0) as sum3, COALESCE(sum4, 0) as sum4, COALESCE(sum5, 0) as sum5 FROM (SELECT s_id, SUM(am) AS total FROM S GROUP BY s_id ORDER BY total) AS total LEFT OUTER JOIN ( SELECT s_id, SUM(am) AS sum1 FROM submitted WHERE category = ‘m’ GROUP BY s_id ) AS sum1 USING (s_id) LEFT OUTER JOIN ( SELECT s_id, SUM(am) AS sum2 FROM submitted WHERE category = ’s’ GROUP BY s_id ) AS sum2 USING (s_id) I can group by a table in Django using: S.objects.values('s_id').annotate(total=Sum('am')) The problem is I need somehow to join this result with the table S and then again and again. Is there a way to accomplish than using Django ORM? -
docker-compoes.yml settings with Django + Gunicorn + NGINX does not work on `docker-compose up`
This is my folder structure. ./awesome_app ├── awesome_app │ ├── celery.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── awesome_app_to_do_list ├── db.sqlite3 ├── docker-compose.yml ├── Dockerfile ├── logs │ ├── nginx-access.log │ └── nginx-error.log ├── manage.py ├── nginx │ └── nginx.conf ├── requirements.txt ├── run └── start.sh This is my nginx.conf. upstream awesome_app { server unix:/home/notalentgeek/Downloads/awesome_app/run/gunicorn.sock fail_timeout=10s; } server { client_max_body_size 4G; listen 8080; access_log /home/notalentgeek/Downloads/awesome_app/logs/nginx-access.log; error_log /home/notalentgeek/Downloads/awesome_app/logs/nginx-error.log warn; location /static/ { autoindex on; alias /home/notalentgeek/Downloads/awesome_app/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://awesome_app; break; } } } This is my docker-compose.yml. version: "3" services: nginx: image: nginx:latest container_name: nginx_awesome_app ports: - "8080:8080" volumes: - ./:/src - ./nginx:/etc/nginx/conf.d depends_on: - web web: build: ./ container_name: django_awesome_app volumes: - ./:/src expose: - "8080" This is my start.sh. #!/bin/bash # PENDING: From the source here, # http://tutos.readthedocs.io/en/latest/source/ndg.html it says that it is a # common practice to have a specific user to handle the webserver. SCRIPT=$(readlink -f "$0") BASEDIR=$(dirname "$SCRIPT") DJANGO_SETTINGS_MODULE=awesome_app.settings DJANGO_WSGI_MODULE=awesome_app.wsgi NAME="awesome_app" NUM_WORKERS=3 VENV_BIN=${BASEDIR}"/venv/bin" SOCKFILE=${BASEDIR}"/run/gunicorn.sock" echo $SOCKFILE SOCKFILEDIR="$(dirname "$SOCKFILE")" VENV_ACTIVATE=${VENV_BIN}"/activate" VENV_GUNICORN=${VENV_BIN}"/gunicorn" # Activate the virtual environment. cd $BASEDIR source $VENV_ACTIVATE export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$PYTHONPATH:$BASEDIR # Create … -
Django:csrf token
When ever i am submitting the form i am getting csrfmiddlewaretoken=Mlhg830h3mLCuVD0sl1MTXUnSxFHMib6ZYtXmfZ8k1jZL1DA2IrNwzGVp2PymTCN&choice=1 in my url, even after including the csrf token also {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ froloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}" >{{ choice.choice_text }}</label><br/> {% endfor %} <input type="submit" value="Vote" /> </form> I have 'django.middleware.csrf.CsrfViewMiddleware' in my middleware settings. How to resolve this issue -
DJango Python File Upload how to preserve orginal file
I am trying to upload a file using Rest to a DJango Python API. But I noticed the file gets modified. Specifically a content-disposition is added to it. I haven't found a good way to remove this. The problem is I am trying to upload a tar that needs to be unzipped, but the modified content prevents unzipping the file. I’m using this file parser on a rest page: from rest_framework.parsers import FileUploadParser The following code seems to get the file for me in the post method of an APIView file_obj = request.FILES['file'] scanfile.file.save(file_obj.name, file_obj) Where scanfile is a model with a file field. The file gets saved with contents like this: --b3c91a6c13e34fd5a1e253b1a72d63b3 Content-Disposition: form-data; name="exclusion_file"; filename="exclusionlist.txt" My tar file contents here..... --b3c91a6c13e34fd5a1e253b1a72d63b3 My client looks like this: filename = "requirements.txt" exclusion = "../../exclusionlist.txt" headers = {'Content-Type': 'multipart/form-data;’, 'Authorization': 'JWT %s' % token, } url = "http://localhost:%s/api/scan/DysonGlobal/%s/" % (port, filename) #files = {'file': open(filename, 'rb'), 'exclusion_file': open(exclusion, 'rb')} # also tried this way but it just put the info in the same file and I see the headers in the file files = [('file', open(filename, 'rb')), ('file', open(exclusion, 'rb'))] x = requests.post(url, files=files, headers=headers) -
How to speed up Django when doing new changes to the views.py and urls.py?
Currently we have our production Django web app hosted in IIS and we have noticed that when we add new changes into the views.py or, specially, the url.py files, the changes take a while to be reflected in the server, that is, it can take an hour to see the changes. This does not happen when I modify the html files, changes take effect immediately. We also broke on purpose the url.py file by adding incorrect lines such as url1234567(r'^tickets/$', views.tickets_calculate), but this line did not take effect until several minutes later. Questions Why do the changes in these files take so long? How can I speed up this process of "refreshing of views.py and urls.py? -
Django ModelForm add data to context
On a ModelForm I have some fields that depend on the other. For example, class FactorForm(ModelForm): //field definitions class Meta: model=Factor fields=['name', 'type', 'sets'] sets is a select that depend on the type which is also a select. When type is changed, I should update the options of the sets. Therefore, I would like to put a list of fields to the template (i.e., refresh=['type']), so a JavaScript function can replace the form when a field given is changed. So, how can I put random data in the forms context? I can do that by overriding get_context_data with generic CBV's. But the ModelForm has no such method. Preferably, I would like to put the common logic in a ModelFormParent function, and list my refreshing fields under Meta: class FactorForm(ModelFormParent): //field definitions class Meta: model=Factor fields=['name', 'type', 'sets'] refresh=['type'] -
Celery/Celerybeat - inserting periodic task results into DB and how to see if task is running (when Celery is a daemon)
I have celery and celerybeat successfully running as daemons. I have also scheduled a task in my app.settings file. Im using DB as a results backend and have installed django_Celery_results. Using the demo task and set it to run every 1 minute, the DB has 0 entires and I cant see where a log would indicate a task is running or not. celery config: # Names of nodes to start # most people will only start one node: CELERYD_NODES="worker1" # but you can also start multiple and configure settings # for each in CELERYD_OPTS #CELERYD_NODES="worker1 worker2 worker3" # alternatively, you can specify the number of nodes to start: #CELERYD_NODES=10 # Absolute or relative path to the 'celery' command: CELERY_BIN="/usr/local/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="itapp" # or fully qualified: # Where to chdir at start. CELERYD_CHDIR="/itapp/itapp/" # Extra command-line arguments to the worker CELERYD_OPTS="flower --time-limit=300 --concurrency=8" # Configure node-specific settings by appending node name to arguments: #CELERYD_OPTS="--time-limit=300 -c 8 -c:worker2 4 -c:worker3 2 -Ofair:worker1" # Set logging level to DEBUG #CELERYD_LOG_LEVEL="DEBUG" # %n will be replaced with the first part of the nodename. CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" # Workers should run … -
How can I send user ID in Angular using both REST API and websockets
I am going to create chatbot using websockets. Each user can have their own account. I have Django backend and frontend written in Angular. I am not sure how can I send my user_id from frontend to backend, because I use in my project both Django Rest Framework and websockets, so it seems to me that frontend has to authenticate user both using websockets and REST and has to know that it is the same one user. However it seems to me that it is impossible to have one common authentication for REST and websockets. This is example JSON data that my backend has to receive: { "user_id":2, "message":"My message" } Any ideas how can I solve it? This is part of my Angular component: export class HomeComponent { response: string; response2: string; constructor( private chatService: ChatService, private router: Router, private http: Http, ) { chatService.messages.subscribe(msg => { this.response = msg.message; console.log("Response from backend: " + msg.message); }); } private message = { message: 'this is a test message' } sendMsg() { console.log('new message from client to websocket: ', this.message); this.chatService.messages.next(this.message); return this.message.message; } send(msg) { this.message.message = msg; this.sendMsg(); } login() { return this.http.get('/data', ) .map(response => response.json()) .subscribe(response2 … -
How do i put a time into a datetime field
I am getting times in the form of eg. 1:00 from a json file and I need to get them into a datetime field. How do I convert this into a datetime? -
Django's TestCase doesn't seem to clean up database between tests
I have written a test to check the integrity of the data I keep in my fixtures. It is a class inheriting from django.tests.TestCase, and it declares the fixtures it needs. When I run the methods in this class only, they pass. However, when I run all of my tests, some fixtures from other tests remain in the db, which makes the tests fail. I tried different variants, and for now I am overriding the _fixture_setup method to kill all db data before my test, but this can't be right. There must be a better way :) class FixturesTest(TestCase): fixtures = ["tariff.json"] def _fixture_setup(self): TariffModel.objects.all().delete() super()._fixture_setup() def test_tariff_fixtures(self): """Check the fixtures for tariffs""" ... Thanks. -
graphen-django mutation relationships
I am attempting to create a mutation with django-graphene that includes a relationship and return the related objects in the response. Django 1.11.5 graphene-django 1.2.1 Amazon Redshift Models import uuid from django.db import models from dwtools.sources.base_models import BaseModel class MasterAccount(BaseModel): master_id = models.CharField( max_length=36, help_text='''The UUID of the record.''', unique=True, default=uuid.uuid4) account_nm = models.CharField( max_length=255, null=True, blank=True, help_text='''The account's name.''') class Meta: managed = False db_table = 'account_dev' app_label = 'mappings' class PlatformAccount(BaseModel): platform_id = models.BigIntegerField(help_text='''Platform account ID''') master = models.ForeignKey(MasterAccount, to_field='master_id') class Meta: managed = False db_table = 'platform_dev' app_label = 'mappings' GraphQL models import graphene from graphene import ObjectType, String class PlatformAccountGraphQL(ObjectType): platform_id = String() class MasterAccountGraphQL(ObjectType): master_id = String() account_nm = String() platform_account = graphene.Field(PlatformAccountGraphQL) Schema class MasterAccountNode(DjangoObjectType): class Meta: model = MasterAccount interfaces = (relay.Node,) class PlatformAccountNode(DjangoObjectType): class Meta: model = PlatformAccount interfaces = (relay.Node,) class CreateAccount(ClientIDMutation): class Input: account_nm = String() ok = Boolean() master_account = Field(MasterAccountNode) platform_account = Field(PlatformAccountNode) @classmethod def mutate_and_get_payload(cls, args, instance, info): ok = True master_account = MasterAccount(account_nm=args.get('account_nm')) master_account.save(force_insert=True) # Testing ID platform_id = 123456 platform_account = PlatformAccount(master=master_account, platform_id=platform_id) platform_account.save() return CreateAccount(master_account=master_account, platform_account=platform_account, ok=ok) class Mutations(AbstractType): """Mutations for the mappings class.""" create_account = CreateAccount.Field() class Query(AbstractType): """The account query class for … -
JSONDecodeError while paginating using Django framework
I'm trying to add pagination to a custom search page and am running into the following error: JSONDecodeError. Below are two methods inside my view that I am using to get the search results. The first is meant to paginate the results, the second for a total dump of the results i.e., no pagination. def super_search(request): query = "chapel hill" BASEURL = "ip_address" query = request.GET.get("q") ip = request.GET.get("ip") params = { "q": query, } r = requests.get(BASEURL,verify=False, params=params) result_set_list = (r.json())['newsResults'] print("Type:"+str(type(result_set_list))) ## The type is <class 'list'> paginator = Paginator(result_set_list, 10) # Showing 10 results page = request.GET.get('page') try: result_set = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. result_set = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. result_set = paginator.page(paginator.num_pages) context = { "results": result_set, "title": "my Results" } return render(request,"resultsPage.html",context) def super_searchNoPagination(request): query = "chapel hill" BASEURL = "ip_address" query = request.GET.get("q") ip = request.GET.get("ip") params = { "q": query, } r = requests.get(BASEURL,verify=False, params=params) context = { "results": (r.json())['newsResults'], "title": "my Results" } return render(request,"resultsPageNoPagination.html",context) I get no error when calling the method super_searchNoPagination; the results get rendered fine. But … -
Migrating Django from 1.9 to 1.11: trouble with MultiValueField and MultiWidget behaviour
Here is a code that works as expected in Django 1.9: class MultipleBooleanField(forms.MultiValueField): def __init__(self, *args, **kwargs): self.fieldnames = kwargs.pop('fields') fields = [ forms.BooleanField(required=False) for x in self.fieldnames ] super(MultipleBooleanField, self).__init__(fields=fields, require_all_fields=False, *args, **kwargs) self.widget = MultipleBooleanWidget(widgets=[ f.widget for f in fields ]) self.widget.fieldnames = self.fieldnames def compress(self, datalist): # return a list of the fieldnames, datalist is a list of booleans print('compress datalist:', datalist) if self.required and not any(datalist): raise forms.ValidationError('You must choose at least one value') return [ self.fieldnames[i] for i in range(len(datalist)) if datalist[i] ] class MultipleBooleanWidget(forms.MultiWidget): def render(self, name, value, attrs=None, renderer=None): if not value: value = [ False for x in self.fieldnames ] rendered_widgets = [ x.render(name, value[i]) for i,x in enumerate(self.widgets) ] items = [ '%s %s' % (rendered_widgets[i], f) for (i,f) in enumerate(self.fieldnames) ] return ' '.join(items) def decompress(self, value): # return a list of boolean, value is a list of fieldnames print('decompress value:', value) if not value: return [ False for x in self.fieldnames ] return [ x in value for x in self.fieldnames ] With Django 1.11, it no more works, the ValidationError is always raised. The datalist is always a list containing only False. The decompress method is never called. … -
Getting the object from a GCBV in the view?
this feels like a terrible stupid question. But a GCBV (DetailView) uses the get_object_function to make a query and to fetch an object and return obj in the function. I want the obj in my actual view to create a gerneric relation and I don't seem capable of doing so. I'm aware that the solution is probably very simple. Be gentle with me ... I tried this out for about 45 min. and it just won't work ... class PostDetail(PostGetMixin, DateDetailView): model = Post date_field = 'pub_date' content_type = ContentType.objects.get_for_model(Post) obj = DateDetailView.get_object() obj_id = obj.id comments = Comment.objects.filter(content_tye=content_type, object_id=obj_id) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update( {"comments": self.comments} ) return context This line: obj = DateDetailView.get_object() does not work since I did not instanciate the class but I can't really instanciate the class in the view since it cant access all the necessary functions there. -
Class Based Views Inheritance Django
I have a base Class defined as follows: class FundDetailView(TemplateView): template_name = "fund_monitor/fund_details.html" model = FundAccount fund_account_id = None transmission = None start_date = None end_date = None def get_context_data(self, **kwargs): context = super(__class__, self).get_context_data(**kwargs) context['fund_account_id'] = kwargs['fund_account_id'] context['transmission'] = kwargs['transmission'] context['start_date'] = kwargs['start_date'] context['end_date'] = kwargs['end_date'] context['sbar'] = "fund_details" context['account_description'] = self.model.objects.get(id=context['fund_account_id']).account_description self.fund_account_id = kwargs['fund_account_id'] self.transmission = kwargs['transmission'] self.start_date = kwargs['start_date'] self.end_date = kwargs['end_date'] return context and I am creating another API class that would like to use the FundDetailView's parameters. I define it like so: class FundDetailApi(APIView, FundDetailView): option = 'default' model_class = NAV def get(self, request, **kwargs): print(self.fund_account_id) return Response("No Api Selected") However, I get the error: context['fund_account_id'] = kwargs['fund_account_id'] django_1 | KeyError: 'fund_account_id' Any ideas on how to resolve this issue? I simply want to access the fund_account_id , transmission, start_date, end_date specified in the parent class. -
How to overwrite Highcharts credits default settings
I've been trying to customize the settings of the credits on a Highchart but without success. I'm working on Django, passing data from Python to my html file in which the Highchart object is rendered, everything works except for the credits settings. See my code below: <div id={{ chartID|safe }} class="chart"> </div> <!-- Maps the Python template context variables from views.py to the Highchart js variables --> <script> var chart_id = "#chart_ID" var chart = {{ chart|safe }} var title = {{ title|safe }} var xAxis = {{ xAxis|safe }} var yAxis = {{ yAxis|safe }} var series = {{ series|safe }} </script> <!-- Highchart js. Variable map shown above --> <script> $(document).ready(function() { $(chart_id).highcharts({ chart: chart, title: title, xAxis: xAxis, yAxis: yAxis, series: series, plotOptions: {series: {borderColor: '#303030',allowPointSelect: true,cursor: 'pointer'}}, credits: {text: 'MyCompanyName',href:'mywebsite.com',color:'#303030',position:{align:'center',verticalAlign:'center'}} }); }); </script> With the above code, everything shows up nicely when I run it, even the plotOptions settings work ... but the credits update doesn't work. Credits still show the default settings, i.e. highcharts.com is shown at the bottom right corner of the graph and it doesn't update with my new settings. What am I missing here? Thanks. -
send email from djangocms-forms
I use djangocms-forms, I configure SEND FORM DATA TO E-MAIL ADDRESS: , SENDER EMAIL ADDRESS:, EMAIL SUBJECT: but the web-hosted does not send to the email address on the configuration. -
django loaddata fails because of concurrent database query
I am trying to migrate the database of one my django projects from sqlite to mysql. I first dumped the whole thing with ./manage.py dumpdata > dump.json and prepared the database with ./manage.py migrate and deleted any created data in the tables (This was necessary, as the dump holds all the data). When I wanted to import the data into the new database with ./manage.py loaddata, there were a lot of errors I was able to resolve, but I can't find the source of this error: Processed 330984 object(s).Traceback (most recent call last): File "/app/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 175, in load_label obj.save(using=self.using) File "/usr/local/lib/python3.5/site-packages/django/core/serializers/base.py", line 205, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 904, in _save_table forced_update) File "/usr/local/lib/python3.5/site-packages/django/db/models/base.py", line 954, in _do_update return filtered._update(values) > 0 File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py", line 664, in _update … -
OSError at /user/1/edit [Errno 13] Permission denied: '/home/django/django_project/media/profile_pics/Square.jpg'
My Django site is live, as far as I know, everything works correctly except for when a user tries to upload a profile image they get this error: OSError at /user/1/edit [Errno 13] Permission denied: '/home/django/django_project/media/profile_pics/Square.jpg' I have never seen this before so I'm not really sure what to do... Here is the traceback: Traceback Switch to copy-and-paste view /usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _legacy_get_response response = self._get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/contrib/auth/mixins.py in dispatch return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in dispatch return handler(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py in post return super(BaseUpdateView, self).post(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py in post return self.form_valid(form) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/edit.py in form_valid self.object = form.save() ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/forms/models.py in save self.instance.save() ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/db/models/base.py in save force_update=force_update, update_fields=update_fields) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/db/models/base.py in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/db/models/base.py … -
Django settings module...not possible to run the logger?
I use the python logging module in my my_app/views.py file with no problem. I tried to use it inside the staging_settings.py that I use for my configuration. But the messages never reach the error log, whilst the messages from the views.py work fine. my staging_settings.py: LOGGING= { ..redacted for space.. } # the logging config-dict import logging logger = logging.getLogger(__name__) logger.debug(F"this is staging_ setup") Is it just an impossibility to run a logger inside a setup.py? I guess the server actually isn't running yet, so there is nothing for the logger to send to? I'm running this on pythonanywhere, so I don't really have a console to simply print() to or some other hack alternative. -
How can I ran Gunicorn with NGINX (I wan to move from Django development to test my production)?
This is for learning purpose. I have done the web application with Django + Celery/RabbitMQ. I tried to follow this tutorial. I got everything set until "That’s all for gunicorn.". In sense, my Gunicors runs like what it is describe in the tutorial. Now I am confused with the NGINX settings. I have these configurations in /etc/nginx/nginx.conf in its http block. upstream awesome_app { server unix:/home/notalentgeek/Downloads/awesome_app/run/gunicorn.sock fail_timeout=10s; } server { listen 8080; client_max_body_size 4G; access_log /home/notalentgeek/Downloads/awesome_app/logs/nginx-access.log; error_log /home/notalentgeek/Downloads/awesome_app/logs/nginx-error.log warn; location /static/ { autoindex on; alias /home/notalentgeek/Downloads/awesome_app/static/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://awesome_app; break; } } } Everything else there stay untouched. And then what should I do after this? The tutorial does not way anything. How can I see my web application? Moreover how can I set NGINX for Docker ready? Thanks! -
Chaining Django models: how to format results on the template according to the specific model
I have a view that allows me to work with two different models at once, thanks to itertools chain. I'm rendering the instances of the two chained models inside a table in my template, and I'd need the rows of the table to be formatted differently in case the instances are from one model as opposed to the other. So basically: I'm chaining two models and displaying their instances in a table, and all the rows of the table that contain instances from model A should be formatted with a yellow background and all the rows containing instances from model B should have a blue background instead. This is the view: class BaseView(generic.ListView): template_name = 'base/base_list.html' context_object_name = 'base_list' def get_queryset(self): queryset = Document.objects.order_by('due_date') return queryset def get_context_data(self, **kwargs): context = super(BaseView, self).get_context_data(**kwargs) context['object_list'] = sorted( itertools.chain(Program.objects.all(), Document.objects.all()), key=attrgetter('validity_date'), reverse=True) return context In logic, what I'd need in the template would be something like this: if object in object_list ***belongs*** to Program.objects.all() (etc) else (etc) The question is: how should I express that belongs? I've also looked into template tags but could not find the right way to go. Thank you in advance. -
django 2 fields form not working
2 of my fields from my form not working when i try to search with them. I have about 10 fields total and they all work but those 2 don't this is part of my forms.py with the fields that are not working. class AllTablesForm(forms.Form): title = forms.CharField(label='', max_length=250, required=False, widget=forms.TextInput(attrs={'placeholder': 'Title'})) ....... redirectstatus = forms.IntegerField(label='', required=False, widget=forms.TextInput(attrs={'placeholder': 'Redirect Status'})) created_at = forms.DateTimeField(label='', required=False, input_formats=["%Y-%m-%d"], widget=forms.TextInput(attrs={'placeholder': 'Created At'})) redirectstatus and created_at are not working. The format of my dates are like this. 2017-09-27 13:03:49 and the format for the redirect is simple. 200 300 etc. I want to make the created_at like something like the phpmyadmin date search. this is my views.py def search_form_table(request, pk): table_name = Crawledtables.objects.get(id=pk) t = create_model(table_name.name) if request.method == 'GET': form = AllTablesForm(request.GET) if form.is_valid(): cd = form.cleaned_data title = cd['title'] url = cd['url'] description = cd['description'] canonical = cd['canonical'] robots = cd['robots'] schematype = cd['schematype'] redirectstatus = cd['redirectstatus'] created_at = cd['created_at'] query = t.objects.filter(title__icontains=title, url__icontains=url, description__icontains=description, canonical__icontains=canonical, robots__icontains=robots, schematype__icontains=schematype, redirectstatus__exact=redirectstatus, created_at__range=created_at) return render(request, 'search/search_table.html', {'tbl_name': table_name, 'form': form, 'details': query, 'detail': True}) else: form = AllTablesForm() return render(request, 'search/search_table.html', {'form': form}) Thank you in advance