Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
In Django, why do view functions require a request parameter?
Example from Django documentation: def index(request): return HttpResponse('<h1>hellworld!</h1>') def detail(request, question_id): return HttpResponse("Question: %s" % question_id) Since the request argument is never used, why should I include it in each function signature? -
Adding Filer to Django CMS toolbar?
On the Django CMS demo they have something called a "Media Library" which takes you right to the Django Filer. How do I put this on the tool bar? I can go to it easily through the admin but not get an option for the toolbar. -
django fat models: should they make rest requests?
Some time ago a colleague of mine wrote a method on a model that updated its data over a REST api. At that time, I thought that this kind of thing should be done by a controller (or view in Django's lingo), which should make the request and tell model to update itself, and so I asked her to rewrite that. However, reading more on Django and its "Fat models" approach, I now come to think that it is the model that should do the request after all. It is a payment system, and the model in question is a Transaction. The REST api that needs to be called is a backend of that payment system that has certain statuses that affect the status of the transaction, and the REST api call is made to check the status of the remote system and to set the status of the Transaction in the local application. What would you do? Where would you put the API call: the model or a view? -
'Image' object has no attribute '_committed' django - python
I'm cropping with an imge cropper. I use a form to handle the crop process. The below snippet is that for: class EditHeaderForm(forms.Form): x = forms.FloatField() y = forms.FloatField() width = forms.FloatField() height = forms.FloatField() file = forms.ImageField() def clean_file(self): file = self.cleaned_data.get('file', False) if file: filetype = magic.from_buffer(file.read()) if file._size > 3 * 1024 * 1024: raise ValidationError("The image shouldn't more than 3 MBs") x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(file) cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) return resized_image and this is the model that I want to save image to it: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) name = models.CharField(max_length=30) header = models.ImageField(upload_to=userHeaderNameToSave, blank=True, null=True) and at last, the below snippet is my view: def change_header(request): form = EditHeaderForm(request.POST, request.FILES) if form.is_valid(): profile = get_object_or_404(Profile, pk=request.user.profile.pk) profile.header = form.cleaned_data['file'] profile.save() return JsonResponse({'success': True}) else: return JsonResponse({'success': False, 'errors': form.errors}) When I try to upload and crop the image, it shows me this error: 'Image' object has no attribute '_committed'. the cropper crops image properly, but when the profile tries to save, it shows the error. How can I solve the … -
Get information from a model using unrelated field
I have these two models: class A(models.Model): name=models.CharField(max_length=10) class D(models.Model): code=models.IntegerField() the code field can have a number that exists in model A but it cant be related due to other factors. But what I want know is to list items from A whose value is the same with code items=D.objects.values('code__name') would work but since they are not related nor can be related, how can I handle that? -
Django optional parameter is not readed from url
I was reading the thread Django optional url parameters And following the steps to generate a URL with a single optional parameter. Well, my URL should be: /client/ /client/?clientname=John And I have defined two urlpatterns url(r'^$', views.index, name='index'), url(r'^/(?P<clientname>\d+)/',views.index), Well, at this point both of them render the page. But, in my view: def index(request, clientname='noparameter'): print("The searched name is: " + str(clientname)) The searched name is always noparameter Am I doing something wrong? -
Django port not open in container when starting Django Docker container via shell script
I'm trying to containerize my Django application, and everything is working fine, except in the situation where I try to run the container from a shell script. In this case, the Django server is running, but the port is not open inside the container. Here's the command I'm running to start the container: docker run -d -p 8000:8000 --net=mynet --name myapp -v $PWD:/myapp myimage ./ss ss is a shell script that launches my Django app. It contains: python3 manage.py runserver 0:8000 When I run the Docker RUN command from the command line, everything works fine; the port is mapped correctly, I can browse to my app from a browser in my host and it loads correctly, etc. However, if I copy the above run command in a shell script (start_container.sh for example), the container launches just fine, the ports are mapped correctly, but when I try to open the app in my browser, I get a connection reset error. If open a shell to the container by running docker exec -i -t myapp /bin/bash I can get into the container. I check running processes with ps -eaf I do see the python process running my Django app. However, if I … -
Django- copy filefield url
I want to copy FileFieldURL from one model to another model.not file or image.just URL only how can I do that? for eg: Sender to receiver. sender uploaded some file for receiver and receiver receives that file. models.py sender: class DB1(models.Model): user = models.ForeignKey(User) attachments = models.FileField(upload_to= 'attachments/',blank=True,null= True) Receiver: class DB2(models.Model): user = models.ForeignKey(User) copy_url= ??? -
Django - Multiple post_save signals after create despite dispatch_uid
I'm having trouble preventing a post_save signal from firing multiple times after the creation of an object. My signal is defined as follows: @receiver(post_save, sender=Order, dispatch_uid='post_save_order') def post_save_order(sender, **kwargs): instance = kwargs.get('instance') if instance.type == 'buy': delta = instance.quantity else: delta = instance.quantity * -1 Balance.update(instance.user, instance.quote_currency, delta) the signal is imported in orders/apps.py class OrdersConfig(AppConfig): name = 'orders' def ready(self): super(OrdersConfig, self).ready() import orders.signals When printing passed kwargs to the signal after 1 Order.create: {'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': True} {'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': False} {'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': False} {'instance': object, 'signal': signal, 'using': 'default', 'update_fields': None, 'raw': False, 'created': False} so apparently on a single creation, there is 1 post_save signal fired with args created: True and three with created: False. I don't think that the problem is that the signal may be imported multiple times, because I provided a dispatch_uid and a post_delete signal that is defined in the same file is not fired multiple times on a single deletion. Can anyone enlighten me why this is happening? Thanks -
Turning off access logging for static GET requests in nginx
I see a lot of GET requests in my nginx access logs that relate to static assets. Is there a way to turn off nginx access logging for assets (e.g. in /static/)? I've already done the following, but it hasn't solved the problem: location ~* \.(?:ico|css|js|gif|jpe?g|png)$ { root /home/myuser/myproject/myapp; access_log off; expires 30d; add_header Pragma public; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; } In case relevant, I'm using nginx as a reverse proxy with gunicorn (Django). -
DJANGO static images dont show me in template
I try to use static images in my template using DJANGO framework and that images don't view in my page. I follow complete the manuals. any idea ? here the code : html : {% load staticfiles %} div class="portfolio-item"> <a href="#"><img class="img-portfolio img-responsive" src="{% static portfolio2.jpg %}"></a> </div> settings.py : STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static','static_dirs'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static','static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'static','media') MEDIA_URL = ('/media/') urls.py + urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)