Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Switch between data presentation in template of django
Im new to django. I don't know if thing that I ask if available in pure django tempates. I have main page of my application that load data from database. It output information in div which then use bootstrap for better look. In that div I have Image and Title. Is there a way to give user ability to switch between views so they could pick if they like to have div's or for example table with titles only ? I know that ajax-based frameworks had something like that but never used them. Also I would like to preserve data from model while switching view, because I would like to not ask db for data when view is switched. Is it possible? or the only way to do it is make separate template and add route for /view/ so I redirect user to different page with different template and handle viewing as new page (with reloading model) -
cant access admin page with Postgresql database
I am beginner when it comes to Djagno .I am tryng to connect Postgresql database with my new project,i did everything properly in settings module and with migrations but i cannot access my admin page ?? here is screnshot of an eror here is screenshot of url -
Display queryset results by month in template
Id like to group the results of my queryset in a table by month with the month name as a header for each table. I have a model like so: class Tenant(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) telephone = models.CharField(max_length=30) email = models.CharField(max_length=30) contract_end = models.DateField(blank=False) def __str__(self): return u'%s %s' % (self.first_name, self.last_name) View like so: def expired_contracts(request): now = datetime.datetime.now() tenant_queryset = Tenant.objects.all() expired_list = [] for x in range(0, 12): date = now + relativedelta(months=x) expired = tenant_queryset.filter( contract_end__year=date.year, contract_end__month=date.month ) expired_list += expired context = {"expired_list": expired_list} return render(request, "expired_template.html", context) Template: {% for tenant in expired_list %} <table> <tr> <td>{{ tenant.first_name }}</td> <td>{{ tenant.telephone }}</td> <td>{{ tenant.contract_end }}</td> </tr> </table> {% endfor %} I guess I could create a bunch of empty lists and populate them with a loop and if statements, but that seems a little much. Any other way I could go about this? Thanks! -
Django - How to calculate field in property
i want to calculate multiplication of amount and percent field: class Info_data(models.Model): name = models.CharField(blank=True, max_length=100) amount = models.DecimalField(max_digits=5, decimal_places=0) percent = models.ForeignKey(Owner, related_name="percentage") then write this property: def _get_total(self): return self.percent * self.amount total = property(_get_total) and use in template: {% for list_calculated in list_calculateds %} <ul> <li>{{list_calculated.name}}</li> <li>{{list_calculated.total}}</li> </ul> {% endfor %} but return blank. how to use property in template? -
Django reverse URL for app
I am using a third party app (django-sphinxdoc) in my Django project and I would like to be able to link to it in a base.html template so that it is reachable from all pages that are using base.html, but I just can't figure out how to do this. It works just fine with "Home" and "Admin" as defined below. I have tried a number of different variants and with the below I get: Exception Type: NoReverseMatch Exception Value: Reverse for 'doc-list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I have a urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^', include('Myapp.urls', namespace='Myapp')), url(r'^admin/', admin.site.urls), url(r'^docs/', include('sphinxdoc.urls', namespace='Myapp-sphinxdoc'),), ] A Myapp/urls.py: from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.index, name='Myapp-index'), url(r'^(?P<detail_id>[0-9]+)/$', views.detail, name='Myapp-detail'), ] My base.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <div class="box"> <h1>MYAPP</h1> <hr> <a href="{% url 'Myapp:Myapp-index' %}">Home</a> <a href="{% url 'admin:index' %}">Admin</a> <a href="{% url 'Myapp-sphinxdoc:doc-list' %}">Docs</a> <hr> {% block content %}{% endblock %} {% block footer %} <hr> © Copyright 2017, MG {% endblock %} </div> </body> … -
Django session for multiple users
I have set request.session['username']=username if two users are logged in simultaneously then will the request.session['username'] will be overwritten by the username of the user who last logged in? -
use_required_attribute() missing 1 required positional argument: 'initial' django forms
I wrote a dynamic form: class VoteForm(forms.Form): def __init__(self, *args, **kwargs): question = kwargs.pop('instance', None) super().__init__(*args, **kwargs) if question: if question.allow_multiple_votes: choice_field = forms.ModelMultipleChoiceField(queryset=question.choice_set) else: choice_field = forms.ModelChoiceField(queryset=question.choice_set) choice_field.widget = forms.RadioSelect choice_field.label=False choice_field.empty_label=None choice_field.error_messages={'required': _('No choice selected.'), 'invalid': _('Invalid choice selected.')} self.fields['choice'] = choice_field Without the RadioSelect widget every thing seems to work, but with it the following error occurs: TypeError: use_required_attribute() missing 1 required positional argument: 'initial' -
Django error that doesn't make sense
I am currently working on a Django site, and I am trying to get the login system to work. However I keep on having the same issue, where I get the error message No modules named 'users.urls'. However I do have this module in users, so I am not sure what is wrong. There is a fair amount of code, so I won't upload it, but if you need to see anything just ask and I will edit it. Thanks very much, Milo -
Django url change language code
I am trying to change the language of the website when users click a button in Django. I have a base project and the urls are: urlpatterns += i18n_patterns( # Ecommerce is the app where I want to change the language url(r'^', include("ecommerce.urls")), ) The url inside Ecommerce.urls is: urlpatterns = [ url(r'^testing/$', views.test, name='url_testing'), ... other urls ] When I visit the url above, I first go to: http://localhost/en/testing/. I want to set a link <a href="{% url 'url_testing' %}">Change Language</a> so that when users click it, it will change language to http://localhost/zh_hans/testing/. How do I do this in my template? -
Custom Django Authenticate using other Field
This my model from django.contrib.auth.models import User class Pegawai(models.Model) nip = models.CharField(primary_key=True, max_length=255) user = models.ForeignKey(User, ) name = models.CharField(max_length=255) sex = models.CharField(max_length=2, choices=(('L', 'Laki-Laki'),('P', 'Perempuan'),)) default builtin django auth login login_user = authenticate(username=username, password=password) how to custom like this login_user = authenticate(nip=nip, password=password) -
How to custom authentica
This my model to custom auth from django.contrib.auth.models import User class Pegawai(models.Model) nip = models.CharField(primary_key=True, max_length=255) user = models.ForeignKey(User, ) name = models.CharField(max_length=255) sex = models.CharField(max_length=2, choices=(('L', 'Laki-Laki'),('P', 'Perempuan'),)) default builtin django auth login login_user = authenticate(username=username, password=password) how to custom like this login_user = authenticate(nip=nip, password=password) -
could not connect to server:PostgreSQL -Heroku
I deployed a Django app in Heroku. Initially, it was run on SQLite3 database and later I upgraded to PostgreSQL. App is working perfect with local settings but, when I pushed the file to server it doesn't behave as expected. When I login to django admin ( https://my_app_name.herokuapp.com/admin/ ) got an error as below could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Can anyone solve this issue ? Thanks settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } Traceback Environment: Request Method: POST Request URL: https://cyc-new.herokuapp.com/admin/login/?next=/admin/ Django Version: 1.9 Python Version: 2.7.13 Installed Applications: ['rest_framework', 'background_task', 'userApp', 'imageUpload', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/sites.py" in login 407. return login(request, **defaults) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/views.py" in inner 49. return func(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response … -
Trying to use dictionaries in django
I'm developing an application in Django and I have to do the following: A page for a candidate to be evaluated (using form), I created the models correctly, so I went to do the third model, which should relate The candidate, the evaluator (user), the criterion (criterio) and the note (NOTE) that this criterion will receive. I thought of using a variable that received something like 'models.DictField (dictionary), however there is nothing like this in models, so the second thing I thought was a variable (candidato) to receive a ForeignKey with the model' candidate 'and Another receive IntegerField (valor) and then put these variables inside another variable called 'dic' (which would be a dictionary), something like this: models.py from django.db import models from site_.settings import MEDIA_ROOT class Criterio(models.Model): label = models.CharField(max_length=100) def __str__(self): return self.label class Candidato(models.Model): name = models.CharField(max_length=100) e_mail = models.EmailField(max_length=100, default = '') github = models.URLField(default = '') linkedin = models.URLField(max_length=100, default = '') cover_letter = models.TextField(default = '') Ensino_superior = models.BooleanField(default = False) med = models.IntegerField(default = 0) #talvez tenha que alterrar essa linha docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True) def __str__(self): return self.name class Avaliacao(models.Model): candidato = models.ForeignKey(Candidato) criterio = models.ManyToManyField(Criterio, default = '') valor = … -
NoReverseMatch at / Reverse for
problem with Django Help me pls! I NEED TO CAPTURE THE ID and send it by get Reverse for 'listar_esp' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'solicitar/lista/(?P<id_especialidad>\\d+)/$'] html: <a href="{% url "usuario:listar_esp" esp.id %}" method="GET" type="submit" class="btn btn-success pull-right" value="editar" onclick="document.location.reload();"/>Solicitar</a> views.py: def home(request): encargado = Encargado.objects.all() especialidad = Especialidad.objects.all() pedido = Pedido.objects.all() template = "index3.html" return render_to_response(template,locals()) def ArticuloListView(request): user = request.user if user.is_superuser: pedido = Pedido.objects.all() template = 'admindata.html' return render_to_response(template,locals()) else: pedido = Pedido.objects.filter(especialidad=1) template = 'index2.html' return render_to_response(template,locals()) and url: project: url(r'^solicitar/', include(urls, namespace="usuario")), app: url(r'^lista/(?P<id_especialidad>\d+)/$', ArticuloListView, name="listar_esp"), and models.py: class Especialidad(models.Model): nombre = models.CharField(max_length=50, blank=True) encargado = models.ForeignKey('Encargado', blank=True, on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.nombre) class Pedido(models.Model): especialidad = models.ForeignKey('Especialidad') articulo = models.ForeignKey('Articulo') fecha_pedido = models.DateTimeField(auto_now_add=True,null=True, blank=True) cantidad = models.IntegerField(blank=True)blank=True) estado = models.CharField(max_length=20, blank=True, default='pendiente') What is the problem please help me, bless! -
CharField choice list change the behavior
As you can see here below I have model with CharField, where user can choice one of the value inside ROLE_CHOICE. Question: How to make some values unavailable for selection in form but you can see them. Right now I tried next code but it make invisable some values inside ROLE_CHOICES which is not what I want. model.py: ROLE_CHOICES = ( ('manager', 'Manager'), ('developer', 'Developer'), ('business_analyst', 'Business analyst'), ('system_analysts', 'System analysts'), ) class Membership (models.Model): ***OTHER FIELDS*** role = models.CharField(max_length=20, choices=ROLE_CHOICES,) forms.py: class MembershipForm(forms.ModelForm): class Meta: model = Membership fields = '__all__' def __init__(self, *args, **kwargs): super(MembershipForm, self).__init__(*args, **kwargs) self.fields['role'].choices = tuple(choice for choice in ROLE_CHOICES if choice[0] not in ['developer']) -
How to create groups and assign permission during project setup in django?
I know I can create user groups and assign permission to them from the admin area in a django project. I can also create a group and assign permission to it by importing Group and Permission model from django's auth module. What I want to know if there is any way I can create group and assign permission to them when I set up the project. So, if I have types of users, Admin, Developer, Tester and Project Manager. They are basically user groups which would have different permission level. I did not customize the User model and only can differentiate by the groups they are assigned to. So is there a way to create these groups and assign required permission to them like when permissions are created for admin when I run python manage.py migrate? -
Get CSS drowndown menu option name in Django
I am trying to create a drop down menu in CSS and get the selected option's value in Django for processing. How can I accomplish this? I tried my code with a textbox HTML and was able to get data using request.get function but how can I accomplish this using CSS dropdown menu. Sample CSS (W3 schools): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>MyPage</title> </head> <body> <!DOCTYPE html> <html> <head> <style> .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #f1f1f1} .dropdown:hover .dropdown-content { display: block; } .dropdown:hover .dropbtn { background-color: #3e8e41; } </style> </head> <body> <h2>Hoverable Dropdown</h2> <p>Move the mouse over the button to open the dropdown menu.</p> <div class="dropdown"> <button class="dropbtn">Dropdown</button> <div class="dropdown-content"> <a href="someurlwhichhasaviewattached" name="Linke">XXX</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> </body> </body> </html> if user chooses XXX, How can i retrieve it in background? -
How to show all the queryset result in one cell of table with Django
I want to show all the queryset result in one cell of table. Right now,rows in ECMs shows queryset directly as shown in below image. But I want to show each items in queryset in one cell. Could anyone give me any advice how to implement? html file % extends "base.html" %} {% block content %} {% load staticfiles %} <h2>Results comparison </h2> <div class="row"> <h4>annual energy consumption</h4> <svg width="1200" height="400"></svg> </div> <table class="table"> <thead> <tr> <th>Version</th> <th>Diff</th> <th>ECMs</th> <th>Area[m2]</th> <th>EUI[kWh/m2]</th> <th>Unmet hour[h]</th> </tr> </thead> <tbody> {% for project in object_list %} <tr> <td><a href="{% url 'project:detail' project.pk %}">{{project.version}}</a></td> <td>{{project.diff}}</td> <td>{{project.ecms.all}}</td> <td>{{project.area.total_area|floatformat:"0"}}</td> <td>{{project.energy.euipertotal|floatformat:"0"}}</td> <td>{{project.unmet.heating|add:project.unmet.cooling}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} -
Heroku: Django database file lost on every dyno restart
I deployed a Django app on Heroku. I have some models and inserted some data to the database (SQLite database). But, when I tried to access the data after certain time, it showing an empty database. I found a problem similar to my issue here ->django heroku media files 404 error and I understood that, I should keep my Media files somewhwere else. Here my problem is with database and my question is, can I prevent my SQLite database from this data loss ? -
Django-taggit-templatetags2 Attribute Error
I need help using the slug of tags as a link to all posts containing that tag. Using Django-taggit-templatetags2. 'function' object has no attribute 'filter' tags.html <h2>Tags</h2> {% get_taglist as tags %} {% for tag in tags %} <h4><a href="{{tag}}">{{tag}} x{{tag.num_times}}</a></h4> {% endfor %} urls.py url(r'^blog/tags/(?P<slug>[a-z0-9]+)/$', views.TagDetailView.as_view(), name = 'tag'), views.py class TagDetailView(DetailView): template_name = 'home/tag.html' context_object_name = 'tag' def get_queryset(self): return Post.objects.all Traceback: File "/home/vinyasa/web_dev/practice/venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/vinyasa/web_dev/practice/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/vinyasa/web_dev/practice/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vinyasa/web_dev/practice/venv/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/vinyasa/web_dev/practice/venv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/vinyasa/web_dev/practice/venv/lib/python3.5/site-packages/django/views/generic/detail.py" in get 115. self.object = self.get_object() File "/home/vinyasa/web_dev/practice/venv/lib/python3.5/site-packages/django/views/generic/detail.py" in get_object 43. queryset = queryset.filter(**{slug_field: slug}) Exception Type: AttributeError at /blog/tags/mods/ Exception Value: 'function' object has no attribute 'filter' -
Django admin page with custom fields to relations that are not in the Model (just in a JSON)
I have a model in which one of its fields is a postgres.fields.JSONField. The Json that is going to be stored there is a variable dictionary of IDs referencing other items (possible relations/attributes) in the database. Allow me to be more specific: Basically, I'm trying to create a discount system, in which some discounts would apply to certain products. The JSON field contains the constraints to know what products can receive a discount. For instance: If I want to apply a 50% off to all products that fall under the "Beverages" category, and the "Beverages" category has id 5 in the database, the coupon would look like: discount_type='percent' discount='0.5' discount_record={ 'category': [5] } If I wanted to apply a $20 off to all the products in the "Beverages" category AND that are manufactured by, let's say, CocaCola, the filtering dictionary would look like: discount_type='fixed amount' discount='20' discount_record={ 'category': [5], 'manufacturer': [2] # Assuming coca-cola is the Manufacturer # with id==2 in the 'Manufacturers' # table of the database (NOTE: this is # needed since CocaCola manufactures # products besides "Beverages") } If I wanted to apply a 25% off to a particular product (let's say to the product whose id … -
Multilevel foldable content with Jquery in django template
I have a multilevel (unknown depth) content that I want to serve in Django template. I have the variable {{ source }} that's essentially a list of elements. Each element can be simple ({name:xxx, value:yyy}) or a new container ({name:zzz: members: [another list of elements]}) I'm trying to figure out how to write my jquery and my template to achieve foldable content that will show user <div class='header'>{{xxx.name}}</div> <div class='content'>{{xxx.value}}</div> I figured that I need to use recursion in template (like this) so I can loop over and over until I reach the bottom of my variable content. Any suggestions on how to do this? With jQuery I can probably use thing like to allow unfold/fold back: $(".header").click(function(){ $content = $(this).next('content'); $content.toggle(); }); So I can allow user to show hidden div with class "content" as this class is initially set to be display: none with CSS, everywhere on the page. But I'm failing to figure out how to have this nested structure where upon click user unfolds content of what's inside of that level and show only either member values or new sub-member names (in case if content is another list) and new sub-members become new headers (containers) that … -
How to have richtext filter and maintain css styles?
This is based off of the tutorial on the Wagtail website I have this inside of blog_page.html - blog folder <p class="content"> {{ page.body|richtext }} </p> My css class content is referenced in base.html - mysite folder <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> I notice that richtext means that css class content is not applied. What's a good way to solve this while still being able to use html in Wagtail CMS for say, a page/blog post? -
How do I reference a parameter from a second model object inside a DeleteView to pass to my get_success_url?
My question is: how do I reference a parameter from an object other than the model the DeleteView is based on (in this case the <'list_pk'> param) from the List object instance and pass it from my DeleteView to my get_success_url reverse method... In order to successfully render the get_success_url template? My get_success_url is this: url(r'^(?P<username>[a-zA-Z0-0_.-]+)/(?P<list_pk>\d+)/$', views.list_detail, name='listdetail'), My DeleteView url is: url(r'^(?P<username>[a-zA-Z0-0_.-]+)/(?P<list_pk>\d+)/delete_item/(?P<pk>\d+)$', views.DeleteItemView.as_view(), name='deleteitem'), My DeleteView code is the following: class DeleteItemView(LoggedInMixin, DeleteView): model = Item def get_success_url(self): return reverse_lazy( 'lists:listdetail', kwargs = {'username': self.request.user, ??'list_pk': self.request.user.list.id ??}) list_pk is the parameter I need to pass into the success_url. It is from a related but separate List() object. I.e. a List has many Items - an Item has a List. self.request.user passes the username parameter no problem. I have tried many permutations to capture the list_pk parameter to no avail. The current attempt surrounded by ?? ?? is the one that logically makes sense to me, but I get an error saying that the User object has no list attribute. I'm new to class-based views so I'm sure there is an obvious fix for this, but I haven't found it yet. Another of my attempts centered around using get_context_data … -
Multiple Markers on google map using Django
I am trying to place multiple markers on google map by passing a coordinate list in Django. But when a page is rendered no marker is there. Can anybody help me in pointing out what is the problem in my code: Html Code: <script> {{ coordinatelist }} var map; function initMap() { // Constructor creates a new map - only center and zoom are required. map = new google.maps.Map(document.getElementById('map'), { center: {lat: 40, lng:0}, zoom:1, minZoom:1 }); } {% for item in coordinatelist %} var latlongcoordinates = new google.maps.LatLng({{ item.0 }},{{ item.1 }}); var map = new google.maps.Map(document.getElementById("map"), mapOptions); var marker1 = new google.maps.Marker({ position: he, title:"Mymarker"}); marker1.setMap(map); {% endfor %}