Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not parse the remainder: '=='Sophia'' from 'abc.first_name=='Sophia'' Python/Django
I'm trying to put an == sign inside an if statement in my html document (fourth line). It looks like this: <ol> {% for league in teams %} {% for abc in league.curr_players.all %} {% if abc.first_name=='Sophia' %} <li>{{league.location}} {{league.team_name}} </li> {% endif %} {% endfor %} {% empty %} <p>No leagues found. Try <code>python manage.py loaddata data.json</code>, or, if that doesn't work, going <a href="{% url 'make_data' %}">here</a> (but be prepared to wait).</p> {% endfor %} </ol> Anyways, I keep getting this error saying it can't parse the argument at that certain point. -
How to pass a function result to a tuple?
I am working on a Python/Django/Wagtail project, and at some point I have a class like this: class SuperClass(BaseClass): body = StreamField([ ('overview_speakers', OverviewSpeakers()), ]) def some_function(): return 'Hola' OverviewSpeakers is a class that is expecting an argument and I want to try to pass in the results of some_function() I tried both: body = StreamField([ ('overview_speakers', OverviewSpeakers(self.some_function())), ]) and body = StreamField([ ('overview_speakers', OverviewSpeakers(SuperClass.some_function())), ]) But respectively it yells that self or SuperClass are not defined. What can I do to pass in the results of the function? -
Select Column name based on values
In a table, a row have 24 columns which contains Boolean values either true or false. I need to select the columns where the values are true or false. -
Customize context data
I have three class. The first class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) the second class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' and the third class CustomerPerceptionIndexView(CustomerMixin, PerceptionIndexView): template_name = 'loanwolf/customers/perceptions.html' pjax_template_name = 'loanwolf/customers/perceptions.pjax.html' def get_context_data(self, **kwargs): context = super(CustomerPerceptionIndexView, self).get_context_data(**kwargs) filter_perceptions= (Perception.objects.filter(loan__request__customer__pk=self.customer.pk)) resultant = [r for r in context['results'] if r['object'] in filter_perceptions] context["resultant"] = resultant return context Actually, the context of CustomerPerceptionIndexView did not contain the attribute state. I would like to get access state attribute from Perception class in the context of CustomerPerceptionIndexView class. How could I do such thing? Thanks in advance! P.S. Please let me know if it is unclear. -
Two ManyToMany relations to the same model via the same intermediate model in Django
My models: class Person(SchoolModel): first_name = models.CharField(max_length=75) last_surname = models.CharField(max_length=75) students = models.ManyToManyField('self', through='StudentParent', through_fields=('parent', 'student'), related_name='+') parents = models.ManyToManyField('self', through='StudentParent', through_fields=('student', 'parent'), related_name='+') class StudentParent(SchoolModel): student = models.ForeignKey('Person') parent = models.ForeignKey('Person') relation = models.CharField(max_length=26) class Meta: unique_together = ('student', 'parent') As seen above Person model has two m2m relationships to itself: students, and parents. Each person may have many students on the same Person table, and also many parents. However, Django does not allow this: Person: (models.E003) The model has two many-to-many relations through the intermediate model 'StudentParent'. Probably because it would be a pain for Django to validate and save such data concurrently. However, I only need to use these fields to retrieve related models more easily. Examples: person_obj.students.all() Person.objects.filter(parents__in=another_person_queryset) So my question is, 1) Is there a way around this issue in Django1.11 (making such 2 m2m fields possible via configuration etc)? 2) is there a way to make this happen for a read only scenario by other means? Would using a proxy to the intermediary model trick django to make 1) happen? Would using custom managers help make 2) happen? What would be the shortest, neatest path? Note: I am aware a similar question is asked … -
Django: showing many to many additional fields in template
I have following problems when trying to show the additional field of the 'trough table' of a many-to-many relationship templates. my model.py: class Product(models.Model): productName = models.CharField(max_length=500) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) def __str__(self): return self.productName def get_absolute_url(self): return reverse('itake:productList') class Order(models.Model): orderID = models.CharField(max_length=100, blank=True, null=True) products = models.ManyToManyField(Product,related_name="order_item", through="OrderItem") def __str__(self): return self.orderID class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,null=True) order = models.ForeignKey(Order,on_delete=models.CASCADE, null=True) orderQuantity = models.IntegerField(default=10) def __str__(self): return self.order.orderID + '-' +self.product.productName my views.py: def orderDetails(request,order_id): order = get_object_or_404(Order,pk=order_id) products = order.products.all() context = {'order': order,'products':products} return render(request, 'itake/orderDetails.html', context) my templates: {% for products in products %} <p>{{products.productName}} | {{products.price}} | {{products.orderQuantity}}</p> {% endfor %} However, it can only list the product name and price, the orderQuantity is not showed in the webpage. -
Where has django.utils.translation.trans_real.templatize vanished?
The Django 1.11 documentation says it should be there and I checked the github repo and it is not there. In 1.10.7 it was still there. -
POST from AngularJS to Django API to obtain JWT and returning a 405 error
i'm getting this 405 when i do a POST to get the token in the endpoint that supposed accepts POST requests. I'm using rest_framework and rest_framework_jwt Endpoint: from django.conf.urls import url from django.contrib import admin from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import refresh_jwt_token from rest_framework_jwt.views import verify_jwt_token urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^api/api-token-auth/', obtain_jwt_token), url(r'^api/api-token-verify/', verify_jwt_token), url(r'^api/api-token-refresh/', refresh_jwt_token), ] AngularJS POST: $scope.login = function () { $http.post('api/api-token-auth/', { 'username': $scope.username, 'password': $scope.password }) .success(function (response) { $scope.logged = true; $scope.jwt = response.token; console.log(response.token); store.set('token', response.token); }) .erro(function (response, status) { $scope.logged = false; console.log(status); }); } I'm getting the same error when doing the POST in Postman -
Find most common field value in queryset
I have a Post and Profile model. I'm trying to find out the most common category in a list of user posts. Here's my models: class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1') class Profile(models.Model): user = models.ForeignKey(User, blank=True, null=True) def most_common_category(self): posts = Post.objects.filter(user=self.user) for post in posts: print(post.category) # 1, 1, 2, 3, 2, 2, 4, 1, 2, 2 How would I do this? -
Override context
I have three class. The first class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) the second class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' and the third class CustomerPerceptionIndexView(CustomerMixin, PerceptionIndexView): template_name = 'loanwolf/customers/perceptions.html' pjax_template_name = 'loanwolf/customers/perceptions.pjax.html' def get_context_data(self, **kwargs): context = super(CustomerPerceptionIndexView, self).get_context_data(**kwargs) filter_perceptions= (Perception.objects.filter(loan__request__customer__pk=self.customer.pk)) resultant = [r for r in context['results'] if r['object'] in filter_perceptions] context["resultant"] = resultant return context I would like to get access state attribute from Perception class in the context of PerceptionIndexView class. How could I do such thing? P.S. Please let me know if it is unclear. -
Quiz App Website for Django
Looking for a tutorial or simple quiz application for a Django website. I am new to Django but I have worked with Python before. Please help me to build a quizzing website in Django. -
Python 3.6.1 Filter Multiple Objects and Inputs
I'm new in Python and I'm trying to filter some objects from my models class. I have successfully added a new order to the system and now I want to send a notification to the workers who's service is related to the order requested. Example: CustomerA sends a request of a electrician on date X at Y address. In my services' team I have Josh and Cris who are mechanics and Arnold and David who are electrician. I want to filter first which worker covers that service (resulting Arnold and David), then I want to filter their online_status. Here is what I've got so far: models.py class Service(models.Model): #electrician, mechanic, etc name = models.CharField(max_length=500) short_description = models.CharField(max_length=500) image = models.ImageField(upload_to='service_image/', blank=False) price = models.IntegerField(default=0) def __str__(self): return self.name class Worker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='worker') avatar = models.CharField(max_length=500) phone = models.CharField(max_length=500, blank=True) address = models.CharField(max_length=500, blank=True) service = models.ForeignKey(Service, blank=True, null=True) online_status = models.BooleanField(default=1) # 1=online OR 0=offline def __str__(self): return self.user.get_full_name() class Order(models.Model): REQUESTED = 1 ACCEPTED = 2 DENIED = 3 CANCELED = 4 COMPLETED = 5 STATUS_CHOICES = ( (REQUESTED, "Requested"), (ACCEPTED, "Accepted"), (DENIED, "Denied"), (CANCELED, "Canceled"), (COMPLETED, "Completed"), ) customer = models.ForeignKey(Customer) worker = models.ForeignKey(Worker, blank=True, … -
(django-template) link to current page but change values of variables
I have an archive.html template that is used by two views: myapp:paginated_view and myapp:whole_view. Both views can be shown in a reversed or in a normal way. Now I want to create a link to change in between the ways. That means there are four cases: (after the arrow what happens when you click that link) Whole_view & non-reversed -> whole_view and reversed Whole_view & reversed -> whole_view and non-reversed Paged_view & non-reversed -> paged_view (still on same page) and reversed Paged_view & reversed -> paged_view (still on same page) and non-reversed I wonder if I had to declare all cases with if-clauses in the template or work with absolute url-pathes or create multiple templates, but these are my only ideas. Is there a better way? (I hope for something like: {% url current_page reverse=not reverse %} My url conf: (in myapp) urlpatterns = [ url(r'^archive/(?P<reverse>[n]{0,1})/?$', views.ArchivePagedView.as_view(), name="paged_archive"), url(r'^archive/all/(?P<reverse>[n]{0,1})/?$', views.WholeArchiveView.as_view(), name='whole_archive'), ] As you can see, in the url-conf reverse can be n or it's empty/doesn't exist. In my template it's true or false. How to deal with this? -
modify django templates in production
Okay this might be a bad question but as someone who is new to django production I am a little lost I have deployed my django project on Ubuntu 16.04 with a nginx, gunicorn and postgres stack. I am trying to make some simple template changes in the project (adding content in the .html templates) but the changes aren't showing up when I restart gunicorn and nginx. All I can find online is reference to the collectstatic command which only seems to collect css, js and img... How would I go about serving the updated template files? Thanks in advance for your help. -
where to define a slug without a model.py in Django
I am rather new to django, and am looking at where to define a slug in django when creating a backend without models. the url is created as such: url(r'^main/(?P<slug>[-\w]+)/', include('main.urls')), I have slugs within my main.urls which I define inside of each view function. Im not exactly sure where to define this slug(link, whatever you may call it). On other django slug examples, the common way is in a model, and I am currently talking to a program rather then creating my own models. Would this be in the urls.py, or views.py (in the project, not app)? Thank you so much. Hopefully this is understandable. -
Get queryset of objects that are unique based on a field - Django
I have a large inventory of vehicles, and there are a lot of duplicates that are only unique by a stock number. I am trying to query for a list of all vehicles, but only want one vehicle for each model number, ignoring it's stock number field. V1.stock_no = 15393 V2.stock_no = 15394 V1.model_no = 98874 V2.model_no = 98874 So when doing a query in Django, I only want one instance of each object with that model no. I read this Stack Overflow question Select DISTINCT individual columns in django?, but q = ProductOrder.objects.values('Category').distinct() just returns a distinct list of model numbers, and not the object instance, and Productorder.objects.all().distinct('category') made available since Django 1.4, only works with PostgreSQL, and not SQLite3. Is there any way to do this with SQLite, without having some contrived for loop to get it done ? -
Updating Django Admin Interface to current look after upgrade
Since I updated my application from django 1.7 through every update to 1.11, the django admin interface has stuck to the old classic admin look. How do I update the django admin UI to the current latest look -
Django initial data for built-in app
I'm starting to use the "redirects" app built into Django to replace some existing redirects I have in my urls.py. I was wondering if there was any generally accepted way to include initial data in the code base for other apps. For example, if it was for an app I created I could create a migration file that had a RunPython section where I could load some initial data. With a built-in or third-party app there doesn't seem to be any way to create a migration file to add initial data. The best I can think of right now is to include a .sql file in my repository with the initial data and just manually import the data as I push the code to the different instances. -
Same view, but with different contexts
In Django, I have two apps which use the same view (i.e., PerceptionIndexView). I created the method def get_context_data(self, **kwargs): context = super(PerceptionIndexView, self).get_context_data(**kwargs) filter_perceptions= (Perception.objects.filter(loan__request__customer__pk=self.customer.pk)) resultant = [r for r in context['results'] if r['object'] in filter_perceptions] context["resultant"] = resultant return context However, one of those apps doesn't have the attribute customer, i.e., AttributeError: 'PerceptionIndexView' object has no attribute 'customer'. Question : Is it possible that two app using the same view could have a different context? Could I insert get_context_data() directly inside the url? Thanks in advance! P.S. Please tell me if the question is unclear. -
Python/Django Trying to continually reference foreign keys in multiple classes and be able to print out information from views
I know how to reference a single foreign key but when it comes to a foreign key inside another foreign key, I'm lost. I can't think of the correct logic to make this work, which makes me think there's a special logic that applies to this. What I've tried: b2=[] league = League.objects.get(name='International Collegiate Baseball Conference') team = league.teams.all() for b in team.curr_players.all(): b2.append(b.first_name + b.last_name) From my models: class League(models.Model): name = models.CharField(max_length=50) sport = models.CharField(max_length=15) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Team(models.Model): location = models.CharField(max_length=50) team_name = models.CharField(max_length=50) league = models.ForeignKey(League, related_name="teams") class Player(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) curr_team = models.ForeignKey(Team, related_name="curr_players") all_teams = models.ManyToManyField(Team, related_name="all_players") -
django project not working in virtualenv
I recently installed a virtualenv and cloned an existing django project into it. When I run python manage.py runserver I'm getting the following error: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/Users/user/eb-virt/lib/python2.7/site-packages/django/core/management/init.py", line 443, in execute_from_command_line utility.execute() File "/Users/user/eb-virt/lib/python2.7/site-packages/django/core/management/init.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/user/eb-virt/lib/python2.7/site-packages/django/core/management/init.py", line 261, in fetch_command klass = load_command_class(app_name, subcommand) File "/Users/user/eb-virt/lib/python2.7/site-packages/django/core/management/init.py", line 69, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/Users/user/eb-virt/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module import(name) File "/Users/user/eb-virt/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 8, in from django.core.servers.basehttp import AdminMediaHandler, run, WSGIServerException, get_internal_wsgi_application File "/Users/user/eb-virt/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 26, in from django.views import static File "/Users/user/eb-virt/lib/python2.7/site-packages/django/views/static.py", line 95, in template_translatable = ugettext_noop(u"Index of %(directory)s") File "/Users/user/eb-virt/lib/python2.7/site-packages/django/utils/translation/init.py", line 75, in gettext_noop return _trans.gettext_noop(message) File "/Users/user/eb-virt/lib/python2.7/site-packages/django/utils/translation/init.py", line 48, in getattr if settings.USE_I18N: File "/Users/user/eb-virt/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner self._setup() File "/Users/user/eb-virt/lib/python2.7/site-packages/django/conf/init.py", line 42, in _setup self._wrapped = Settings(settings_module) File "/Users/user/eb-virt/lib/python2.7/site-packages/django/conf/init.py", line 95, in init raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'application-name.settings' (Is it on sys.path?): No module named application-name.settings -
How to search for multiple keywords over multiple columns in Django
I want to be able to input a list of strings like so: ["searchterm1", "searchterm2", "searchtermN"] And output all rows from the database where "searchterm1" matches one of the columns OR "searchterm2" matches one of the columns and so on. Is there a way to do so? -
Install failed with Django-Chronograph by pip in django 1.10
Similar to this question but i got a different error. I'm try to installing via pip with: pip install django-chronograph I'm using python 2.7 and a virtualenv pip freeze Django==1.10 django-backbone==0.2.3 django-jstemplate==1.1.1 gunicorn==18.0 MySQL-python==1.2.5 six==1.10.0 South==0.7.6 unicodecsv==0.9.4 Error: pip install django-chronograph Collecting django-chronograph Using cached django-chronograph-0.3.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/87/h3ltndc5279cknk_vn9nzjjc0000gn/T/pip-build-_JDRxl/django-chronograph/setup.py", line 32, in <module> setup_distribute() File "/private/var/folders/87/h3ltndc5279cknk_vn9nzjjc0000gn/T/pip-build-_JDRxl/django-chronograph/setup.py", line 18, in setup_distribute distribute_setup = __import__('distribute_setup') File "distribute_setup.py", line 1 <html> ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/87/h3ltndc5279cknk_vn9nzjjc0000gn/T/pip-build-_JDRxl/django-chronograph/ -
Equivalent of background-position: 50% 50% for img css
I can't use background-position because I'm using django variables into CSS. I looked at these Image position equivalent to background position CSS background position 50% 50% does not work (the suggested answer here uses background-position, where I just want to use an img tag) I want to replicate this into just an img tag. everything looks good except background-position: 50% 50%. What's the equivalent for that? /*.main-header { min-height: 40%; background: url('../img/parallax11.jpeg') no-repeat center; background-size: cover; text-align: center; background-position: 50% 50%; } So far this has worked .cover-img { display: flex; min-height: 30%; overflow: hidden; height:30vh; width: 100vw; object-fit: cover; } -
Django CSV: variable in context_data and template has different values
I am experiencing an issue in a template where a variable that I'd expect to have a certain value (True) actually has another one (False). The template is fetched via an AJAX request and rendered in the HTML, actually replacing existing HTML with the old data. So basically this is the simplified scenario with the parts involved: partial_template.html <div id="some-div"> {% if active %} {% endif %} </div> class SomeView(FormView): def get_context_data(self, **kwargs): context = super(SomeView, self).get_context_data(**kwargs) context.update({ 'active': is_active # is_active is True now }) return context def form_valid(self, form): # HttpJsonResponse is a custom HttpResponse that serializes data as JSON # and sets the mimetype as 'application/json' return HttpJsonResponse({ 'template': render_to_string(self.template_name, self.get_context_data()) }) This view is called when making a request to the mapped URL with AJAX, and the response.template is rendered in an element of the DOM. All this is part of a hierarchy of views and a more complex tree of templates. However, ultimately, we are rendering the template passing the context data, which I can vouch has a context['valid'] = True, so it should override any existing valid variables from different contexts, right? I am pretty lost here, I cannot think why the context data …