Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
if request.method == 'POST': is true when the form is blank but false when there's data in the form
When the form is blank, the first if command works and the html is redirected to the "fail" webpage, however when numbers are inputted into the form, i.e the if statement should be true, the first if command is false and a blank form is returned (from the last else). def formview(request): if request.method == 'POST': form = MyCalculator(request.POST) if form.is_valid(): parents = form.cleaned_data['parents'] jobs = form.cleaned_data['jobs'] grants_bursaries_scholarships = form.cleaned_data['grants_bursaries_scholarships'] student_loan = form.cleaned_data['student_loan'] other_income = form.cleaned_data['other_income'] rent = form.cleaned_data['rent'] travel = form.cleaned_data['travel'] bills = form.cleaned_data['bills'] other_outcome = form.cleaned_data['other_outcome'] if ( Calculator.objects.filter(parents=parents).exists() and \ Calculator.objects.filter(jobs=jobs).exists() and \ Calculator.objects.filter(grants_bursaries_scholarships=grants_bursaries_scholarships).exists() and \ Calculator.objects.filter(student_loan=student_loan).exists() and \ Calculator.objects.filter(other_income=other_income).exists() and \ Calculator.objects.filter(rent=rent).exists() and \ Calculator.objects.filter(travel=travel).exists() and \ Calculator.objects.filter(bills=bills).exists() and \ Calculator.objects.filter(other_outcome=other_outcome).exists()): myparents = Calculator.objects.get(parents=parents).get_parents() myjobs = Calculator.objects.get(jobs=jobs).get_jobs() mygrants_bursaries_scholarship = Calculator.objects.get(grants_bursaries_scholarships=grants_bursaries_scholarships).get_grants() mystudent_loan = Calculator.objects.get(student_loan=student_loan).get_studentloan() myother_income = Calculator.objects.get(other_income=other_income).get_otherincome() myrent = Calculator.objects.get(rent=rent).get_rent() mytravel = Calculator.objects.get(travel=travel).get_travel() mybills = Calculator.objects.get(bills=bills).get_bills() myother_outcome = Calculator.objects.get(other_outcome=other_outcome).get_otheroutcome() mytotal_income = total_income(myparents, myjobs, mygrants_bursaries_scholarship, mystudent_loan, myother_income) myfixed_outcome = fixed_outcome(myrent, mytravel, mybills, myother_outcome) myvariable_outcome = variable_outcomes(mytotal_income, myfixed_outcome) myfood = food(myvariable_outcome) mysocialising = socialising(myvariable_outcome) return render(request, 'Noteable_Budgeting/out.html', {'food1' :myfood}, {'mysocialising1' :mysocialising}) else: return HttpResponseRedirect('/calculator/fail') else: form = MyCalculator() return render(request, 'Noteable_Budgeting/calculator_list.html', {'form':form}) -
How do I check if the user is authenticated with the database using PyMongo?
I'm using PyMongo for a project, what I have found is that all I need is the server name to create, update or delete any entry/collection or even a database. I mean, it doesn't care if I'm authenticated with a username and password with read/write roles. Here's an example: from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client.wow db.wowagain.insert_one('field':'value') My question is: Is it safe to use Mongodb with python applications, specially with web applications? I have also tried mongoengine for Django and still I found the same. -
django log in user in manage.py commands
I have commands in my_app/management/commands/ which need a user that is logged in, more precisely a root user. I need this root for logging (datbase, not python logging) purposes. All I found is that a request object is needed from the session to log in a user, like for example in the django documentation. Question: Is there a way to log in a user when calling a command with manage.py without the frontend? -
django modelform doesn't render BooleanFiled
I have this model: class Event(models.Model): title = models.CharField("Event Title",max_length=250) private = models.BooleanField("Private event",default=False) category = models.ForeignKey(Category) created = models.DateTimeField(default=timezone.now') This modelform: class EventForm(forms.ModelForm): private = forms.BooleanField(label='Private event',required=False) class Meta: model = Event exclude = ('created',) In my template the boolean field is not rendered. Even when I try to display the form with {{ form.as_p }}. I have droped and created the database several times. I have checked permissions. I have checked migrations. What am I missing? -
Django way to process url .../api/example/merge/{urlparams}/ and process a filtered query in DB
So I'm a newb to python and django, I have GET with the following url .../api/example/merge/{urlparams}/ in where urlParameters can be like variable in length and number of parameters for example ?derivate=22&engine=52?start_date=2017-03-05?end_date=2017-05-05 I have read documentation and I have achieve this tiny bit: @list_route(permission_classes=[permissions.AllowAny], url_path='example/(?P<urlparams>[^/]+)$') def example(self, request, *args, **kwargs): # do something... return Response(something) Is this the django way to achieve this, or should I try to do it in some other way? -
rendering foreign field in django form
I have a model where a field references a foreign key from another model as: class DummyModel(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=150) image_type = models.ForeignKey(ImageTypeModel) # Foreign key class Meta: db_table = "dummy" The parent model is also simple: class ImageTypeModel(models.Model): name = models.CharField(max_length=100) dims = models.IntegerField() class Meta: db_table = "imagetypes" Now, I attempt to render a record in a form and for that purpose I am using django-crispy-forms. So, I have: class DummyForm(ModelForm): class Meta: model = DummyModel fields = ['name', 'description', 'image_type'] def __init__(self, *args, **kwargs): super(DummyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-2' self.helper.field_class = 'col-sm-10' #self.helper.form_tag = False self.helper.layout = Layout( Field('name'), Field('description'), Field('image_type')) The image_type field renders as a drop-down list which is perfect but instead of the name of the image types, the entries are all labelled ImageTypeModel. Is there a mechanism so that I can display the corresponding name from the ImageTypeModel record but when the form is saved it saves the primary key rather than the name. -
Accessing models linked to a Django user
Using python 2.7 and Django 1.10 I have a model called "hostname" that links to a Django User. I can assign a model object to a user, and the object gets created correctly; via the django admin GUI, i can confirm that object "Hostname" has been created and assigned correctly to the choosen user. My question is, via "Python manage.py shell", how can i list all "Hostname" objects that are linked to a specific user, lets call the user "user1". So far, I've got this: >>> from app.models import * >>> from django.contrib.auth.models import User >>> userVar = User.objects.get(pk=2) >>> userVar <User: user1> >>> userVar.hostname() The above fails with: User object has no attribute "hostname" I've tried varying edits of the above command, all failing with the same error. in models.py: class Hostname(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) def __str__(self): return self.name I've tried my best to google this, but im new to Django, and still working on the terminology, so if anyone can correct my terminology used here it would be most appreciated. -
django-eav attributes as form fields
I am trying to implement EAV model in Django. I decided to use django-eav (active development compared to eav-django) for my application where the user can define dynamic fields see this stack overflow link for django dynamic fields. My question is how to render the model (entity) attributes as form fields in the template from EAV prespective? Below is the toy example import eav from app.models import Patient eav.register(Patient) Attribute.objects.create(name='age', datatype=Attribute.TYPE_INT) Attribute.objects.create(name='height', datatype=Attribute.TYPE_FLOAT) # Patient Bob has been already created, below is the Patient object instance pat = Patient.object.get(name='Bob') pat.eav.age = 32 pat.eav.height = 165.2 How to get the age and height attributes as a form-field in django? Any insight in the right direction is highly appreciated. I have gone through django-eav documentation but, they are not well documented. Thank you. -
angular2/Django rest application browser asks for login after application login
I am building an app with angular2 on frontend and Django rest on backend. Even after I login to my application, browser asks for login once again like following: This happens each day, but not on consecutive logins in the same day. Why does this happen? My Django rest configuration code: MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } and angular2 service: login(username: string, password: string) { let body = JSON.stringify({ 'username' : username, 'password': password }); let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); return this.http.post(this._authenticationUrl + 'login/', body, options) .map(this.extractData) .catch(this.handleError) } Why does this happen? -
Django Queryset - returning only filtered related objects
I have model presented below: class ClassA(models.Model): name = models.CharField(max_length=250) connections = models.ManyToManyField(ClassB) class ClassB(models.Model): ... date=models.DateTimeField() .... Can I create queryset, which returns me objects from ClassA, containing only objects from ClassB with specified date? I tried the following code: objects_list = ClassA.objects.filter(connections__date__gte='2016-01-01') But in the objects_list, there are objects which have connections__date less than specified date. -
How do minus in django template [duplicate]
This question already has an answer here: Variable subtraction in django templates 3 answers Whanna do minus in template try: {{ order.total_price|add:"-"order.shop.delivery_price }} Could not parse the remainder: ' order.shop.delivery_price' from 'order.total_price|add:"-" order.shop.delivery_price' how i can do minus? ... -
Storing large amount of json data into binary file in live
I am building a web application and a web socket server that is meant for live monitoring of servers, using django and python. The web socket server (in python) performs some REST request periodically to the servers to be monitored and fetches some metrics, so as to serve up the web application for plotting. The metrics are to be stored in message pack binary format file. To achieve that, i use a json object to hold up the fetched metrics and this object is periodically updated (every second) to get latest metrics value; And every 24hrs, this object will be written into a new message pack binary file for achiving purposes. Knowing that i will be dealing with huge amount of data (in GB), i suspect holding up all these data in a json object in memory might cause to some memory issue, am i right ? The problem here is due to the fact that the object has to be updated periodically, so i can't just read/write from/to the file each time it need to be updated (every seconds). What could be a more efficient approach ? -
Best back end file upload parallelism technique
In my web application (Django), I am sending multiple files to the backend. I need to implement a parallel file upload technique which will make use of maximum CPU core capacity. I am ready to implement it it any language or any tool. Please someone suggest best tools or techniques to implement this, so that file saving to backend server (to hard disk or database) should be completed in much less time compared to normal file upload. -
geonode 2.4: overwrite subtemplate in new project
Geonode 2.4 themes can be customized by creating a new project and copy site_base.html to my project dir /var/www/myproject/myproject/templates. How would I overwrite this subtemplate resourcebase_info_panel.html https://github.com/GeoNode/geonode/blob/2.4.x/geonode/base/templates/base/resourcebase_info_panel.html IΒ΄ve tried to copy it to /var/www/myproject/myproject/templates /var/www/myproject/myproject/templates/base/templates without effect. -
Filter related models
Please refer to my models (3 models: Variant, Deal and Campaign) below. I want to get a list of Variants and their related deals whose campaigns start date is today. I have been able to filter the campaigns start date but, the list of deals being returned are not being filtered. class Variant(BaseModel): """ Product model """ variant_id = models.AutoField(primary_key=True) unit = models.ForeignKey(Unit, on_delete=models.CASCADE) value = models.DecimalField(max_digits=3, decimal_places=2, default=Decimal('0.0')) product = models.ForeignKey(Product, on_delete=models.CASCADE) class Deal(BaseModel): """ Deal model """ deal_id = models.AutoField(primary_key=True) price = models.DecimalField(max_digits=4, decimal_places=2) variant = models.ForeignKey(Variant, on_delete=models.CASCADE) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) class Campaign(BaseModel): """ Campaign model """ campaign_id = models.AutoField(primary_key=True) start_date = models.DateField(default=now()) end_date = models.DateField(default=now()) store = models.ForeignKey(Store, on_delete=models.CASCADE) -
I can't get celery working properly (aws elasticbeanstalk)
I'm moving a django app to python3/django 1.10. Part of the process include also a new deployment and we use AWS EBS. The celery tasks were ok before the migration, but now I can't get the tasks works properly. The packages: ... celery==3.1.23 Django==1.10.6 django-celery==3.2.1 ... Python: Python 3.4.3 On the supervisor configuration I added a configuration to run celery: [program:celeryd-workers] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/python /opt/python/current/app/manage.py celery worker -A app --app=app.celery_app:app -l DEBUG -c 4 directory=/opt/python/current/app user=nobody numprocs=1 autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true stdout_logfile=/var/log/celery-worker.log stderr_logfile=/var/log/celery-worker.log environment=PYTHONPATH="/opt/python/current/app/:",PATH="/opt/python/run/venv/bin/:%(ENV_PATH)s",DJANGO_SETTINGS_MODULE="settings.qa" [program:celeryd-beat] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/python /opt/python/current/app/manage.py celery beat -A app --app=app.celery_app:app --loglevel=DEBUG --workdir=/tmp --pidfile=/tmp/celerybeat.pid -s /tmp/celerybeat-schedule.db directory=/opt/python/current/app user=nobody numprocs=1 autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true stdout_logfile=/var/log/celery-beat.log stderr_logfile=/var/log/celery-beat.log environment=PYTHONPATH="/opt/python/current/app/:",PATH="/opt/python/run/venv/bin/:%(ENV_PATH)s",DJANGO_SETTINGS_MODULE="settings.qa" my celery_app.py is pretty simple: from __future__ import unicode_literals, absolute_import from celery import Celery from django.conf import settings app = Celery() app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) The configuration On the EC2 instance the settings for celery: BROKER_URL = 'the aws elastic cache redis url' CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' BROKER_TRANSPORT_OPTIONS = { 'visibility_timeout': 600, } BROKER_POOL_LIMIT = 1 CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack'] CELERY_DEFAULT_QUEUE = 'default' CELERY_QUEUES = { 'default': { 'exchange': 'default', β¦ -
Django Development server doesn't detect changes in my html files
I am using django 1.7.5 for my project .I am using vagrant and virtual box for my project.I successfully ran the server and detected changes on my browser.But,the problem is After making any changes in the html file,I had to restart the server to see changes on the browser. Does django 1.7.5 detect changes on the go?(like make change the file,refresh the browser,see changes.) or this is not related to django version? -
Django-crontab - automatic add on start, automatic remove on stop
I use django-crontab. It works, if I use the command python manage.py crontab add after server start and the command python manage.py crontab remove I would like to use this management commands automatically on start/stop of the server. Where I should call it? Where should be the commands placed? Is it ok to put start command in the end of settings.py? Where should be the stop command? Thanks you in advance. -
Django OneToOneField with possible null value
I have a relation, first model is associated to 1 or 0 of the the other model, I tried: #OneToOneField with null = True class ModelA(models.Model): fieldA = models.PositiveIntegerField() class ModelB(models.Model): fieldB = models.CharField(max_length=100) modelA = models.OneToOneField(ModelA, null = True, blank = True) then I got an Error: Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. And I tried: #ForeinKey with unique = True and null = True class ModelA(models.Model): fieldA = models.PositiveIntegerField() class ModelB(models.Model): fieldB = models.CharField(max_length=100) modelA = models.ForeignKey(ModelA, unique=True, null = True, blank = True) Then I got a warning: Setting unique=True on a ForeignKey has the same effect as using a OneToOneField. HINT: ForeignKey(unique=True) is usually better served by a OneToOneField. It would be better if I use a proper solution without any warning or deprecation (I am using Django 1.8.17). -
Angular 2: Downloading a ZIP as blob fails
I guess my back-end works, because this works and the zip is fine: curl -X POST -H 'Content-Type: application/json' -d '{}' http://localhost:3000/zip/create > file.zip My Django back-end returns the data like this: return HttpResponse(data, content_type='application/octet-stream') I cannot figure out what's wrong in my Angular 2 code, because the ZIP it gets ends up being somehow corrupted and I cannot open it. The actual data seems to be in response._body: let blob = new Blob([response._body], { "type": 'application/octet-stream;' }); this.exportUrl = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(blob)); this.exportFileName = "download.zip"; After clicking that URL it downloads the zip but it doesn't work. So apparently I handle the binary data somehow incorrectly? My service is essentially this: return this.http.post( this.zipUrl, JSON.stringify(zipCreationParameters), {headers: {'Content-Type': 'application/json'} }); -
ionic 2 upload image to django rest
I am trying to upload an image from Ionic 2 app to Django-powered website through Django Rest API. The API is working and tested through Postman but I always get HTTP 400 BAD Request error in Ionic. Here is my code in Ionic: openCamera(){ var options = { sourceType: Camera.PictureSourceType.CAMERA, destinationType: Camera.DestinationType.DATA_URL }; Camera.getPicture(options).then((imageData) => { this.imageName = imageData; this.imageURL = 'data:image/jpeg;base64,' + imageData; }, (err) => { this.showAlert(err); }); } Upload file (I am serving my Django project on my local PC with IP address 192.168.22.4): transferData(auth){ let headers = new Headers(); headers.append('Authorization', auth); let formData = new FormData(); formData.append('image', this.imageURL, this.imageName); this.http.post("http://192.168.22.4/api-imageUpload", formData, {headers: headers}).subscribe(res => { let status = res['status']; if(status == 200){ this.showAlert( "The image was successfully uploaded!"); }else{ this.showAlert("upload error"); } }, (err) => { var message = "Error in uploading file " + err this.showAlert(message); }); } On Django, here is my serializer: class ImageDetailsSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) class Meta: model = ImageDetails fields= ('image','status','category', 'user') ####status, category has default value and views.py: class ImageDetailsViewSet(generics.ListCreateAPIView): queryset = ImageDetails.objects.all() serializer_class = ImageDetailsSerializer I am not sure if my code in uploading file is correct. I am trying to pass the data through Form data β¦ -
Python Anywhere Django App Import Error
I'm getting the following import error when trying to run a django app on Python Anywhere: Error running WSGI application ImportError: No module named 'chamberlin.settings' File "/var/www/mikechamberlin_pythonanywhere_com_wsgi.py", line 58, in <module> application = get_wsgi_application() I have checked both my WSGI config file and my directory structure and both seem to be correct. WSGI File: import os import sys path = '/home/mikechamberlin/chamberlin' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'chamberlin.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Tree: mikechamberlin βββ ... βββ chamberlin βββ __init__.py βββ chamberlin β βββ __init__.py β βββ admin.py β βββ private_settings.py β βββ settings.py β βββ static ... Can anyone see something I'm not seeing? I've already searched here and read the ImportError help messages on PythonAnywhere, but my things seem to be named correctly. Importing from the console works, but I still get this error when trying to run the application. Much Appreciated. -
Django - format labels in admin panel
I have a label "Inactive sites" in my django admin: class InactiveSite(Site): class Meta: proxy = True verbose_name_plural = 'Inactive sites (' + str(Site.objects.filter(is_active=False).count()) + ')' I would like to format "Inactive sites" (change color, font size, etc.). How can I do that? -
Django model with number of fields less than corresponding database table
If a database table contains 100 fields, and a django application utilises only a few fields say 1 or 2, does the corresponding django model needs to be declared with 100 fields? -
Stuck on pyenv with Django, sqlite and pysqlite with spatialite
I have tries every combination of brew, Django, python and sqlite I can think of. Possible the built-in version of sqlite is messing with me. I am trying to run the test suite for django-geojson (https://github.com/makinacorpus/django-geojson). The instructions are here: https://github.com/makinacorpus/django-geojson/issues/86 I keep running into this error: django.core.exceptions.ImproperlyConfigured: The pysqlite library does not support C extension loading. Both SQLite and pysqlite must be configured to allow the loading of extensions to use SpatiaLite. I use macOS Sierra with brew, pyenv, various Python versions. Ask me if you need more info. I found several Google results from years ago that got me nowhere.