Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Websockets server in django
I want to run Websockets python-based library on Django. for example: # WS server example import asyncio import websockets async def hello(websocket, path): name = await websocket.recv() print(f"< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"> {greeting}") start_server = websockets.serve(hello, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() This sample run websockets server, but it blocks Django from running (because of the event_loop().run_forever() part). Note: I'm a beginner at Django -
How to use {{ post.title }} from blog.models into home_app template
I want to use the {{ post.title }} and {{ for post in object_list }} into my home template to show the latest 4 posts, i tried to import> from blog.models import Post, but it doesnt work i guess im putting it in the wrong place Please help blog.models from django.db import models from ckeditor.fields import RichTextField class Post(models.Model): title = models.CharField(max_length = 140) image = models.ImageField(upload_to="media", blank=True) body = RichTextField(config_name='default') date = models.DateField() def __str__(self): return self.title home.urls from django.urls import path from . import views urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), ] home.views from django.views.generic import TemplateView from allauth.account.forms import LoginForm class HomePageView(TemplateView): template_name = 'home/index.html' mysite tree look like this mysite home admin app models tests urls views blog admin app models tests urls views -
Creating search form in admin panel - Django
I am new to django.. I created the sqlite3 database called "test.db"(not using the models.py or default database to sync) in views.py for saving data And created the html to get the value to store in test.db and print the data using the normal sqlite3 statements But I have to access the test.db database in admin panel to search and print the data stored in database How to do this.. thanks -
ModelForm for a manytomanyfield field with extra fields in through
I need to create a Field in ModelForm for a manytomanyfield field with extra fields in through. Can you help me? For example, I have a recipe model with a ManyToManyField related to Malting: models.py class Recipe(models.Model): name = models.CharField(max_length=50) observaciones = models.CharField(max_length=200) litros_finales = models.IntegerField() lavado = models.IntegerField() rendimiento = models.FloatField(null=False) equipment = models.ForeignKey(Equipment, null=True,blank=True,on_delete=models.CASCADE) malts = models.ManyToManyField(Malt, through='Malting') style = models.ForeignKey(Style, null=True,blank=True,on_delete=models.CASCADE) class Malting(models.Model): malt = models.ForeignKey(Malt,on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe,on_delete=models.CASCADE) tiempo = models.TimeField() cantidad = models.FloatField(null=False) And I need to create a form that allows me to relate Recipe and Malteado with the field extra quantity and time. Thanks! Luciano. -
Test Django-Rest custom field
I'm trying to test a custom field that is in an internal shared Python package with no django settings file (as there is not django app). When I run my tests I get the following error. tests/test_fields.py:3: in <module> from rest_framework.validators import ValidationError ../../../.virtualenvs/myenv/lib/python3.6/site-packages/rest_framework/validators.py:14: in <module> from rest_framework.compat import unicode_to_repr ../../../.virtualenvs/myenv/lib/python3.6/site-packages/rest_framework/compat.py:107: in <module> from django.contrib.postgres import fields as postgres_fields ../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/fields/__init__.py:1: in <module> from .array import * # NOQA ../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/fields/array.py:3: in <module> from django.contrib.postgres import lookups ../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/lookups.py:4: in <module> from .search import SearchVector, SearchVectorExact, SearchVectorField ../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/search.py:47: in <module> class SearchVector(SearchVectorCombinable, Func): ../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/postgres/search.py:50: in SearchVector _output_field = SearchVectorField() ../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:172: in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE ../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/conf/__init__.py:56: in __getattr__ self._setup(name) ../../../.virtualenvs/myenv/lib/python3.6/site-packages/django/conf/__init__.py:39: in _setup % (desc, ENVIRONMENT_VARIABLE)) E django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Is there anyway to suppress the need for loading the settings? I'm simply trying to test the logic of the field. class FMIDField(Field): VALID_CHARS = '[a-zA-Z0-9]{8}' default_error_messages = { 'invalid_type': 'FMID must be a string', 'invalid_characters': 'FMID must be 8 characters long and consist only of a-z, A-Z and 0-9' } def is_valid_chars(self, data): prog = re.compile(self.VALID_CHARS) return prog.fullmatch(data) def to_internal_value(self, data): β¦ -
Compiling django filters into a variable and executing it at runtime?
I'm trying to write a search function for my model. A customer has the following fields: cstid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=35) age=models.IntegerField() gender = models.CharField(max_length=10, default='') mobile = models.CharField(max_length=15, default='') email = models.CharField(max_length=50, default='') address = models.CharField(max_length=80, default='') city = models.CharField(max_length=25, default='') My html form will submit the following data by POST via an ajax call to django: var data = { "name": name, "age": age, "email": email, "address": address, "phone": phone, "city": city }; data = $(this).serialize() + "&" + $.param(data); These will be verified in the django view, and a search query performed, as below: def searchpat_for_docwise_appt (request): from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q from django.db.models import CharField from django.db.models.functions import Lower CharField.register_lookup(Lower, "lower") if request.method == 'POST': name = request.POST.get('name') age = request.POST.get('age') # gender = request.POST.get('gender') phone = request.POST.get('phone') email = request.POST.get('email').lower() address = request.POST.get('address') city = request.POST.get('city') if age.isdigit(): ANDSearchResult = customer.objects.filter(name__lower__contains=name.lower(), age=age, mobile__contains=phone, email__lower__contains=email.lower( ), address__lower__contains=address.lower(), city__lower__contains=city.lower()) else: ANDSearchResult = customer.objects.filter(name__lower__contains=name.lower(), mobile__contains=phone, email__lower__contains=email.lower( ), address__lower__contains=address.lower(), city__lower__contains=city.lower()) if len(ANDSearchResult) < 1: errmsg = 'No search results for AND search' print("Error message is <%s>" % errmsg) else: print ("ANDSearchResult is <%s>" % ANDSearchResult) errmsg = '' if age.isdigit(): ORSearchResult = customer.objects.filter( Q(name__lower__contains=name.lower()) β¦ -
Post data from Html5 geolocation Javascript (with Ajax) and data from Django Forms to Django admin backend simultaneously
I would like to combine the data posted from javascript ajax and the django forms, so that the models.py fields are all complete. The javascript retrieves the User's html5 geolocation (latitude and longitude values) and then posts them to models.py. At the same time the User also fills in other information and submits them via a django form. How can I make sure that both the data from html5 geolocation (javascript) and user provided information (django forms) populates the models.py in a single click of the button at a single page that is - create_product.html. I intend to replicate the same function for edit_product.html page too. The first section of the code below involves the data received from django forms. The files are: - models.py - views.py - forms.py - create_product.html - edit_product.html The second section of the code involves latitude and longitude data received from html5 geolocation with javascript and ajax. The files are: - models.py - views.py - urls.py - base.html - script.js - index.html FIRST SECTION models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils.text import slugify class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True, blank=True) description = models.TextField(blank=True) β¦ -
Setting django-allauth to work with Azure as provider
I use django-allauth for my DRF-based app with different providers and I see Azure was listed as a provider but no proper guide on how to set it up. Does anyone has an idea? The list of providers: https://github.com/pennersr/django-allauth/tree/master/allauth/socialaccount/providers -
How to remove input type hidden from html?
I am working with Django forms and html. The text area will create when I put input into that output will come but text box will go off. After getting output also text area should be there forms.py: from django import forms class ReportForm(forms.Form): text = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100})) html: {% extends 'base.html' %} {% block content %} <h1>StopWordsRemoval</h1> <div> <form method = "post" > {% csrf_token %} {{ form.as_p }} <button type="submit">stopwordsremoval</button> </div> <div > <ul> <li>{{ naturallanguageprocessing }}</li> </ul> <a href="{% url 'stopwordsremoval' %}" </a> <style> div { width: 1000px; border: 5px solid green; padding: 10px; margin: 10px; } </style> </div> </div> {% endblock %} In between form as_p and button line input type hidden is created. If we can replace input type text then problem will solve. -
comment form doesn't load when using django-comments-xtd
I am new to both Django and Python and am trying to create my blog.My setup consists of Django 2.0.7 and Python 3.6.5 running on windows 10.I have configured only one app named "personal".In my case the the page loads with "0 Comments Posted" and it doesn't renders the comment form. Below is my code snippet settings.py config INSTALLED_APPS = [ 'personal', 'django.contrib.sites', 'django_comments_xtd', 'django_comments', ] COMMENTS_APP = "django_comments_xtd" COMMENTS_XTD_CONFIRM_EMAIL = True COMMENTS_XTD_SALT = b"es-war-einmal-una-bella-princesa-in-a-beautiful-castle" COMMENTS_XTD_FROM_EMAIL = 'noreply@example.com' COMMENTS_XTD_CONTACT_EMAIL = 'helpdesk@example.com' COMMENTS_XTD_MAX_THREAD_LEVEL = 0 COMMENTS_XTD_THREADED_EMAILS = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'noreply@example.com' EMAIL_HOST_PASSWORD = 'abcd1234' urls.py (urls.py under personal app) urlpatterns = [ ........................ ........................ url(r'^comments/', include('django_comments_xtd.urls')), ] models.py (under personal app) from django.db import models class mycomments(models.Model): mail = models.CharField(max_length = 50) name = models.CharField(max_length = 50) phonenumber = models.IntegerField() class Meta: db_table = "mycomments" views (under personal app) def page1(request): mycomm =Recipiecomments() return render(request, 'personal/blackforestcake.html',locals()) And Finally page_detail.html <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>My Page</title> {% load static %} </head> <body> <div class="fh5co-loader"></div> <div id="page"> {% include 'personal/head.html' %} {% load comments %} {% load comments_xtd %} <div id="fh5co-author"> <div class="container"> <div class="row top-line β¦ -
Applying renaming migration backward in Django raises a programmingError
I'm fairly new at django development, so I hope I'm not missing something too obvious here. On a Django 2.1 project I'm working on, I'm getting the following error when I try to migrate backward : django.db.utils.ProgrammingError: ERROR: the column django_content_type.name does not exists Here is the TraceBack : File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 203, in handle fake_initial=fake_initial, File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/db/migrations/executor.py", line 121, in migrate state = self._migrate_all_backwards(plan, full_plan, fake=fake) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/db/migrations/executor.py", line 196, in _migrate_all_backwards self.unapply_migration(states[migration], migration, fake=fake) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/db/migrations/executor.py", line 262, in unapply_migration state = migration.unapply(state, schema_editor) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/db/migrations/migration.py", line 175, in unapply operation.database_backwards(self.app_label, schema_editor, from_state, to_state) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/db/migrations/operations/special.py", line 196, in database_backwards self.reverse_code(from_state.apps, schema_editor) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/contrib/contenttypes/management/__init__.py", line 42, in rename_backward self._rename(apps, schema_editor, self.new_model, self.old_model) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/contrib/contenttypes/management/__init__.py", line 20, in _rename content_type = ContentType.objects.db_manager(db).get_by_natural_key(self.app_label, old_model) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/contrib/contenttypes/models.py", line 21, in get_by_natural_key ct = self.get(app_label=app_label, model=model) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/jb/.local/share/virtualenvs/cryptonavia-nKl5euKi/lib/python3.6/site-packages/django/db/models/query.py", line 393, in get num β¦ -
How to get property from object returned by a custom templatetag filter without another filter
I'm usign Django-CMS (v3.4.6), Django (v1.11), and Python (v2.7.x). I have a custom templatetag filter called get_foo that takes an my_obj, does some processing and then returns an instance known to have property bar, however when I attempt to do the following, I get an TemplateSyntaxError: Could not parse some characters: my_obj|get_foo|.bar error: {% my_obj|get_foo.bar %} The only workaround I've found is creating another filter which returns bar and so the line in my template looks like this: {% my_obj|get_foo|get_bar %}. But I want to be sure: isn't there a way to do this without creating yet another filter? -
How to override my template instead of django admin panel for reset password?
I am following this blog to reset the user password in django. It is working perfectly. But the problem is that I want to show my template instead of the djnago admin panel when resetting the password or confirming the mail. How can I achieve it? This is my urls.py file url(r'^password_reset/$', password_reset , name='password_reset_reset1'), url(r'^password_reset/done/$', password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', password_reset_complete, name='password_reset_complete'), What step do I need to take for template and views> I have tried many and add some file like: registration/password_reset_form.html registration/password_reset_subject.txt registration/password_reset_email.html registration/password_reset_done.html registration/password_reset_confirm.html registration/password_reset_complete.html But there is no effect> I just want to render my website template while resetting the password. This is my directory structure: βββ backmyitem β βββ __init__.py β βββ __pycache__ β β βββ __init__.cpython-36.pyc β β βββ settings.cpython-36.pyc β β βββ urls.cpython-36.pyc β β βββ wsgi.cpython-36.pyc β βββ settings.py β βββ urls.py β βββ wsgi.py βββ feed β βββ admin.py β βββ apps.py β βββ forms.py β βββ __init__.py β βββ migrations β β βββ 0001_initial.py β β βββ 0002_auto_20180804_1610.py β β βββ 0003_auto_20180805_0533.py β β βββ 0004_claimform.py β β βββ 0005_auto_20180807_1403.py β β βββ 0006_auto_20180807_1840.py β β βββ 0007_auto_20180809_0045.py β β βββ 0008_auto_20180809_0126.py β β βββ 0009_auto_20180809_0140.py β β β¦ -
Call class method or return None
I am struggling with database relationships and Django, but have simplified my case drastically in order to get to the point. I have the following class: class Car(object): owner = 'No owner' def get_owner(self): return self.owner If I do not instantiate Car, but set nissan to None and then call get_owner, I get the following error: nissan = None nissan.get_owner() AttributeError. 'NoneType' object has no attribute 'get_owner' Is it possible to return None when calling nissan.get_owner() if nissan is None? The bigger picture: I am writing a Django templatetag that returns some data based on whether database relationships exist. It would be nice to write such code one one line though. In the end, I just want to get the value from get_owner() or get None. nissan.get_owner() or None Is not working here... -
How to access the Azure AD Groups and user deatils using python?
params = urllib.urlencode({ # Specify values for the following required parameters 'api-version': '1.5', 'tenant_id':'vvvvvvvvXXXXXX', }) headers = { 'Authorization':'TzmMKl1QoxWjvPyX8Xv79ZxvZgoGHwbRt3ZQXwNoFBu42R6yj0o4aMraEVkNkoLyvN8KZjDi4mD7w41gTREsUhbOyg_PsUEv7g4SoTsbRluj8hHrrWuXj8h32MyklOB7ahAKBRLE8KAcmVARdb4vpQ' } try: conn = httplib.HTTPSConnection('graph.windows.net') print("got connection and getting it to actual domain") print(conn) conn.request("GET", "/{tenent_id}/groups?%s" % params, "", headers) response = conn.getresponse() data = response.read() print(data) conn.close() But am getting below error: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond -
Django ORM "." vs "_" when access the id of foreign key
class Author(models.Model): name = models.CharField(max_length=120) class Book(models.Model): name = models.CharField(max_length=20) author= models.ForeignKey(Author) Consider those two models. When I access this foreign key, what's the difference between those two ways: id= Book.objects.get(pk=1).author.id id= Book.objects.get(pk=1).author_id -
Values_list with flat=True still showing brackets
so I have this html code: <legend><h1 > Weapons that this character has </h1></legend> <div> <ul style="list-style-type:none" > {% if request.GET.idChar %} <li >{{ charname }} Has Maihand {{ mh }} and Offhand {{ oh }}</li> {% else %} <li>no</li> {% endif %} </ul> </div> The issue is that {{ charname }}, {{ mh }} and {{ oh }} are still displaying the brackets after i added flat=True in their line in views.py, in fact they stopped showing the parenthesys, but still showing the brackets. I also tried named=True, named=bool, flat=bool. Also tried values instead of values_list... Views.py: def character_weapons (request): idchar = request.GET.get('idChar') weapons = Characterweapons.objects.filter(characterid__exact=idchar).values_list('weaponid','categoryid_id') charname = Characters.objects.filter(characterid__exact = idchar).values_list('name', flat=True) print("charname: ") print(charname) if weapons[0][1] == 1: mh_id = weapons[0][0] oh_id = weapons[1][0] elif weapons[0][1] == 2: oh_id = weapons[0][0] mh_id = weapons[1][0] mh = Weapons.objects.filter(weaponid__exact=mh_id).values_list('weaponname', flat=True) oh = Weapons.objects.filter(weaponid__exact=oh_id).values_list('weaponname', flat=True) context={"mh": mh, "oh": oh,"idchar": idchar,"charname": charname} return render(request,'users/character_weapons.html', context) If someone knows how to fix it please let me know. Thanks in advance! -
Django - Using a Form or ModelForms to update multiple tables?
I am trying to create a one form that when submitted will either create or update a record based on validation of the PK that was submitted. This form will need to interact with at least two models though. So my question would be, Would it be better to create one form and handle the DB interaction in the view or somehow create a ModelForm that will update both tables when submitted? I understand that a modelform can only have one model attached to it. Ex. I have a model called "Item" with fields "name" PK, "description" and "price". Another model called "Requisition" with fields "ID" PK, "item" FK to Item, "signature" How should i go about creating a form that when submitted will take the fields at face value and create a record for the requisition table but also create or update the item table based on the value entered? If i create a modelform on Requisition the FK field displays a dropdown which is not what I want. I want it to be a textfield. Thank you in advance! -
Django : Select value from list with conditions
It makes a long time I've never used Django and I have some issues in order to select values from a table with previous conditions. I will try to simplify my code in order to give you only the essential. I have to make that with Class Based View but for the moment I prefer Function Based View Objective : User going to a new form page Select an Omcl among the list of all OMCL stored in the table Select one document among the list of all documents for the choosen OMCL Could edit the document title and save the new one in the database Database : I have 2 tables in the same database. The first one is Omcl which corresponds to institutes. The second one is OmclDocuments which corresponds to documents assigned to each Omcl. #models.py file from django.db import models class Omcl(models.Model): code = models.CharField(verbose_name=('code'), max_length=20, unique=True) name = models.CharField(verbose_name=('name'), max_length=255) country = models.CharField(verbose_name=("country"), max_length=30) town = models.CharField(verbose_name=('town'), max_length=50) def __str__(self): return self.code + ': ' + self.name class Meta: db_table = 'omcl' verbose_name = ('OMCL') verbose_name_plural = ('OMCL') unique_together = ('code', 'name') ordering = ['code'] class OmclDocuments(models.Model): document_type = models.CharField(verbose_name=('type of document'), max_length=30) title = β¦ -
How to use three urls same with one template.? Django Python
Views.py def cartdata(request): emailid = request.session['emailid'] dressnum = cart_details.objects.raw("select dress_cart_id from project_cart_details where emailid='%s'" % str( emailid)) cartdetails = dress_details.objects.raw("select * from main.project_dress_details where dress_id= '%s'" % dressnum) return render(request, 'project/shop.html', {'cartdetails':cartdetails}) def alldress(request): all_dress = dress_details.objects.order_by('dress_id') return render(request, 'project/shop.html', {'all_dress': all_dress}) def cart(request): emailid = request.session['emailid'] dressid = request.POST.get('dressid') #reg_id = register.objects.raw("SELECT regid FROM main.project_register") reg_id = register.objects.filter(email=emailid).values('regid').distinct() p1=cart_details(emailid=emailid,dressid=dressid,regid=reg_id) p1.save() #cart_details.objects.create(emailid=emailid,dressid=dressid,regid=reg_id) return render(request, "project/index.html") urls.py url(r'^shop.html$', views.alldress, name='alldress'), url(r'^shop.html$', views.cartdata, name='cartdata'), url(r'^shop.html$', views.cart, name='cart'), I want to use three urls in the same shop.html file one for display all dress from database second from cartdata and third for add to cart three are in one only. How can I use it.? -
Bilingual Blog posts in Django
I want to create a blog which will have bilingual posts. What exactly I want to do is :- 1. I want the website primarily in English. 2. When user opens a certain post. It should have an option to switch to other language I.e. Hindi. 3. Basically I want to add a boolean field to the post with name has_translation and somehow link it to its translated version. 4 And in the post view, if it has a translation, I need to provide a button to switch it to translated version. -
Django annotate Count include 0 results
I have this query to do a count of photos taken by month. It's only returning the values where it's not 0. How can I make it so it will show all months, even when it's 0? today = datetime.date.today() 6months = today - datetime.timedelta(6*365/12) qs = Photo.objects.filter(camera__owner=self, timestamp__gte=6months).annotate( month=ExtractMonth('timestamp'), ).values('month').annotate( photos=Count('id') ).order_by('month') -
Using save_model to save the current user
I try to save the current user with creating the new object in the post_save. There is the model class SourceHistory(models.Model): source = models.ForeignKey(Source, verbose_name=u'ΠΡΡΠΎΡΠ½ΠΈΠΊ', null=False, blank=False) editor = models.ForeignKey(User, verbose_name=u'ΠΠΎΠ»ΡΠ·ΠΎΠ²Π°ΡΠ΅Π»Ρ', null=True, blank=True) And in the admin.py @admin.register(SourceHistory) class SourceHistoryAdmin(admin.ModelAdmin): list_display = ('source', 'editor') def save_model(self, request, obj, form, change): obj.editor = request.user obj.save() And the creating a new object @receiver(post_save, sender=Source) def source_save_history(sender, **kwargs): source = kwargs.get('instance') for f in source.memorized_fields: if source.__getattribute__(f) != source.memorized_fields[f]: sh = SourceHistory.objects.create( source=source ) So, using this way the 'editor' field in the new object is empty. How should I create the SourceHistory object with the current user? -
Ignore missing variables in Django templates
How can I make Django (1.11) ignore missing variables in template during rendering? I need to render the same template with different data in multiple steps. Instead of replacing them with an empty string: >>> from django.template import Template, Context, TemplateSyntaxError >>> c = Context({'foo': 'hello'}) >>> t = Template('{{foo}} {{bar}}') >>> t.render(c) 'hello ' I would like it to just leave them as is >>> t.render(c) 'hello {{bar}}' -
django using formset to update multiple instances
I want to update multiple instances at once, after searching I found formset but only came to know how to create multiple instances. I need to update existing instances with one form. for example I have model as class Student(models.Model): ... passed = models.BoolenField(default=False) hostel = models.Foreginkey( ... ) I need to update hostel for all passed students with one form. How to do this ?