Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is create_or_update generating manager attribute error?
I receiving an error AttributeError: 'Manager' object has no attribute 'create_or_update' in my views.py upon using create_or_update below. My code is shown below: SlotFilling.objects.create_or_update( originator=textobject.originator, defaults = {empty_slot: True, relevant_intent: intent_rank1, ner_entities_list: ner_entities,} ) I'm not sure how to resolve this error. I'm using Django 1.11.2, so create_or_update should be supported. The only thing I can think of is that I must have missed something in my model.py. I've included that below. Any insights into what might be happening? My models.py: from django.db import models class SlotFilling(models.Model): originator = models.CharField(max_length=20, primary_key=True) empty_slot = models.BooleanField(default=False) relevant_intent = models.CharField(max_length=20) slotted_entity = models.CharField(max_length=20) ner_entities_list = models.CharField(max_length=40) -
model design for considering multiple work schedule with number
I am trying to create convincing job hiring model. However I got stuck to show the conditions like 3 Full Time, 2 Part Time in a single job. For example, a company may post job for senior backend developer with job description and all where he may select both Full Time and Part Time work schedule. Probably he want to state how many Full Time and Part Time employer for that job. That is why I am using ManyToManyField for work schedule but I am not sure for the numbers of employeer for certain workschedule in an efficient manner. Here is the model design that I have designed for now class Category(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=50, unique=True) description = models.CharField(max_length=400, blank=True, null=True) class WorkSchedule(models.Model): name = models.CharField(max_length=100, blank=False, null=False) slug = models.SlugField(max_length=50, unique=True) class Position(models.Model): name = models.CharField(max_length=100, blank=False, null=False) slug = models.SlugField(max_length=50, unique=True) class Job(models.Model): company = models.ForeignKey( Company, related_name='jobs', on_delete=models.CASCADE) job_title = models.CharField(max_length=200, blank=True, null=True) category = models.ForeignKey(Category, related_name='jobs') description = models.TextField(blank=False, null=False) city = models.CharField(max_length=100, blank=False, null=False) position = models.ManyToManyField( Position, related_name='jobs', blank=False, null=False) work_schedule = models.ManyToManyField( WorkSchedule, related_name='jobs', blank=False, null=False) -
Django + HTML Template cannot display the right way
I'like to represent the list of news_list, the result should be like following style using 2 loops: category1 -- info_record 1 -- info_record 2 category2 -- info_record 3 The problem is, inside loop {% for m in p_list.p.name %} always nothing happen, meanwhile outside loop {% for p in p_category %} could be retrieved properly. html template file is shown as below, {% block content %} <div class = "container"> {% for p in p_category %} <div class = "row" > ......... {{p}} </br> </div> {% for m in p_list.p.name %} <div calss ="row"> .. <a href = "/pubinfo/{{m.slug}}" > {{m.title}} - [ {{m.created}}] </a> </div> {% endfor %} {% endfor %} </div> {% endblock %} the view file is shown as below, from django.shortcuts import render from datetime import datetime from .models import Category from .models import PostInfo def list_all(request): post_categories = Category.objects.all() post_lists ={} for cate in post_categories: post_lists[cate.name] = PostInfo.objects.all().filter(category = cate) import pdb; pdb.set_trace() return render(request, 'pub_post.html', {'p_category': post_lists.keys(), "p_list": post_lists}) model file is shown as below, from django.db import models from django.contrib.auth.models import User # Create your models here. class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) … -
How do I pass primary key from url to function based view in django?
I have a function based view as: @api_view(['GET', 'PUT', 'DELETE']) def hotel_detail(request, pk): # Lots of code and I'm using this URL pattern: url(r'^hotel/(?P<pk>[0-9]+)/$', api.hotel_detail) but it's not working -
How do you conditionally modify/update an object in django?
I'm looking to create/update an object in Django. My current code shown below: SlotFilling.objects.create( originator=textobject.originator, empty_slot=True, ) Where originator is set as my primary key. This works fine for creating new objects for the first time the originator is seen. However, I'm wondering how do I update the object if the originator has already exists in the DB. Basically if primary key already exists update functionality, but if it doesn't then create functionality. I'm looking for an alternative to .create here. I couldn't find how to do this in the models documentation. Is it possible? I know I could use try/except but I am wondering if django has an alternative. -
SQL query radius based on latitude and longitude of a linked model
I am having issues executing one query as I can't link properly two models together. ModelA contains a OneToOne relationship with a Location(latitude, longitude) table. The database is Postgres. The query is failing on: ( SELECT * FROM "myapp_location" WHERE id=location_id ) as location, The message it's giving me is: subquery must return only one column Here is the Query: ''' SELECT * FROM ( SELECT id, location_id, ( SELECT * FROM "myapp_location" WHERE id=location_id ) as location, ( 3956 * 2 * ASIN( SQRT( POWER( SIN(({latitude}- location.latitude) * pi()/180 / 2), 2) + COS({latitude} * pi() / 180) * COS(location.latitude * pi() / 180) * POWER(SIN(({longitude} - location.longitude) * pi() / 180 / 2), 2) ) ) ) AS distance FROM {model} ORDER BY distance ) items WHERE distance <= {miles} '''.format(latitude=latitude, longitude=longitude, miles=miles, model=model) Does anyone have any good suggestions? Much appreciated. -
ImportError: No module named captchia.fields
I am using python 2.7 django 1.11 and django simple captcha 0.56, when I using python manage.py test captcha, error popup as below, appreciated if any assistance. -
Highlight search terms on a django search results page
How can I create a search results page in Django 1.11, using PostgreSQL full text search, where the terms searched for are highlighted? -
required=false for BooleanField generates TypeError
It is my understanding from documentation and other SO posts that BooleanField needs required=. When I left it out there was a syntax error in my view.py, where I was saving to the model. However, now that I've added required=False I'm getting a TypeError. My code: class SlotFilling(models.Model): originator = models.CharField(max_length=20, primary_key=True) empty_slot = models.BooleanField(default=False, required=False) My error: File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 996, in __init__ super(BooleanField, self).__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'required' Any insights into what might be happening here? -
How to get description of object from python django backend to AJAX in front end?
So for each of my models in my apps I have the object description def unicode(self): ............................... And I want to see this description in my dynamic drop boxes generated with Ajax. My data flows in following way: 1-I have sterilizer in my api class LeaseTermSerializer(serializers.ModelSerializer): class Meta: model=LeaseTerm fields = '__all__' 2-I have api method in view @api_view(['GET']) @csrf_exempt def get_leaseterm(request, tid): leasetermobj = LeaseTerm.objects.filter(lease=tid,is_active = True) leaseterm_serializer = LeaseTermSerializer(leasetermobj, many=True) response = Response(leaseterm_serializer.data) return Response(response.data,status=status.HTTP_200_OK) 3-In my template I build it like this function getleaseterm() { //get a reference to the select element $select = $('#leaseterm'); //request the JSON data and parse into the select element var l_id = ($("select[name='lease'] option:selected").attr('value')); l_url = "/api/get_leaseterm/"+l_id+"/"; $.ajax({ url: l_url, dataType:'JSON', success:function(data1){ //clear the current content of the select $select.empty(); $select.append('<option value="-1">Select term </option>'); //iterate over the data and append a select option $.each(data1, function(key, val){ $select.append('<option value="' + val.id + '">' + val + '</option>'); }) }, }); } Problem is that the "val" value I display in dropdown if I I don't specify what field I want to show will display [object Object] for all the values in dropdown when I want it to display description of object I … -
How to cache element position Django
Issue description: At my Django project user can change element position using JQuery UI selectable() function. What I want implement: I want to cached HTML divs after replace position. For example: User change element position. After refresh website elements position should be like user preferences. I read about template cache: https://docs.djangoproject.com/en/1.10/ref/templates/api/#django.template.loaders.cached.Loader Thanks in advance! -
django-cron task not executing automatically
When I run python manage.py runcrons, the cron job successfully executes (prints 'Executed'). But it doesn't do it automatically. It's supposed to execute every minute as I've stated in the Class. Here's the code: settings.py CRON_CLASSES = [ "app.views.MyCronJob" ] app.views class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'my_app.my_cron_job' # not sure what this is supposed to be? def do(self): print('Executed') Any idea? -
Bad request sending request to Synapse API -- Django
I have a django application that I am building right now and I am trying to send a request in the sandbox to have a user login to a bank account and link that bank account through the Synapse APi. I have the body of the request and the Synapse api user id to send the full request and link the bank account through Synapse. Does anyone know why I can be getting this error. I think I know where an error is coming from, but I am not sure if it is the reason for the error. SO within django, there is the defauly keyword 'USER' that is used for all the users that are created within the app. The Synapse api also uses the key word 'USER' for creating and passing a user created by the api through with the request. I imported Users from synapse, but changed the name of the keyword to differentiate. from synapse_pay_rest import Client from synapse_pay_rest import User as SynapseUser from synapse_pay_rest.models.nodes import AchUsNode So when I pass the syanspe user account in a request, I send SynapseUser instead of User. Here is the code and error message that I am having. ValueError … -
displaying a table from views.py in a django project
<table class="table"> <thead> <tr> <th>School</th> <th>Strength</th> <th>Average</th> </tr> </thead> <tbody> {% for school in cluster.school_set.all %} <tr> <td><a href="{% url 'data:school_detail' state.id region.id cluster.id school.id %}">{{ school.school_name }}</a></td> <td>{{ school.strength }}</td> <td>school average</td> </tr> {% endfor %} </tbody> </table> This is the table in my template which shows details of all the schools in a cluster(town/city) in a tabular form with columns as 1) School Name 2) School strength 3) school Average Marks from certain number of exams. I could easily get the data for columns 1) school name & 2) school strength because they are just fields for class School. The problem is with the column average. To get the average I need to have certain lines of code which I cannot do directly in template. The problem is I don't know how to do it in views.py either. to calculate that I need school.id but from url I only get cluster.id What to do in these cases where you cannot simply get the data from views.py without giving a value from template? -
trying to override AppRegistryNotReady in standalone Django
I'm experimenting with standalone script with Django, inherited from https://github.com/syntarsus/minimal-django When I leave invoking a development server to command line call things go well: python minimal.py runserver the server is happily up and running: Performing system checks... System check identified no issues (0 silenced). September 24, 2017 - 00:58:36 Django version 1.11.5, using settings None Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. I wanted to modify the script to go a level down in Django abstractions and invoke the server with: from django.core import management management.call_command('runserver') this throws exception AppRegistryNotReady: Apps aren't loaded yet. As suggested in other SO questions, I tried overriding ths exception with: import django django.setup() ...but apparently it is not working again, so I'm lost. -
How to perform filtered database lookup in views
I'm working with a database in Django. I'm familiar with the Django database API but am wondering how to interact with the data base inside views.py. Here's the relevant model: class SlotFilling(models.Model): originator = models.CharField(max_length=20) empty_slot = models.BooleanField(default=False) I'm trying to write an If statment in my program to check if empty_slot is True for a given originator. I'm thinking I might be able to use filter() to accomplish this. Any experience with the most efficient way to implement this? -
django: Read UPDATING file PERIODICALLY and SHOW data in form
I am new to python, also celery I started to use today only, I am trying to read an updating file periodically I have used these: Reading from a frequently updated file, Python - Reading from a text file that is being written in Windows and Read from a log file as it's being written using python but they didn't even read file let alone periodically!! My view is: def myView(request): title = 'Algorithms' if request.method == 'GET': template = 'algoInput.html' form = AlgoInputForm() context = {'title': title, 'form': form} if request.method == 'POST': form = AlgoInputForm(request.POST, request.FILES) if form.is_valid(): task = configAndRun(form.cleaned_data) output = readFile.delay('algorithms/out-file.txt') template = 'result.html' result = AlgoResult(initial={'outputData': output}) context = {'title': title, 'form': form, 'result': result} return render(request, template, context) Above configAndRun method use subprocess to run a long task which create a file, you can imagine it as ping google where all output goes to a file. Next method readFile read that file and display output. Its a celery tasks.py as follows: from celery import shared_task @shared_task def readFile(file): try: file = open(file, "r") loglines = follow(file) data = [] for line in loglines: data.append(line) return data except Exception as e: raise e def … -
Django Rendering Formsets Performance Issues
I'm using modelformsets to modify large numbers of objects at once (up to 1500), but loading the template with all the forms in takes an extremely long time. 10939.18ms according to django debug toolbar. I initially assumed this was bad SQL queries however I'm only making 5 according to the toolbar, and I can't seem to work out what is causing the long loading time. Any advice on what may be causing this would be hugely appreciated! Edit: To clarify, using the same queryset to just display the objects in another view doesn't take long at all. -
Using a Django form on more than one HTML page
In this latest project I'm using a simple contact form, which resolves to the url /email/. I also want to include this form on the homepage. In the past I've used get_context_data when I have a page class in a view, but I'm using cookiecutter with crispy forms for the first time and don't know where to do that, or even if that is the right thing to do. Here's the forms.py: from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions from crispy_forms.layout import Submit class ContactForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) content = forms.CharField(required=True, widget=forms.Textarea) # the new bit we're adding def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field('contact_name', placeholder="Full Name", autofocus=""), Field('contact_email', placeholder="Email Address"), Field('content', placeholder=""), Submit('sign_in', 'Submit', css_class="btn btn-info"), ) self.fields['contact_name'].label = "Your name:" self.fields['contact_email'].label = "Your email:" self.fields['content'].label = "Your message:" ...and that renders perfectly at /email/. How do I get this form to appear on the front page also? In case it's needed, here's the urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^email/$', views.email, name='email'), url(r'^success/$', views.success, name='success'), … -
Show result from two unrelated models but have common column and value
Background info: it is for a loan system. Basically, the company gives its clients items that are predefined such as Flour, Raisin etc. Each transaction is documented. Clients pay any time they want without caring for which item they are paying. All it matters to the company is they payback the total amount they awe. Hence, I came up with these two models: class Give(models.Model): client=models.ForeignKey(User) quantity=models.DecimalField() price=models.DecimalField() done_on=models.DateField() item=models.ForeignKey(Items) class PayBacks(models.Model): client=models.ForeignKey(User) paid_on=models.DateField() amount_paid=models.DecimalField() Now, it is the displayed that is mattering to me. I want the output to be something like this (tabular): Client Total Borrowed Total Paid Samuel $100 $40 Daniel $200 $200 So far, I can only do them indepedently (loans and paybacks separately). What is the proper way to get the above result for JSON output: [{"client":"Samuel","total borrowed":100,"total paid":40}] -
Heroku GeoDjango issues with missing GDAL (and possibly GEOS)
I'm working on a GeoDjango application and am using Heroku (with a Heroku-16 stack) as my platform. I am following the instructions found here, which specify the following: If your application requires geo libraries, experimental support for a handful of these libraries are available: GDAL v2.2.1 (v1.11.5 for cedar-14) Geos v3.6.2 (v3.4.2 for cedar-14) Proj v4.9.3 (v4.8.0 for cedar-14) To make these libraries available to your application, simply set the BUILD_WITH_GEO_LIBRARIES environment variable: $ heroku config:set BUILD_WITH_GEO_LIBRARIES=1 During your next build, these libraries will be downloaded and installed. In your Django settings.py, also add the following: import dj_database_url DATABASES['default'] = dj_database_url.config() DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' GDAL_LIBRARY_PATH = os.getenv('GDAL_LIBRARY_PATH') GEOS_LIBRARY_PATH = os.getenv('GEOS_LIBRARY_PATH') This will ensure that Django can find the GEOS libraries that are installed. I have set the env variables in Heroku: However, I have found that this isn't making a difference when it's time to deploy: 2017-09-23T19:29:55.142378+00:00 app[web.1]: % '", "'.join(lib_names) 2017-09-23T19:29:55.142414+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. Here's my requirements.txt: dj-database-url==0.4.1 Django==1.11.5 gunicorn==19.6.0 psycopg2==2.6.2 pytz==2017.2 whitenoise==3.2 The only anomaly I have here is that I'm using Django … -
Dealing with two forms in Django : Unable to pass the primary id from one object to another through one view
I have difficulties to work with 2 forms within one view. Here is my code and issue : Model class Process(models.Model): name = models.CharField(max_length = 200) order = models.IntegerField( default=0, validators=[ MinValueValidator(0) ] ) status = models.BooleanField(default = True) process_owner = models.CharField(max_length = 200) created_by = models.CharField(max_length = 200) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) class SubProcess(models.Model): process = models.ForeignKey(Process, on_delete=models.CASCADE) next_sub_process = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=False) name = models.CharField(max_length = 200) status = models.BooleanField(default = True) sub_process_owner = models.CharField(max_length = 200) created_by = models.CharField(max_length = 200) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) Forms class createProcessForm(ModelForm): class Meta: model = Process fields = ['name', 'order',] class createSubProcessForOneShotCreationForm(ModelForm): class Meta: model = SubProcess fields = ['name',] Template <form action="{% url 'processmanagement:create_process_subProcess_step' %}" method="post"> {% csrf_token %} <p>Process</p> {{ form_process }} <p>Sub Process</p> {{ form_subProcess }} <p></p> <input type="submit" value="Submit" /> </form> The view def create_process_subProcess_step(request): if request.method == 'POST': form_process = createProcessForm(request.POST) print('form_process : ' + str(form_process)) form_subProcess = createSubProcessForOneShotCreationForm(request.POST) if form_process.is_valid() and form_subProcess.is_valid(): process_instance = form_process.save() subProcess_instance = form_subProcess.save(commit=False) subProcess_instance.process = process_instance subProcess_instance.save() return redirect('processmanagement:displayProcessAndSubProcess') form_process = createProcessForm() form_subProcess = createSubProcessForOneShotCreationForm() context = { 'form_process' : form_process, 'form_subProcess' : form_subProcess } return … -
Django upload form with different models
I am building my first Django app and I need to have an upload page where I would be able to upload multiple files in different upload forms. I need different forms and, I guess, models since depending on the form the file has to be stored in a respective folder in my media root and go through different further transformations. I also want different users have different levels of access to these uploads. So far I have something like this (I have quite a bit of additional code inside functions in views.py that send data to data frames or other programs but I am not posting those: models.py class Upload(models.Model): document = models.FileField(storage=OverwriteStorage(),upload_to=get_file_path) upload_date=models.DateTimeField(auto_now_add =True) class Upload_variables(models.Model): variables = models.FileField(storage=OverwriteStorage(),upload_to=get_file_path_var) upload_date=models.DateTimeField(auto_now_add =True) forms.py from django import forms from uploader.models import Upload, Upload_variables class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ('document',) class UploadFormVar(forms.ModelForm): class Meta: model = Upload_variables fields = ('variables',) views.py def home(request): if request.method=="POST": img = UploadForm(request.POST, request.FILES) if img.is_valid(): img.save() else: img=UploadForm() files=Upload.objects.all() return render(request,'home.html',{'form':img}) def variables(request): if request.method == 'POST': var = UploadFormVar(request.POST, request.FILES) if var.is_valid(): var.save() else: var = UploadFormVar() files_st = Upload_variables.objects.all() return render(request, 'home.html', {'form_b': var}) HTML <form action="#" method="post" enctype="multipart/form-data"> … -
Angular with Django development
I've almost finished developing my frontend in Angular 2 using static json files as API mocks. Now I want to use it with my real API from Django, and I'm struggling with few issues, since it is my first Angular 2 frontend. I've moved whole Angular project generated by Angular CLI as frontend directory within my Django project. Django is exposing API at /api, and I want to perform request to that API from Angular. In production, Angular sources will be transpiled into javascript and moved into static (i guess), but I don't know how to handle it during development. Is it possible to run Django development server with Angular ng serve on the same port at the same time? If I'll run them at different ports, I will need to hardcode my API url in frontend, and enable CORS which won't be enabled in production. What are the best practices to develop Angular with Django? -
Django additional arguments to per view cache
In the excellent Django cache framework documentation it mentions the possibility of adding additional arguments to template fragment caching: Sometimes you might want to cache multiple copies of a fragment depending on some dynamic data that appears inside the fragment. For example, you might want a separate cached copy of the sidebar used in the previous example for every user of your site. Do this by passing additional arguments to the {% cache %} template tag to uniquely identify the cache fragment: {% load cache %} {% cache 500 sidebar request.user.username %} .. sidebar for logged in user .. {% endcache %} It’s perfectly fine to specify more than one argument to identify the fragment. Simply pass as many arguments to {% cache %} as you need. However it doesn't seem to mention anything about doing something similar when the per-view cache. It mentions the possible to use @vary_on_headers and @vary_on_cookie, but that is not quite the same. In my use case I would for example like to use something like request.user.company to ensure all users from the same company get the same cached version of a view. Is it not possible to add such arguments to the per-view cache …