Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing with-declared variables to a custom function in Django template tags
I want to build a table of 5 columns and 8 rows with the data contained in a list of 40 elements: {% for row_num in 0|range:8 %} {% with startrange=row_num|multiply:5 endrange=row_num|multiply:5|add:5 %} {{ startrange }} {{ endrange }} <div class="row"> {% for item in items|slice:startrange,endrange %} <div class="col"> {% include "shop/item_card.html" %} </div> {% endfor %} </div> {% endwith %} {% endfor %} I have successfully defined multiply and add custom functions, and I have defined startrange and endrange. Now, I need to pass them to slice function. I've tried slice:"startrange:endrange" among other possibilities, but none seems correct. How can I pass 2 (or more) variables to a custom function? -
How to rename Table name in Django?
I just created a model named Carts and now I want to rename it to Cart only, how do I do it? I have tried doing this: python manage.py makemigrations <app_name> and then python manage.py migrate But its not reflecting the change in the database table: I am seeing the database as: python manage.py sqlmigrate <app_name> 0001 Please Help! -
Django No Post matches the given query?
A bit of magic : today i was woken up, power my laptop and start working for my project, but... When i pushed on button, django was return to me 404 error, and say "that No match queries". It a bit sad me, because yesterday all was work as well as never. This is my huge view: def p(request, pk): user = request.user topic = get_object_or_404(Topic, pk=pk) post = get_object_or_404(Post, pk=pk) comment = Comments.objects.filter(pk=pk) who_come = WhoComeOnEvent.objects.filter(which_event=topic.id) if request.is_ajax() and request.POST.get('action') == 'joinEvent': who_come_obj = WhoComeOnEvent.objects.create( visiter=user, which_event=post.topic ) visitors_usernames = [] for w in who_come: visitors_usernames.append(w.visiter.username) return HttpResponse(json.dumps(visitors_usernames)) if request.method == 'POST': form = CustomCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.creator = user # comment.save() #из-за этой блевотины было 2 записи в базу comment = Comments.objects.create( body=form.cleaned_data.get('body'), creator=user, post=post ) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) # return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment, # 'form': form, 'who_come': who_come}) else: form = CustomCommentForm() return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment, 'form': form, 'who_come': who_come}) the problem in post = get_object_or_404(Post, pk=pk), this code worked for month but now it shows 404 error. I don't know what the reason. Why it broken? I try to change post … -
Nginx showing default page instead of Django (Gunicorn)
Can't figure out where is the problem with my configuration. I have DigitalOcean VPS where I run Django project. I've configured Gunicorn and Nginx. Set correct IP address. Checked gunicorn status (ok). No errors in /var/log/nginx/error.log Even deleted default from sites-enabled and still see nginx default page. gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/django/nameofmyproject ExecStart=/home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/django/nameofmyproject/nameofmyproject.sock nameofmyproject.wsgi:application [Install] WantedBy=multi-user.target sites-available/nameofmyproject server { listen 80; server_name <my_ip_address>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/nameofmyproject; } location / { include proxy_params; proxy_pass http://unix:/home/django/nameofmyproject/nameofmyproject.sock; } } gunicorn status unicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2017-10-19 09:56:18 UTC; 1min 2s ago Main PID: 1372 (gunicorn) Tasks: 4 Memory: 138.0M CPU: 3.971s CGroup: /system.slice/gunicorn.service ├─1372 /home/django/nameofmyproject/nameofmyprojectvenv/bin/python /home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --work ├─1555 /home/django/nameofmyproject/nameofmyprojectvenv/bin/python /home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --work ├─1556 /home/django/nameofmyproject/nameofmyprojectvenv/bin/python /home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --work └─1557 /home/django/nameofmyproject/nameofmyprojectvenv/bin/python /home/django/nameofmyproject/nameofmyprojectvenv/bin/gunicorn --access-logfile - --work Oct 19 09:56:18 ubuntu-16 systemd[1]: Started gunicorn daemon. Oct 19 09:56:21 ubuntu-16 gunicorn[1372]: [2017-10-19 09:56:21 +0000] [1372] [INFO] Starting gunicorn 19.7.1 Oct 19 09:56:21 ubuntu-16 gunicorn[1372]: [2017-10-19 09:56:21 +0000] [1372] [INFO] Listening at: unix:/home/django/nameofmyproject/nameofmyproject Oct 19 09:56:21 ubuntu-16 gunicorn[1372]: [2017-10-19 09:56:21 +0000] [1372] … -
Django filter a day name in many to many field that contains list of days
class DayOfWeek(models.Model): name = models.CharField(max_length=45) class PermanentShiftSchedule(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid4) shift = models.ForeignKey(Shift, related_name='shift_permanent_schedule', on_delete=models.CASCADE) branch_employee = models.ForeignKey(BranchEmployee, related_name='branch_emp_permanent_schedule', on_delete=models.CASCADE) days_of_week = models.ManyToManyField(DayOfWeek, related_name='permanent_shift_days') Now I want to filter the PermanentShiftSchedule where days_of_week field contanins "Thursday" days_of_week field may contain multiple days names -
Error 404 on post request from AJAX call with django
I'm trying to integrate jquery formbuilder, but I'm constantly getting a 404 (Not Found) whenever I post the data. This is how my html looks like (where I render the form) <form id="custom-form"> <div id="fb-editor"></div> <button type="submit" class="btn btn-round btn-primary"> Submit Form </button> </form> the js file I call: jQuery(function($) { var $fbEditor = $(document.getElementById('fb-editor')), $formContainer = $(document.getElementById('fb-rendered-form')), fbOptions = { onSave: function() { $fbEditor.toggle(); $formContainer.toggle(); $('form', $formContainer).formRender({ formData: formBuilder.formData }); }, }, formBuilder = $fbEditor.formBuilder(fbOptions); $('.edit-form', $formContainer).click(function() { $fbEditor.toggle(); $formContainer.toggle(); }); $('#custom-form').on('submit', function (e) { e.preventDefault(); // Collect form data var formData = JSON.stringify(formBuilder.actions.getData('json', true)); console.log(formData); // Send data to server $.post('/ajax/save/', formData) .done(function (response) { console.log('form saved') }).fail(function (jqXHR) { console.log('form was not saved') }); // Prevent form submission return false; }); }); and this is the url: url(r'^ajax/save/$', views.ajax_formbuilder_save, name='ajax-formbuilder-save') This is the specific error I'm getting: POST http://127.0.0.1:8000/ajax/save/ 404 (Not Found) How should I solve this? Thanks! -
Django project set up with MySql and virtual environment from start
I am new to django so I need to start with django projects..I need information regarding how to start with django project using MySql database and virtual environment on Linux. -
Can not solving Reverse accessor clashes
I have a bug that I can not solve in django>=1.8,<1.9. I merged my changes and I get this: ERRORS: archive.Booking.articles: (fields.E304) Reverse accessor for 'Booking.articles' clashes with reverse accessor for 'Booking.articles'. HINT: Add or change a related_name argument to the definition for 'Booking.articles' or 'Booking.articles'. archive.Booking.articles: (fields.E305) Reverse query name for 'Booking.articles' clashes with reverse query name for 'Booking.articles'. HINT: Add or change a related_name argument to the definition for 'Booking.articles' or 'Booking.articles'. events.Booking.articles: (fields.E304) Reverse accessor for 'Booking.articles' clashes with reverse accessor for 'Booking.articles'. HINT: Add or change a related_name argument to the definition for 'Booking.articles' or 'Booking.articles'. events.Booking.articles: (fields.E305) Reverse query name for 'Booking.articles' clashes with reverse query name for 'Booking.articles'. HINT: Add or change a related_name argument to the definition for 'Booking.articles' or 'Booking.articles'. Here is my model: class Booking(events_models.AbstractBooking): period = models.ForeignKey('archive.Period', null=True, related_name='events', help_text='ref_artistic_period') distributions = models.ManyToManyField('archive.Distribution', related_name='bookings', through='archive.Booking2Distribution') def get_absolute_url(self): return reverse('archive:detail', kwargs={'slug': self.slug, 'pk': self.id}) class Meta: ordering = ['date_start',] Here is my base class with articles field: class AbstractBooking(SearchMixin, TranslationMixin, MediaMixin, PriceMixin, ImagesMixin, DownloadsMixin, AdminMixin, TicketMixin): ... articles = models.ManyToManyField('blog.Article', related_name='bookings', blank=True) ... I tried added articles field to my Booking class like below, but without success: articles = models.ManyToManyField('blog.Article', related_name='%(class)s_bookings', … -
send just a specific filed on ModelSerializer to client - django rest framework
I have a Serializer like below: class KlassStudentSerializer(ModelSerializer): student = ProfileSerializer() klass = KlassSerializer() class Meta: model = KlassStudents fields = ['pk', 'student', 'klass'] I want to send just klass values in a view and send just student in another view. How can I do that? -
In Django REST API, should a POST only APIView define a GET method?
I am fairly new to Django and REST APIs in general. I am exposing a data import URL using Django REST framework i.e. /api/data/import. I currently have an associated APIView that implements a POST method, but returns 405 - Bad Request on a GET as that is the default framework behaviour when GET has not been explicitly implemented. This MDN article strongly suggests GET should always be implemented, so should I just return an empty 200 response? This also smells a little bit like I am using REST incorrectly. Thanks -
Remain logged in ldap between views using Django
I'm using the ldap3 module and trying to create a simple Web App to search for users in an ldap server. The user (help desk people normally, doing the searching) must log in and input the user searched for. The code so far creates/binds to the ldap server, and upon finding the searched user, a different page is displayed showing the user's credentials. So far so good. On the page displaying the credentials, there is a search box, so that that the user can search again for another user. The problem I have now is how to remain logged in via ldap, so that the user only needs to input the searched user (and not again his username and password). I'm thinking I need to parse the conn object in my returns, but somehow this seems a little clumsy. Here is my code: views.py def ldap_authentication(request): if request.POST: username = request.POST['username'] LDAP_MODIFY_PASS = request.POST['password'] searchFilter = request.POST['searchUser'] LDAP_AUTH_SEARCH_DN = '{}\\{}'.format(settings.DOMAIN_NAME, username) conn = ldap_connect(request, un=LDAP_AUTH_SEARCH_DN, pw=LDAP_MODIFY_PASS) attributes_list_keys = ['mail', 'givenName', 'employeeID', 'department', 'telephoneNumber', 'st', 'cn', 'l', 'title'] conn.search( search_base=settings.LDAP_AUTH_SEARCH_BASE, search_filter= '(cn={})'.format(searchFilter), search_scope=SUBTREE, attributes = attributes_list_keys ) entry = conn.entries[0] attributes_split = list(entry._attributes.values()) attr_keys = [] attr_values = [] for i … -
python custom password hasher error
hye . i cannot import my new custom password hasher and i still cannot figure it out why . the error : ImportError at /admin/ No module named 'honeywordHasher.hashers.MyHoneywordHasherdjango'; 'honeywordHasher.hashers' is not a package i already did install honeywordHasher in INSTALLED_APPS and i have the init.py inside the honeywordHasher file. directory : C:. ├───checkout │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───contact │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───custom_user │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───honeywordHasher │ ├───migrations │ │ └───__pycache__ │ └───__pycache__ ├───profiles │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───accounts │ └───__pycache__ ├───register │ ├───migrations │ ├───templates │ │ └───accounts │ └───__pycache__ ├───sqlite ├───tryFOUR │ └───__pycache__ └───__pycache__ settings.py : PASSWORD_HASHERS = [ 'honeywordHasher.hashers.MyHoneywordHasher' 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] i already create hashers.py and also the honeyword generation in honeywordgen.py . i still get this error . can someone help me ? -
Dynamic Django model Table x doesn't exist
I'm new to Django and I start to do a project that consist of create a dynamic table based on csv file. The program have to manage columns addition and deletion on the fly. I face an issue which is that the table do not exist and I don't understand why ... I guess it's a basic problem. (1146, "Table x doesn't exist") CSV File is loaded : HTML def gestionTable(request) : if (request.method == 'POST' and request.FILES['file']) : if (handle_uploaded_file(request.FILES['file'], request.POST['table'])) : messages.success(request, 'ok') else : messages.error(request, _("failed")) return HttpResponseRedirect('#') return render(request, 'weather/gestion_table.html') Model is created here : Python def csv_to_model(f, tableName): reader = csv.reader(f, delimiter=";") data_list = list(reader) col_names = data_list[0] first_values = data_list[1] fields = {} for i in range(len(col_names)) : try : fields[col_names[i]] = typeDeduce(type(literal_eval(first_values[i])).__name__) print(typeDeduce(type(literal_eval(first_values[i])).__name__)) except ValueError: fields[col_names[i]] = typeDeduce("str") return create_model(name=str(tableName), fields=fields, app_label="weather", module="weather") def typeDeduce(a): if (a == "int") : return models.IntegerField() if (a == "float") : return models.FloatField() if (a == "str") : return models.CharField() Dynamic model factory : def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None): class Meta: pass if app_label: setattr(Meta, 'app_label', app_label) if options is not None: for key, value in options.iteritems(): setattr(Meta, key, value) attrs = {'__module__': module, 'Meta': … -
Can not add a user to group in django using admin site
I cannot add a user to a group in django, when use admin site. I got the message below: Internal Server Error: /admin/auth/user/3/change/ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 551, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/sites.py", line 224, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1511, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1408, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1449, in _changeform_view self.save_related(request, form, formsets, not add) File "/usr/local/lib/python3.5/dist-packages/django/contrib/admin/options.py", line 1001, in save_related form.save_m2m() File "/usr/local/lib/python3.5/dist-packages/django/forms/models.py", line 446, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related.py", line 1686, in save_form_data getattr(instance, self.attname).set(data) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 1007, in set self.add(*new_objs) File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 934, in add self._add_items(self.source_field_name, self.target_field_name, … -
Push django app to IBM Bluemix
I am currently trying to push my local Django App to IBM Bluemix servers. I am using Cloud-foundry to do it and the cf command. Here is the error i get when i'm using the following command: cf push my-app $ python manage.py collectstatic --noinput test os1913 55 static files copied to '/tmp/app/backoffice2/static'. Exit status 0 Staging complete Uploading droplet, build artifacts cache... Uploading build artifacts cache... Uploading droplet... Uploaded build artifacts cache (155M) Uploaded droplet (223.8M) Uploading complete Destroying container Successfully destroyed container 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 starting 0 of 1 instances running, 1 crashed FAILED Error restarting application: Start unsuccessful I tried to use the … -
Can't override product status in Django Mezzanine admin
Hi I've been trying to override Django Mezzanine's product status field (Draft/ Published) and add a new option (Draft/Published/Research) in admin but no luck. I'm a total newbie at Django trying to start a new project on Django instead of Wordpress, so please see with my low knowledge on django's structure. Here's my code: cart/cart/apps/mezzanine/models.py from django.db import models from django.utils.translation import ugettext, ugettext_lazy as _ from mezzanine.core.models import Slugged, MetaData, TimeStamped CONTENT_STATUS_DRAFT = 1 CONTENT_STATUS_PUBLISHED = 2 CONTENT_STATUS_RESEARCH = 3 CONTENT_STATUS_CHOICES = ( (CONTENT_STATUS_DRAFT, _("Draft")), (CONTENT_STATUS_PUBLISHED, _("Published")), (CONTENT_STATUS_RESEARCH, _("Research")), ) class Displayable(Slugged, MetaData, TimeStamped): status = models.IntegerField(_("Status"), choices=CONTENT_STATUS_CHOICES, default=CONTENT_STATUS_RESEARCH, help_text=_("With Draft chosen, will only be shown for admin users " "on the site.")) publish_date = models.DateTimeField(_("Published from"), help_text=_("With Published chosen, won't be shown until this time"), blank=True, null=True, db_index=True) Displayable.default=CONTENT_STATUS_RESEARCH Displayable.choices=CONTENT_STATUS_CHOICES cart/cart/apps/mezzanine/admin.py: from django.contrib import admin from mezzanine.conf import settings from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from cart.apps.mezzanine.models import Displayable from mezzanine.core.admin import BaseTranslationModelAdmin class DisplayableAdminForm(ModelForm): def clean_content(form): status = form.cleaned_data.get("status") content = form.cleaned_data.get("content") if status == CONTENT_STATUS_PUBLISHED and not content: raise ValidationError(_("This field is required if status " "is set to published.")) return content class DisplayableAdmin(BaseTranslationModelAdmin): list_display = ("title", "status", "admin_link") list_display_links = ("title",) … -
How can I access a model that is instantiated later for a calculation in Django?
I am fairly new to Python/Django and I have the following problem. I have structured my models as follows: class Foo: name = models.CharField(max_length=10) class Bar: othername = models.CharField(max_length=10) othername2 = models.CharField(max_length=10) fkey = models.ForeignKey(Foo, on_delete:models.CASCADE) class FooBaroo: FooBarooInt = models.IntegerField() Barkey = models.ForeignKey(Bar, on_delete:models.CASCADE) The relations are that 1 Foo has multiple Bars and 1 Bar has multiple FooBaroos. What I want is to create a table with Django wherein I have a complete overview of a Bar class. One of the things I want to display is the sum of all FooBarooInts of a Bar. If I however add a property to Bar that takes all relevant FooBaroo objects (through objects.all().filter()) it ends up not returning anything in most cases, but not all (which I find weird). Does anybody have an idea of how I should solve this? -
405 Error, Method not allowed Django Rest Framework and ATrigger
I am trying to make a webhook that get triggered by ATrigger. I tried it but every time it shows error 405, method not allowed. It works when doing a POST through the server, or through Hurl.it -
TemplateSyntaxError: Could not parse the remainder
I'm receiving this error each time I try to access a list within a Django template. I have checked the answers to similar questions, but the problem is usually a lack of % or some other character somewhere. As long as I can see, this is not the case: Here I'm passing a dict containing a a list of item id as keys and list of URLs to images as a value for each id. I know I should integrate this into the item model, but since I'm still at development with SQLite3 I cannot store lists easily. And anyway I am intrigued by this problem. So: <a href="{% url 'details_view' item_id=item.id %}"><img class="hover-image" src="{{ img_gallery[item.id][0] }}" alt=""> Exception Value: Could not parse the remainder: '['item.id'][0]' from 'img_gallery['item.id'][0]' Also, yesterday I tried using bootstrap4 flex-grid to easily achieve 5 columns. Since I'm using pagination to retrieve 20 items, my idea was slicing the list of items (model) for each row, like: {% for item in items[0:5] %} And I also received the same error, even when this was the recommended aproach in related answers aboput slicing data passed with a view. In both cases I cannot find the problem, and … -
Django Import-Export Import Duplicate key value violates Error
I'm working on a project with Django 1.10, Python 3.6 and PostgreSQL as the database backend, in which I have a model called 'Article" and I need to import data from CSV files. I have imported my first CSV file successfully with the following fields: id, link & category It's ID fields starts from 1 to 1960 then in next file, I have started ID field from 1961 to onward but it shows the following error: Line number: 1961 - duplicate key value violates unique constraint "article_article_pkey" DETAIL: Key (id)=(1961) already exists. Even when i see my Article model in Django admin it shows IDs from 1- 1960 Here's my models.py: class Article(models.Model): id = models.AutoField(primary_key=True) link = models.URLField(max_length=255) category = models.CharField(max_length=255, choices=Categories) Here's admin.py @admin.register(Article) class ArticleAdmin(ImportExportModelAdmin): resource_class = views.ArticleResource readonly_fields = ('id',) -
python -m django startproject didn't work, I want to know why
My system is centOS6.8, django version is 1.8.6, python 3.5.0 (my_env) [root@localhost my_env]# python -m django startproject mysite /usr/local/python3.5.0/bin/python3: No module named django.__main__; 'django' is a package and cannot be directly executed Thank you for my friends, I need to know why? -
How to create big csv files and send notification to user after completion for download in django
I am hitting some APIs to create CSVs file. total time taken by the CSV is 20-30 minutes avg. How to send notification to download link after creation file in django python -
Multithreading/multiprocessing in Django
I am working on a Django project in which i'll create an online judge (User can submit solutions to programming problems and will be autograded at server using python subprocess library where i can call g++) (something similiar to Codeforces website). When user submits a solution i take his solution file and have to asynchronously call the grading function (automatic grading may take time) I didnt use celery for the purpose because i read it has overheads and would have been overkill for mey project. So i built a queue object in Django and called a function to run on queue by creating a thread and it's working fine (i have read threads are evil warning). I wanted to ask should i call python multiprocessing library to optimize the automatic grading on different cores. For example i'll create 4 queues and call grading function on each queue through different Processes. Will it be nice idea or overheads of calling multiprocessing will be larger? Also will it be safe to do (if not good style of programming)? -
Django: Class object has no attribute of standard function
I have a model: class Order(models.Model): STATUS_CHOICES = ( (100, 'First'), (200, 'Second'), ) status = models.IntegerField('Status', choices=STATUS_CHOICES) def accept(self): self.status = 200 self.save() return self.status, self.get_status_display() And I have a Unit-Test for it: class CustomTestCase(TestCase): @classmethod def setUp(self): pass @classmethod def save(self): pass class OrderTest(CustomTestCase): def test_accept(self): result = Order.accept(self) expected = (200, 'Second') self.assertEqual(expected, result) As you can see, i added 'save' function that do nothing, the reason for that is because without that custom 'save' function I keep getting this error: '[OrderTest] object has no attribute [save]'. If there is a better solution to that custom 'save' function please tell me. But this kind of solution will not work with django-built-in 'get_status_display()' function. And without solution I keep getting this trouble: '[OrderTest] object has no attribute [get_status_display]'. What can I do to make this work as I need ? -
Could not parse the remainder: '{{request.LANGUAGE_CODE}}' from '{{request.LANGUAGE_CODE}}'
I programing with django 1.11, now I have following script in post_list.html {% with lang={{request.LANGUAGE_CODE}} %} {% endwith %} <p> {% if lang == 'zh-CN' %} {{object.category.name_zh_CN}} {% else %} {{object.category.name}} {% endif %} </p> but I cannot get lang actually with following error message, please help.Thanks. TemplateSyntaxError at /adv/australia-strategic/ Could not parse the remainder: '{{request.LANGUAGE_CODE}}' from '{{request.LANGUAGE_CODE}}' Request Method: GET Request URL: http://localhost:8030/adv/australia-strategic/ Django Version: 1.11.6 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '{{request.LANGUAGE_CODE}}' from '{{request.LANGUAGE_CODE}}' Exception Location: /Users/wzy/anaconda2/envs/python36/lib/python3.6/site-packages/django/template/base.py in __init__, line 700 Python Executable: /Users/wzy/anaconda2/envs/python36/bin/python Python Version: 3.6.3 Python Path: ['/Users/wzy/expo3/expo', '/Users/wzy/anaconda2/envs/python36/lib/python36.zip', '/Users/wzy/anaconda2/envs/python36/lib/python3.6', '/Users/wzy/anaconda2/envs/python36/lib/python3.6/lib-dynload', '/Users/wzy/anaconda2/envs/python36/lib/python3.6/site-packages', '/Users/wzy/expo3/expo']