Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
setup a cron job in django in windows
I want to setup cronjob in Django project. I am using windows. I try django-cron but it is not working with windows. how can I use cron job scheduling in my project. thanks -
python, django, wsgi application not working
question we want to run taiga.io using the WSGI but after 1 hour of trying we need help from someone else. we don't qute understand the trace but we think that we run the correct wsgi binary now: gunicorn taiga.wsgi but the webservice still won't start and return a useless trace. we've googled it and are trying various hacks but none seems to be useful. we tried to set DJANGO_SETTINGS_MODULE but unsure if that is required we don't even know if django is calling the correct wsgi binary so why can't the worker boot? is there a more in detail debug for workers somewhere? versions taiga-back-3.3.13 python3.6-Django-1.11.13 python3.6.5 gunicorn-19.7.1 nixos-version 18.03.d6c6c7f-nixcloud_598d0c5 (Impala) quest: run taiga via wsgi i'm integrating https://github.com/betaboon/nixpkgs/blob/445563d6575d7e8cb21768570b837ea3d816dee8/nixos/modules/services/web-apps/taiga.nix into nixcloud-webservices at the moment and while this is working perfectly: ${taiga-back}/bin/manage.py runserver --nostatic "127.0.0.1:8000" we have problems with wsgi: systemd.services.taiga-back = rec { description = "${config.uniqueName} main service (taigaio)"; wantedBy = [ "multi-user.target" ]; after = [ "network.target" ]; environment = let python = pkgs.python3; penv = python.buildEnv.override { extraLibs = [ taiga-back pkgs.python3Packages.gunicorn pkgs.python3Packages.gevent pkgs.python3Packages.celery pkgs.python3Packages.django ]; }; in { PYTHONPATH = "${taigaBackConfigPkg}:${penv}/${python.sitePackages}/:${taiga-back}/lib/python3.6/site-packages"; DJANGO_SETTINGS_MODULE = "settings"; }; serviceConfig = { User = "taigaio-t1"; # FIXME hardcoded Group = … -
how to integrate whatsapp buisness api in project?
I want to integrate whatsapp business web api in django project so I can contact our clients through whatsapp. I need step by step guide to integrate whatsapp web api. for reference: -
Offline Desktop Web Application with Python and Angular (or Django or something else)
Hey all and thanks for reading my question, I would kindly ask for some help with a task as I really do not know how to start. My background: I am just starting to learn backend development with only 1 django backend created and deployed. I have solid experience with game development, architectures, algorithms, and various technologies and languages. The Setup: I have a python script (call it the solver), which runs a complex calculation of some data. I cannot modify the calculation scripts. I can modify the way they are called. Currently it works by typing solver.py "params" in a terminal which returns the calculation results in a file. I have modified this to work by calling a method execute() which returns the solution as string (or a json/yaml object). The Task: I need to create a very simple desktop offline application to call the solver and output the solution. The OS is unknown at this stage (possibly Windows). There should be no requests to a remote server whatsoever (otherwise would be a simple task) and the application should be run from a single file (e.g. solver.exe). Thoughts and Questions: My first thought was to create a simple django/flask … -
Same code fails in the Django view but works in the command-line
What can make a Django view fail, while the same code works well when it's called from the command-line? Below is the simple view I'm calling: from snappy import ProductIO def test(request): path_sar = '<path>/file.dim' sar_pre_product = ProductIO.readProduct(path_sar) Snappy is the python client to the java API of ESA SNAP. This issue seems to be specific to Python web frameworks, since the same code failed also with Flask for the same reason, returning a RuntimeError at ... java.lang.NullPointerException. Now, the code below works correctly from the command-line, and it works also when that same script is called with subprocess.call (which is not really a nice workaround). Any idea if Django is just failing to automatically add to its path certain java libraries already in the classpath when the script is run in the command-line? -
render() missing 1 required positional argument: 'template_name'
this is m views.py code I getting the error as above while running the url form the pycharm -
Django 2.0 - Make test worker to run tests in non-app folder
In Django 2.0, I have following project structure, which I can't change, no matter what: grocery_store_website manage.py grocery_store # contains wsgi, settings,etc. app1 app1 non-app-utils helpers.py serializers.py model_mixins.py tests test_helpers.py # I want test runner to run these. It turned out, I need to write unit tests for non-app-utils. Mentioned directory is not a registered Django App and never will be. These tests must be located in tests directory, located in non-app-utils. How can I make Django's test runner to discoer and run also tests from non-app-utils directory? -
Django: Inject form validation on ModelForm, not Model
Question: Is there a way to inject form field validation on the ModelForm instead of the Model? Justification: I have three ModelForm's that update the same Model instance, which have default conditions for blank. I should have designed three different Models for each form, but I'm to far in to make a change. Please assist! Thanks, Neel -
Django Models entering data
Im quite lost in this models, i want to Enter data in CourseScore. Course score will point to one student, and one course which the student registered. I want to do automatic calculation at the time of data entry. from django.db import models from student.models import Student # Create your models here. class Course(models.Model): name = models.CharField(max_length=200) finternalmark=models.IntegerField(default=40) fexternalmark = models.IntegerField(default=100) fullmark = models.IntegerField() def CalculateFullMark(self): self.fullmark = self.finternalmark + self.fexternalmark def __str__(self): return f'{self.name}-{self.fintegermark}-{self.fexternalmark}' class CourseRegistration(models.Model): student = models.OneToOneField(Student, on_delete=models.CASCADE) courses = models.ManyToManyField(Course) def __str__(self): return f'{self.student}' class CourseScore(models.Model): #entering marks for one course CourseRegn = models.OneToOneField(CourseRegistration, on_delete=models.CASCADE) internalmark = models.IntegerField() externalmark = models.IntegerField() marks = models.IntegerField() def CalculateMarks(self): self.marks = self.internalmark + self.externalmark class SemesterResult(models.Model): student = models.OneToOneField(Student, on_delete=models.CASCADE) courses= models.ForeignKey(CourseScore,on_delete=models.CASCADE) # course in which the student is registered and marks are entered totalmarks=models.IntegerField() grandtotal = models.IntegerField() def CalculateTotalMarks(self): pass #calculate totalmarks = sum of marks scored in courses that the students opted def CalculateGrandTotal(self): pass #calculate grandtotal = sum of all fullmarks of the course that the student opted -
using angular js template inside django {% static %} tag
Hi I am trying to load the image on the basis of name from database. I am fetching the database value from angular ajax request. Now the problem is how to use the angular template in static tag of django. <div ng-repeat="result in dbresults"> <img src= {% static '/images/'{[{result.db}]}'.png' %}> </div -
Django Import Error: cannot import name "Shift"
I'm pretty sure it's due to a circular import but I'm not too sure how to solve my issue in mysite/shifts/models.py from django.db import models class Shift(models.Model): # defines a shift in mysite/shifts/scrapes.py from shifts.models import Shift I can more code if you need but I believe the issue is here, I've added my apps to settings.py I get this error when trying to run scrapes.py as a django-admin command from shifts.models import Shift ImportError: No module named 'shifts' -
Gmail Login API with username and password in python
I have username and password of gmail account, I need API to automatically login to gmail from my python code. I have tried using smtplib -
How can i auto-fill a form field based on the title of an attached document?
This is my form: models.py: class Document(models.Model): Document_name = models.CharField(max_length=255, default='Document_Name') Date = models.DateField() Client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE) File = models.FileField() Filename = models.CharField(max_length=255) def __str__(self): return self.Document_name upload.html: <form method="post" enctype="multipart/form-data" style="margin-left: 16px"> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit" class="btn btn-default">Submit</button> </form> forms.py: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' What I want to happen is when I choose a document to attached e.g. test1.pptx, I want the Filename field to auto populate with that name (test1.pptx) -
Delete a post in Django
I new to django and I am trying to make a web application. I have this page page image and I want to delete one post when I press the delete button. How can I do that? This is my modal for 'Post' : class Post(models.Model): created_date = models.DateTimeField() title = models.CharField(max_length=100) profile_image = models.ImageField(upload_to='poze', blank=True, null=True) text = models.CharField(max_length=1000, default='Nimic', blank=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) I've been looking for delete methods, but I've always found form-only methods and I don't use form. Thank you. -
Ngnix CORS Response to preflight request
I have a jquery plugin that is making api requests for a server i cannot control. When i make such request, i see: Failed to load APISERVER.COM/?QUERY=VAR: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://EXAMPLE.COM' is therefore not allowed access. My ngnix config: upstream api_server { server api.com; } server { listen 80; server_name example.com; add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow_Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH'; return 301 https://$server_name$request_uri; } server { listen 443 default ssl; add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow_Credentials' 'true'; add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH'; location /api_server { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_pass http://api_server; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_redirect off; } } For that plugin I have set "api_url" to my example.com/api_server/ -
Calling instance method of class using celery in Python
In older version of Celery there was facility of converting instance method to celery task like example below according to http://docs.celeryproject.org/en/3.1/reference/celery.contrib.methods.html from celery.contrib.methods import task class X(object): @task() def add(self, x, y): return x + y I am using Celery 4.1 which does not have such feature by default. How can I achieve this facility by my own in some simple way? Let me represent my requirement by example. from abc import ABC, abstractmethod AbstractService(ABC): def __init__(self, client_id, x, y): self.client_id = client_id self.x = x self.y = y @abstractmethod def preProcess(self): '''Some common pre processing will execute here''' @abstractmethod def process(self): '''Some common processing will execute here''' @abstractmethod def postProcess(self): '''Some common post processing will execute here''' Client1Service(AbstractService): def __init__(self, x, y): super(__class__, self).__init__('client1_id', x, y) # I want to run this using celery def preProcess(self): super().preProcess() # I want to run this using celery def process(self): data = super().process() # apply client1 rules to data self.apply_rules(data) print('task done') # I want to run this using celery def postProcess(self): super().postProcess() def appy_rules(self, data): '''Client 1 rules to apply''' # some logic I want to run preProcess, process and postProcess of Client1Service class using celery inside django project. If I … -
Django CreateView Not Working as expected
I have the following CreateView class CreateEmailTemplateView(CreateView): template_name = 'frontend/emailtemplates/create.html' model = Templates fields = '__all__' def form_valid(self, form): form.instance.user = self.request.user return super(CreateEmailTemplateView, self).form_valid(form) And the Templates model looks like this class Templates(models.Model): name = models.CharField(max_length=128) template = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) But when I submit the form it doesn't persist it in the database nor I see any error messages, it simply redirects to the same page, The form method is POST What am I missing? How can I show some error/success message after the form submission ? -
Deploy more than one django application in bitnami
I have deploy two django application on bitnami apache server, but it running alternate. ex. If i hit service for app1 then its run but again i hit the same service it generate 404. same happened with app2. How to solve it. -
Djago - Create all foreign key objects upon creating a parent object.
Consider the following code, in which I have one parent, and all the child models related to the parent by ForeignKey relationship. Each child may have their own child, making the whole family look like a tree structure. class Parent(models.Model): field = models.CharField(max_length=100, primary_key=True) class Child_1(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, related_name='aa') class Child_2(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, related_name='aa') class Child_1_Child_1(models.Model): parent = models.ForeignKey(Child_1, models.CASCADE, related_name='aa') class Child_1_Child_2(models.Model): parent = models.ForeignKey(Child_1, models.CASCADE, related_name='aa') Upon making an object for Parent, I want to create all the child objects. I guess I can create all the child objects like this: parent = Parent.objects.create(**kwargs) child_1 = Child_1.objects.create(parent=parent) child_2 = Child_2.objects.create(parent=parent) child_1_child_1 = Child_1_Child_1.objects.create(parent=child_1) child_1_child_2 = Child_1_Child_2.objects.create(parent=child_1) ... But you know, this doesn't look very good. Is there any built-in Django method that handles this kind of parent-child object creation in chain? -
How to configure webpack for multi-tenant application?
I like to build front-end part for a multi-tenant web application built on django, using React. Am using webpack to generate bundles. So for that how to configure webpack?? please help me. Doubts: 1> If 1 entry point for each tenant, then for every new tenant, is application needs to deploy once again??? 2> For each tenant, a parent component is rendered using react router and child components will be included asynch. so how to build a new component for every new tenant?? 3> How to manage styling for each component across tenants?? 4> How to read css styling from a file for configurable?? Help me, and also am not getting any resources for build a react components for tenant based application. -
Truncate functions return null on Datetime
I am trying to get values from MySQL database and to use GroupBy on basis of month/date/year. My database has dates in the format of unixtimestamps(int(10)) and I am trying to use GroupBy on dates. When I created the model by using default way of creating a model from database tables, Generated type of my columns was charfield(). I have created a custom field for time_start and time_end. Model Class: class LinuxJobTable(models.Model): time_start = UnixTimestampField() time_end = UnixTimestampField() id_group = models.IntegerField() mem_req = models.IntegerField() UnixTimestampTable custom field code: class UnixTimestampField(models.DateField): def __init__(self, null=False, blank=False, **kwargs): super(UnixTimestampField, self).__init__(**kwargs) def db_type(self, connection): return datetime; # Hopefully used to convert database values to Python format def from_db_value(self, value, connection, test,prepared=False): import pytz from pytz import timezone if value is None: return value localtz = timezone('US/Eastern') print "in from_DB_VALUE:",value conv_date = datetime.fromtimestamp(int(value)) print conv_date return conv_date def get_prep_value(self, value): return int(value.strftime('%s')) ViewClass Code: class jobUsageApiView(generics.ListAPIView): todays_date = datetime.today().replace(hour=0, minute=0, second=0) min_pub_date_time = datetime.combine(todays_date, time.min) max_pub_date_time = datetime.combine(todays_date, time.max) queryset = LinuxJobTable.objects.filter(time_start__range=(min_pub_date_time, max_pub_date_time)).annotate(Count('id_job')); #queryset = LinuxJobTable.objects.filter(time_start__range=(min_pub_date_time, max_pub_date_time)).values('time_start').annotate(Count('id_job')); serializer_class = JobUsageSerializer; If I don't use truncate functions with it. It returns correct results as: But when I am trying to group them by date. Truncate functions … -
Django update a field using query of the other table
I have four models like below: class Item(models.Model): name = models.CharField(max_length=20) class BranchItem(models.Model): branch = models.PositiveIntegerField() item = models.ForeignKey(Item, blank=False, null=False) class TaxItem(models.Model): tax_type = models.CharField(max_length=2, blank=True, default='PE') amount = models.FloatField(default=9, blank=True) class SellItem(models.Model): amount = models.FloatField(blank=True, default=0.0) branch_item = models.ForeignKey(BranchItem, blank=Flase, null=False) tax = model.ForeignKey(TaxItem, blank=False, null=False) Now I want to update all SellItemwith appropriate tax which must get from TaxItem table, the SellItem table is huge and I do not want to update each row saparetly in python and it must do completely in database side. The main problem I encountered is what I said above but as a solution I choose update method using a Subquery as is shown in below code: tax_query = TaxItem.objects.filter(item_id=OuterRef('item')).values_list('id') try: SellItem.objects.annotate(item=F('branch_item__item')).update(tax_id=Subquery(tax_query[:1])) finally: connection.queries It generates an insane query like below: UPDATE "api_sellitem" SET "tax_id" = ( SELECT U0."id" FROM "api_taxitem" U0 WHERE U0."item_id" = ("api_branchitem"."item_id") LIMIT 1) WHERE "api_sellitem"."id" IN ( SELECT V0."id" AS Col1 FROM "api_sellitem" V0 INNER JOIN "api_branchitem" V1 ON (V0."branch_item_id" = V1."id")) Which is obviously wrong and I could not figure how could I correct this? I am using django 1.11.3 and postgresql as database, Please give me a suggestion for solving the main problem i.e. updating … -
How to customize a field of model in serializer
I have a model with a field in DateTime type. I want to display this field like 2018-05-04 12:05. How can I do this? my model: class MyModel(models.Model): name = models.CharField(max_length = 100) .... created_at = models.DateTimeField() class MySerializer(serializers.ModelSerialer): class Meta: model = MyModel fields = ('name', 'created_at') but it display created_at like : 1990-12-31T23:59:60Z -
Django with Postgresql error message: django.db.utils.ProgrammingError: operator does not exist: bigint = boolean
I am trying to solve this error I am having in Django. Anyone have an idea what I am doing wrong ? thank yo! The error message: django.db.utils.ProgrammingError: operator does not exist: bigint = boolean LINE 1: ... 'economy' AND "landingpage_profile"."hasArticle" = true) OR... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts The model: class Profile(models.Model): ... hasArticle = models.BooleanField() ... My queryset: if hasArticle =="ALL": queryset_list = queryset_list elif hasArticle =="ALREADY CONTRIBUTED": queryset_list = queryset_list.filter(hasArticle=1) elif hasArticle =="NEVER CONTRIBUTED": queryset_list = queryset_list.filter(hasArticle=0) I have tried this as well: elif hasArticle =="ALREADY CONTRIBUTED": queryset_list = queryset_list.filter(hasArticle=True) elif hasArticle =="NEVER CONTRIBUTED": queryset_list = queryset_list.filter(hasArticle=False) -
How to understand FieldFile in Django?
I'm viewing the Django document and now up to FieldFile. I understand it's doing something like I/O stuff. But I have no idea when & where to use it and how to access it. We already have FielField, I guess this field opens and closes files automatically for us. I can't figure out the relationship between FieldFile and FileField.