Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unknown job error on gunicorn upstart job
I am getting the error start: Unknown job: bifrost.conf when I use the command sudo start gunicorn.bifrost.conf. My conf file is as follows: description "Gunicorn server for bifrost" start on net-device-up stop on shutdown respawn chdir /home/ubuntu/sites/bifrost/source exec ../virtualenv/bin/gunicorn --bind unix:/tmp/bifrost.socket Bifrost.wsgi:application Also my nginx config looks like this. server { listen 80; location /static { alias /home/ubuntu/sites/bifrost/static; } location / { proxy_set_header Host $host; proxy_pass http://unix:/tmp/bifrost.socket; } } -
upstream prematurely closed connection (uwsgi + nginx + django)
I am trying to configure my django application on a new server. It works fine unless I try to pass GET parameters. I get the following errors. uWSGI: [pid: 21530|app: 0|req: 8/9] 109.68.173.7 () {42 vars in 880 bytes} [Thu Mar 2 17:19:29 2017] GET /install/?token=123&shop=1234&insales_id=124 => generated 0 bytes in 71 msecs (HTTP/1.1 500) 0 headers in 0 bytes (0 switches on core 0) nginx: 2017/03/02 09:19:29 [error] 21644#0: *1 upstream prematurely closed connection while reading response header from upstream, client: 109.68.173.7, server: 151-248-112-157.xen.vps.regruhosting.ru, request: "GET /install/?token=123&shop=1234&insales_id=124 HTTP/1.1", upstream: "uwsgi://unix:/home/trackpost.sock:", host: "151-248-112-157.xen.vps.regruhosting.ru" My config files. nginx.conf: # For more information on configuration, see: # * Official English Documentation: http://nginx.org/en/docs/ # * Official Russian Documentation: http://nginx.org/ru/docs/ user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; # Load dynamic modules. See /usr/share/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 120; client_max_body_size 20M; uwsgi_read_timeout 86400; uwsgi_send_timeout 86400; proxy_buffers 8 32k; proxy_buffer_size 64k; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { listen … -
Django models override save and new field value from related objects
I have such Django models: class Car(models.Model): rating = models.PositiveIntegerField( default=0, verbose_name=_('Rating'), ) class ReportInfo(models.Model): car = models.ForeignKey( Car, related_name='car_info', verbose_name='Report', ) And I need to form rating for my car instances including info from reports, in such way: def save(self, *args, **kwargs): rating = 0 for item in self.car_info.all(): rating += 10 self.rating = rating super(Car, self).save(*args, **kwargs) So, I need to get all reports of my car, then get some other data from the report and then save rating into the field. But, self.car_info.all() returns me old data. That means next: when I click save button in admin page of a new car, my code in save method does not have access to real reports, as they are not created yet. Do you understand? What can I do? -
approaching attribute in django auth.user model extension
#models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) birthday = models.DateField(blank=True, null=True) I extended the django.contrib.auth.views.models.User with additional infomations such as birthday etc. The problem is that I can't access birthday with request.user.profile in the views.py I did like this : @login_required def edit(request): if request.method == 'POST': user_form = UserEditForm(instance = request.user, data = request.POST) profile_form = ProfileEditForm(instance = request.user.profile, data = request.POST, files = request.FILES) if user_form.is_valid() and profile_form.is_valid(): request.user.profile.birthday = user_form.cleaned_data['birthday'] user_form.save() profile_form.save() else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm( instance = request.user.profile ) return render(request, 'views/edit_profile.html', {'user_form' : user_form, 'profile_form' : profile_form}) The full traceback: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fac3cbfa488> Traceback (most recent call last): File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/peterkim/PycharmProjects/brave/bravepeach_web/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] … -
django POST in 2 models / database tables
I am absolutly new to this and just finished the tutorials into my needs. Now I'm stuck because I want to save all data from POST orders in 2 models at same time. I tried this def create(self, valiated_data) but the "Altkunde" Table is still empty, while I got lots of new entries in "Kunde" model. After hours of research I can't find a solution. Please give any hints or tips. Here's my models.py models.py views.py views.py serializer.py class KundeSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Kunde #Kunden die Notebook leihen fields = ('url', 'QR', 'owner', 'created', 'Name', 'Info') def create(self, validated_data): Altkundeeintrag = AltKunde.objects.create(**validated_data) return Kunde.objects.create(**validated_data) class AltkundeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = AltKunde #Kunden die Notebook geliehen haben (Altbestand) fields = ('url', 'QR', 'Verleiher' 'created', 'Name', 'Info') -
How to create Django model field to store users related to the model?
I am building a web application in python using the django framework. In my application users need to be able to apply for jobs. I am unsure how to save a list of users who have applied for a job in the job model as a field. Here is my Job.py model: class Job(models.Model): user = models.ForeignKey(User, related_name="jobs") created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=30) description = models.TextField() pay = models.FloatField() category = models.CharField(max_length=3, choices=JOB_CATEGORY_CHOICES) #applicants = def __str__(self): return self.title def get_absolute_url(self): return reverse('jobs:detail', kwargs={ 'job_pk': self.id } ) I need to have the applicants field (which is currently commented out) to store the users who have applied for the job. How do I do this? -
2 dynamic ChoiceFields in a form
I want 2 choice fields where the second choice field is dependent to the first. At first i want to choose the group and can then select the user of this group. class Form(forms.ModelForm): field1 = forms.ModelChoiceField(queryset=Group.objects.all()) field2 = forms.ModelChoiceField(queryset=None) def __init__(self, *args, **kwargs): super(Form, self).__init__(*args, **kwargs) self.fields['field2'].queryset = User.objects.filter(group__contains=self.data['field1']) But it doesn't work. -
Javascript, best way to refresh a div in a Django Template
I want to refresh the <div> that my google chart is embedded in every 30 seconds to display updates to the data in the model that it is using. here is the template: metrics.html {% extends 'metrics/metrics_header.html' %} {% block content %} <h1>Metrics</h1> <p>Submitted = {{ submitted }}, Conforming = {{ conforming }} Transcoding = {{ transcoding }} Complete = {{ complete }} Error = {{ error }} </p> <script type="text/javascript"> google.charts.load("current", {packages:['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Job State', 'Jobs', { role: "style" }], ['Submitted', {{ submitted }},'blue'], ['Conforming', {{ conforming }},'purple'], ['Transcoding', {{ transcoding }},'yellow'], ['Complete', {{ complete }},'green'], ['Error', {{ error }},'red'] ]); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]); var options = { title: "Total Number of Jobs Processed", bar: {groupWidth: "100%"}, legend: { position: "none" }, }; var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values")); chart.draw(view, options); } </script> <div id="columnchart_values" style="width: 100%; height:600px;"></div> {% endblock %} I have been using this to refresh the entire page: : <script> setTimeout(function(){ window.location.reload(true); }, 5000); </script> As you can imagine it looks really bad when the entire page reloads every 5 seconds, is there a more … -
PIL Image.thumbnail() fails with unknown IOError
I have a Django app that gathers data via a multipart form inclusive of both POST and FILES values. The form data is received correctly by my Django views, and I am trying to process the image files passed via the form so as to produce thumbnails via PIL.Image. However, when I call the Image.thumbnail() method (or, for that matter, any method other than Image.open()) I get an IOError which I am unable to investigate any further. Here's the code: from PIL import Image import io import os from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.base import ContentFile from django.conf import settings def generate_thumbnail(file): if 'image' in file.content_type: print "about to save the thumbnail" file_content= ContentFile(file.read()) print "file read" full_filename = os.path.join(settings.MEDIA_ROOT, file.name) print "path selected" fout = open(full_filename, 'wb+') for chunk in file_content.chunks(): fout.write(chunk) fout.close() print " file saved" im = Image.open(open(full_filename, 'rb')) print im.getbands() #no problem up to this point try: size = 128,128 thumb = im.thumbnail(size) except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror) The script raises the IOError exception, but the print gives me only "I/O error(None): None". Please note that fout.write() successfully writes my file to the selected path, and that Image.open() as well as Image.getbands() … -
Run python code oh button click without redirecting
I'm working on a web-page, which allows to move a camera. I created some buttons, so whenever you press it, we go to urls.py "moveRight" and then to the views.py. In a views.py move() function (which is a python script) moves a camera, and then I go back to the first page, where the button was. panel.py <form action="{% url 'cameracontrol:moveRight' %}" method="post"> {% csrf_token %} <button type="submit" id="right" class="btn btn-default" aria-label="Move right"></button> </form> urls.py urlpatterns = [ url(r'^$', views.panelView, name='panel'), url(r'^right/$', views.moveCameraRight, name='moveRight'), ] views.py def moveCameraRight(request): # move() return HttpResponseRedirect('/cameracontrol/') But I need the /cameracontrol/ page running without any reloading. I saw something about ajax, but couldn't figure out how exactly to use it here -
Python - Django - Sum values of a list, too slow
I have a Django project I use to show energy consumptions of a certain time period. I use the following code in order to obtain the data from the database: consumptions = Measurement.objects.filter(idhouse=house) filtered = consumptions.values_list("cost",flat=True).filter(enddatetimestamp__gt=startdate,enddatetimestamp__lte=enddate) total = sum(filtered) I obtain a list of 9000 values, but when I sum those values, it takes 3-4 seconds. I don't know why it takes so much time (I have checked queryset is obtained fastly). In addition, I have tested this code: filtered=consumptions.objects.filter(enddatetimestamp__gt=startdatets,enddatetimestamp__lte=enddatets).aggregate(total=Sum('cost')) total = filtered['total'] However, it takes 3-4 seconds too. I've created a python script which does the same job: array = range(9000) start = datetime.datetime.now() total = sum(array) print "Time: \t{}".format(datetime.datetime.now()-start) In this case, the script takes 0.000176 seconds. I don't know where's the difference, taking into account that, in Django's code, I hit the database once, in order to get the consumptions I want. So in theory, it should take the same time. ¿Can anyone help me? Thanks in advance. -
Django - Profile matching query does not exist
When I click the links on my homepage I am confronted with this error. Profile matching query does not exist http://imgur.com/tCLQAJn Please tell me what I'm doing wrong. The problem has something to do with my views or models, I think. Views.py from django.contrib.auth.decorators import login_required from django.http import Http404 from django.shortcuts import render, redirect from django.template.defaultfilters import slugify from django.views.generic.base import TemplateView from webapp.models import Profile from webapp.forms import ProfileForm def index(request): Profiles = Profile.objects.all() return render(request, 'index.html', {'Profiles': Profiles,}) def Profile_detail(request, slug): Profiles = Profile.objects.get(slug=slug) return render(request, 'Profiles/Profile_detail.html', {'Profile': Profile,}) def edit_Profile(request, slug): Profiles = Profile.objects.get(slug=slug) form_class = ProfileForm if request.method == 'POST': form = form_class(data=request.POST, instance=Profile) if form.is_valid(): form.save() return redirect('Profile_detail',slug=request.user) else: form = form_class(instance=Profile) return render(request, 'Profiles/edit_Profile.html', {'Profile': Profile, 'form': form,}) urls.py from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from webapp import views urlpatterns = [ url(r'^$', views.index, name='home'), url(r'^about/$', TemplateView.as_view(template_name='about.html'), name='about'), url(r'^contact/$', TemplateView.as_view(template_name='contact.html'), name='contact'), url(r'^Profiles/(?P<slug>[-\w]+)/$', views.Profile_detail, name='Profile_detail'), url(r'^Profiles/(?P<slug>[-\w]+)/edit/$', views.edit_Profile, name='edit_Profile'), url(r'^admin/', include(admin.site.urls)), ] models.py from __future__ import unicode_literals from django.contrib import admin from django.db import models # Create your models here. class Profile(models.Model): name = models.CharField(max_length=255) description = models.TextField() slug = models.SlugField(unique=True) -
populate a django form in a jquery dialog
I am showing a simple Django form in a jquery dialog box. I can show a blank form just fine but am having issue populating it with an item data. My Django model is as follows: class DummyModel(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=150) time_points = models.PositiveIntegerField() more_text = models.CharField(max_length=100) class Meta: db_table = "dummy" I have created a corresponding form for this model and render it in a jquery dialog. So, I have the corresponding ModelForm as: class DummyForm(ModelForm): class Meta: model = DummyModel fields = ['name', 'description'] Now, what I want to do is display this form when a link is clicked on a django-tables2 table through a jquery dialog. So for that purpose, I have a LinkColumn object in my django tables as: edit = tables.LinkColumn('dummy_edit', args=[tables.A('pk')], orderable=False, empty_values=(), verbose_name='') And this link is rendered as: def render_edit(self, record): # Change this properly. return mark_safe('<a href="" onclick="return EditDialog()">Edit</a>') My first question is how can I pass the data associated with this record to the javascript function in my django template? {% extends 'base.html' %} {% block title %}Dummy | Edit test {% endblock %} {% block content %} <div id="dialog" title="Edit" style="display: none;"> <form method="post" action=""> {% … -
Django installation error on python 2.7 (centOs 6.8)
Have a trouble with Django installation and unfortunately had not find any information about the same bug in the net. When I try to do first migration of django database I had such an output: > python manage.py migrate Traceback (most recent call last): File > "manage.py", line 23, in <module> > execute_from_command_line(sys.argv) File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/core/management/__init__.py", > line 367, in execute_from_command_line > utility.execute() File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/core/management/__init__.py", > line 359, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/core/management/base.py", > line 294, in run_from_argv > self.execute(*args, **cmd_options) File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/core/management/base.py", > line 345, in execute > output = self.handle(*args, **options) File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/core/management/commands/migrate.py", > line 83, in handle > executor = MigrationExecutor(connection, self.migration_progress_callback) File > "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/db/migrations/executor.py", > line 20, in __init__ > self.loader = MigrationLoader(self.connection) File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/db/migrations/loader.py", > line 52, in __init__ > self.build_graph() File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/db/migrations/loader.py", > line 203, in build_graph > self.applied_migrations = recorder.applied_migrations() File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/db/migrations/recorder.py", > line 65, in applied_migrations > self.ensure_schema() File "/etc/network/scripts/learning_log/ll_env/lib/python2.7/site-packages/django/db/migrations/recorder.py", > line 59, in ensure_schema > raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) > django.db.migrations.exceptions.MigrationSchemaMissing: Unable to > create the django_migrations table (near "BGN": syntax error) This "BGN": syntax error I didn't find anywhere. The same problem with pip installation or from the sources, either in venv or without … -
Django - not getting the queries correct
This is the scenario now: Admin (leader of the group) logs in to see all the members who are in admins group. But what admin gets is members from all other groups when admin only want to see members who are in admins group. I only want admin to see members in his group. Still a newbie so appreciate your help! admin\models.py class Administrator(AbstractUser): ... asoc_name = models.CharField(max_length=100) class Meta: db_table = 'Administrator' member\models.py from pl.admin.models import Administrator class Member(models.Model): member_no = models.AutoField(primary_key=True) asoc_name = models.CharField(max_length=50) ... class Meta: db_table = 'Member' class Association(models.Model): asocnumber = models.AutoField(primary_key=True) asoc_name = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'Association' class member_asoc(models.Model): asocnumber = models.OneToOneField(Association) member_no = models.OneToOneField(Member) user = models.OneToOneField(Administrator) class Meta: db_table = 'member_asoc' Views.py from django.db.models import F class member_overview(ListView): model = Member template_name = 'member/member_overview.html' member_asoc.objects.filter(user__asoc_name=F('member_no__asoc_name')) Let me know if you need more info. -
Django filter: example.objects.filter(owner=user, expression) giving error
Where my expression is dynamic. example -1: "name=Myname, age=32" , length is 2 here example -2: "name=Myname" , length is 1 here Here my search filed length will vary dynamically. Can we write expressions in filter instead "Key" and "value"? Is it possible to implement this in django? -
django form does not render in a jquery dialog
I have a model in Django as follows: class DummyModel(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=150) time_points = models.PositiveIntegerField() more_text = models.CharField(max_length=100) class Meta: db_table = "dummy" I would like to create a corresponding form for tis model and render it in a jquery dialog. So, I have the corresponding ModelForm as: class DummyForm(ModelForm): class Meta: model = DummyModel fields = ['name', 'description'] Now, what I want to do is display this form when a link is clicked on a django-tables2 table through a jquery dialog. So for that purpose, I have a LinkColumn object in my django tables as: edit = tables.LinkColumn('dummy_edit', args=[tables.A('pk')], orderable=False, empty_values=(), verbose_name='') And this link is rendered as: def render_edit(self, record): # Change this properly. return mark_safe('<a href="" onclick="return EditDialog()">Edit</a>') Now, my template (review.html) looks as follows: {% extends 'base.html' %} {% block title %}Dummy | Edit test {% endblock %} {% block content %} <div id="dialog" title="Edit" style="display: none;"> <form method="post" action=""> {% csrf_token %} {{DummyForm.as_table}} <input type="submit" value="Submit Form"/> </form> </div> {% load static %} {% load render_table from django_tables2 %} <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> function EditDialog() { $( "#dialog" ).dialog(); return false; } </script> <div class="function-page"> <div class="table-form"> … -
I have just started learning mongodb. when i am using mongodb it shows attribute error? Please help. Thanks in advance
enter code here [ C:\Users\GAURAVSAMANT\Desktop\python\gauravsamant>python manage.py runserver Unhandled exception in thread started by .wrapper at 0x0000022CDED07268> Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\Anaconda3\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Anaconda3\lib\site-packages\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Anaconda3\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Anaconda3\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Anaconda3\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 665, in exec_module File "", line 222, in _call_with_frames_removed File "C:\Users\GAURAVSAMANT\Desktop\python\gauravsamant\main\models.py", line 8, in class MyDetail(models.Model): File "C:\Anaconda3\lib\site-packages\django\db\models\base.py", line 119, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Anaconda3\lib\site-packages\django\db\models\base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "C:\Anaconda3\lib\site-packages\django\db\models\options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Anaconda3\lib\site-packages\django\db__init__.py", line 33, in getattr return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Anaconda3\lib\site-packages\django\db\utils.py", line 212, in getitem conn = backend.DatabaseWrapper(db, alias) AttributeError: module 'mongoengine.base' has no attribute 'DatabaseWrapper'] -
Django: multiple objects in one form field
I'm doing a project in Django and I can't seem to find my way around this problem I have. Namely, I have two Models: class Document(models.Model): [fields are not relevant here] class DocumentCodes(models.Model): document = models.ForeignKey('Document') code = models.CharField(max_length=12) Now, I want to have a HTML form to add new Document that, in addition to it's own fields (which I've already done), will also have a text area where I can enter several codes (in separate lines) and they should be then validated and added to DocumentCodes as separate objects. I would do it all in View (simply create new objects), but I need to validate the codes (raise errors if needed) and I don't think I should do that in views, but rather in Form, right? So how to properly design these two Forms and work it out in Views? -
How to perform abundant task in django
I am working on an application where I have to get the data from google BigQuery to local Postgres. So I am doing the following task in order to achieve this. Export Table from BigQuery to Google Storage in CSV format. Download CSV from Google Storage to local storage. Parse the CSV to Postgres. In doing this task in a synchronous manner the whole Django server is not listening to any other new request while doing this. Thus making user side unresponsive. So how to do this task with making Django Server available to other requests also. I had tried celery but in celery, Session Data and all others API are not accessible -
Celery daemonization
I'm trying to use celery with Django, and I was able to set them up so, that I can start celery with (dbbs)$ celery -A dbbs worker -l info and it does tasks sent by Django server. Now I was going to daemonize celery, but fail here. I can start the service with sudo /etc/init.d/celeryd start with settings as from manual here http://docs.celeryproject.org/en/latest/userguide/daemonizing.html, but it fails to start. celeryd config file is: CELERYD_NODES="dbbs_worker" ENABLED="true" CELERY_BIN="/home/voytekh/Env/bdds/bin/celery" CELERY_APP="dbbs" #CELERY_APP="proj.tasks:app" CELERYD_CHDIR="/home/voytekh/dbbs/" CELERYD_LOG_FILE="/var/log/celery/celery-%n%I.log" CELERYD_PID_FILE="/var/run/celery/celery-%n.pid" CELERYD_OPTS="--time-limit=300 --concurrency=8" #CELERYD_OPTS="--time-limit=300 -c 8 -c:worker2 4 -c:worker3 2 -Ofair:worker1" CELERYD_LOG_LEVEL="DEBUG" CELERYD_USER="celery" CELERYD_GROUP="celery" btw the service also fails to start with config file empty, so it must be not it. verbose output when attempting to start: $ sudo sh -x /etc/init.d/celeryd start + . /lib/lsb/init-functions + run-parts --lsbsysinit --list /lib/lsb/init-functions.d + [ -r /lib/lsb/init-functions.d/01-upstart-lsb ] + . /lib/lsb/init-functions.d/01-upstart-lsb + unset UPSTART_SESSION + _RC_SCRIPT=/etc/init.d/celeryd + [ -r /etc/init//etc/init.d/celeryd.conf ] + _UPSTART_JOB=celeryd + [ -r /etc/init/celeryd.conf ] + [ -r /lib/lsb/init-functions.d/20-left-info-blocks ] + . /lib/lsb/init-functions.d/20-left-info-blocks + [ -r /lib/lsb/init-functions.d/40-systemd ] + . /lib/lsb/init-functions.d/40-systemd + _use_systemctl=0 + [ -d /run/systemd/system ] + prog=celeryd + service=celeryd.service + systemctl -p LoadState show celeryd.service + state=LoadState=loaded + [ LoadState=loaded = LoadState=masked ] + [ 11377 -ne … -
Key error '% trans "{}" %' in custom tag
I've created a simple tag to make adding tooltips more simple. I've create a templatetags folder with __init__.py and html_tags.py. html_tags.py from django import template from django.utils.html import format_html register = template.Library() @register.simple_tag def tooltip(text): return format_html('<a href="#" data-toggle="tooltip" title="{% trans "{}" %}"><img src="{% static "icons/tooltip.png" %}"></img></a>'.format(text)) The problem is that it seems not work with {% trans "text" %} which I need. This is the error: KeyError at /dashboard/alerts-settings/ '% trans "{}" %' but I use format so tt should be {% trans "text" %} instead of {% trans "{}" %}. So I tried to do this: format_html('<a href="#" data-toggle="tooltip" title="{{% trans "'+text+'" %}}"><img src="{{% static "icons/tooltip.png" %}}"></img></a>') It raises: Single '}' encountered in format string Do you know where is the problem? -
Get group of object s from Django model
I've created an one model, it contains consulting date, time and locations. I want to group the data by date, time and location by using Django ORM models.The result should be [,[group of objects],[group of objects]] and each group contains[,]. How can i achieve this result. -
Creating a Questionnaire within Django
My Idea is to create a questionnaire within Django which will ask questions around radio buttons then store these questions within a SQL Database. Once this is done I would like to take this information and do a comparison between the individuals who took the survey. But I'm not sure what the best way to start this project would be. I'm looking for suggestions. -
How to get the instance of the model in clean()
I've overwritten the clean() method to perform a custom validation in my model. Is there any way to get the instance of the model that is being saved?