Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin - Limit the choices in dropdown
I am now starting to use django and I have an issue trying to filter data based on user information. Let me explain how my app works. A User in my app belongs to a company. So I created a table called Company to capture company info. Then I created another table called UserCompany. Basically, it stores the Id from Django User and the Id from my company table. Now, I want to filter data that the user will see in Django Admin based on their company id. He/She can only see data based on their company Id. I was able to figure this user using get_queryset in admin.py. My only issue now is, the dropdown list that shows in admin as a result of foreign keys isn't being filtered. I did some research and found out about limit_choices_to. I can set that statically like this: class Cleaner(models.Model): company = models.ForeignKey('Company',limit_choices_to = {'companyname' = 'Test'} The dropdown list in admin section only shows the company Test. How can I do this dynamically? Do I do it in the model or do I do it in admin.py? Please help!! -
add icon to particular rows in django template table
I am working on python Django templates in which I have a table having column as id, factor A, factor B, factor C. Values for id, factor A, factor B and factor C respectively are 79, 0.56, 1.1, 1.3. The code for the html template is like this: <table class="table table-bordered"> <thead> <tr> <th class="text-center">id</th> <th class="text-center">Factor A</th> <th class="text-center">Factor B</th> <th class="text-center">Factor C</th> </tr> </thead> <tbody > <tr ng-class="{'info':aggregateData.Mode, 'closed':!aggregateData.Open}"> <td class="text-center">{{aggregateData.id}}</td> <td class="text-center">{{aggregateData.factor_a}}</td> <td class="text-center">{{aggregateData.factor_b}}</td> <td class="text-center">{{aggregateData.factor_c}}</td> </tr> </tbody> </table I want to add a clickable icon to this similar like this for rows having aggregateData.Open true. Can someone suggest a way how I can achieve this. -
add my own class in admin field django-cms
Hi everyone Y create my own app in djando CMS, now I want to add my own class and id's to my field.. y try this, but I don't obtain any successful result. in my model.py I have this class Entry(models.Model): TYPES_CHOICES = ( ('none', 'not specified'), ('s', 'Series'), ('mb', 'Multiples Bar'), ('b', 'Bar suggestion'), ) app_config = AppHookConfigField(HealthConfig) code = models.CharField(blank=True, default='', max_length=250) url_suggestion = models.CharField(blank=True, default='', max_length=250, verbose_name="URL for Suggestion" ) health_placeholder = PlaceholderField('health_info') objects = AppHookConfigManager() def __unicode__(self): return self.url class Meta: verbose_name_plural = 'entries' and now in my form.py I have this from django import forms from .models import Entry class EntryForm(ModelForm): class Meta: model = Entry def __init__(self, *args, **kwargs): super(EntryForm, self).__init__(*args, **kwargs) self.fields['url_suggestion'].widget = TextInput(attrs={ 'id': 'myCustomId', 'class': 'myCustomClass', 'name': 'myCustomName', 'placeholder': 'myCustomPlaceholder'}) self.fields['code'].widget = TextInput(attrs={ 'id': 'code_Icd9', 'class': 'code', 'name': 'myCustomName', 'placeholder': ' code Icd9'}) any idea is I missing something, after that, I do a migrate of the component again. Thanks in advance! -
Error adding a record with a Django model from script
I had a lot of problems tryng to fix a problem in a project I made to learn Django so I decide to make it from scratch AGAIN and go directly for the 'mistake' So, steps: Create a folder named wapi Inside that folder execute virtualenv winenv Activate the virtualenv Install django with pip django-admin startproject subastas python manage.py migrate (then create superuser) Then I run the server and everything works. After that I run python manage.py startapp ah in the folder ah in models.py I write this models from django.db import models import datetime from django.utils import timezone # Create your models here. class Producto(models.Model): nombre = models.CharField(max_length=200, unique=True) id = models.PositiveIntegerField(primary_key=True) umbral = models.PositiveIntegerField(default=0) def __str__(self): return self.nombre class Cotizacion(models.Model): #fecha = models.DateTimeField() minimo = models.FloatField() maximo = models.FloatField() promedio = models.FloatField() cantidad = models.PositiveIntegerField() Producto = models.ForeignKey(Producto) def __str__(self): return self.Producto.nombre Then I register those in the folder /ah/admin.py as:} from django.contrib import admin from ah.models import Producto, Cotizacion # Register your models here. admin.site.register(Producto) admin.site.register(Cotizacion) in the folder /subastas/ I register in settings.py the app in installed apps I run again the migrate command and runserver and I can see everything running, I even add a … -
Can't import django app inside django project
I want to import my app's views inside the URLs config of a django project, I've tried multiple solutions I found online but with no luck. When I run the django server, I'm greeted with an ImportError exception and the error only shows up when I add the import to my app outside the app's directory e.g the project. ImportError 'myapp' And yes, the app is inside the django's project Installed_Apps list INSTALLED_APPS = [ 'myapp.apps.MyappConfig', ] -
How can I create a simple popup for the purposes of giving instructions for my app?
I've been searching for a while but I still haven't found really what I need. I've written a Django app and I want a small dialog box to pop up on each page of my app to provide simple instructions for a new user. I'm not really familiar in javascript, so the simpler the better. -
Django template - Create a cron job to wish an happy birthday
I've created a template in Django which has as function to wish a happy birthday to a client. I'd like to set that message in such a way it'd be send to the client every year for his birthday. I think the best way to do this is to create a cron job. However, I am not familiar with cron jobs, and I would like your help. I've created an attribute birthday_date that will give us the birthday date as day month. Here's what I've done so far : #!/bin/bash MANAGE="../venv/bin/python ../manage.py" Could anyone be able to tell me how could I do this? -
Seam Conversation in Django
I have to implement JBoss Seam Conversation mechanism using Django, but I am new to Django and I don't really know how should I do this. I have working empty template in Django now. Would you help me to take some first steps? -
how to disply django form object in javascript
my problem is whene i click in my tr i display a choicefield whith ({{formFacture.description_article}}) bu it dont work whene i do td.innerHTML = "test" its work. sorry english its not my current language here is my html cod <tbody class="table-article-tbody" id="table_article_tbody"> {% for ligne in liste_article %} <tr id="{{ ligne.ref_article }}"> <td>{{ ligne.descripton_article }}</td> <td>{{ ligne.compte_article }}</td> </tr> {% endfor %} <tr> <td>{{ formFacture.description_article }}</td> <td>{{ formFacture.compte_article }}</td> </tr> </tbody> javascript code <script> $('#table_article tr').on('click', function(event){ event.preventDefault(); if($(this).attr('id') != undefined){ var $this = $(this); $.ajax({ type: 'GET', url : "{% url 'updateligneFacture_tem' %}", data: $("#form_facture").serialize(), success : function(data){ $('#contenue_fact').html(data); $('#table_article tr:last').remove(); var row = $this.attr('id'); var tr = document.getElementById(row); var td = tr.insertCell(0); td.innerHTML = "{{ formFacture.description_article }}"; alert(tr); $('.selectpicker').selectpicker(); }, error : function(){ alert("Erreur update !!"); } }); } }); </script> <tbody class="table-article-tbody" id="table_article_tbody"> {% for ligne in liste_article %} <tr id="{{ ligne.ref_article }}"> <td>{{ ligne.descripton_article }}</td> <td>{{ ligne.compte_article }}</td> </tr> {% endfor %} <tr> <td>{{ formFacture.description_article }}</td> <td>{{ formFacture.compte_article }}</td> </tr> </tbody> -
Using non-Django view in Django code
How to make a Django view based on a function outputting a page together with headers, like the following example function? def f(): print("Content-Type: text/plain\n\nExample.") The best idea I've come up with is to redirect to a string, parse text of the output and recreate the response in Django format. Are there better ways? -
Which languages are supported by django as part I18N, Localization
I'm trying to do Internationalization using Django. I've followed through docs and able to set it up right. My questions here are i) What are all the language supported by django? ii) I've created '.po', '.mo' message files for the languages 'de' , 'de-at' but when trying to access those resources from API I'm only able to get resources from 'de' for both the cases. Does Django overrides 'de-at' by 'de' message file resources. Why is it so? I've created message files using below commands by executing in project directory. django-admin.py makemessages -l de After running above command. I've added resources for both the languages corresponding in their '.po' file django-admin.py compilemessages Any help would be appreciated. -
unknown wsgi error when hosting django application
Okay, so I am trying to deploy my django application on an ubuntu 16.04 sever woth apache2 and I am getting an odd error message I can't quite figure out. I have searched around and it seems that the general answer is that I am not using the correct version of libapache2-mod-wsgi for the python version I have. But I am using python version 2.7 and I have tried uninstalling and reinstalling libapache2-mod-wsgi and I am still getting the same error: [Thu Jan 26 15:49:00.419003 2017] [wsgi:error] [pid 2284:tid 140281335461632] [remote 129.22.1.13:43461] mod_wsgi (pid=2284): Target WSGI script '/var/www/provcare.case.edu/public_html/ProvCaRe/ProvCaRe/wsgi.py' cannot be loaded as Python module. [Thu Jan 26 15:49:00.419037 2017] [wsgi:error] [pid 2284:tid 140281335461632] [remote 129.22.1.13:43461] mod_wsgi (pid=2284): Exception occurred processing WSGI script '/var/www/provcare.case.edu/public_html/ProvCaRe/ProvCaRe/wsgi.py'. [Thu Jan 26 15:49:00.419063 2017] [wsgi:error] [pid 2284:tid 140281335461632] [remote 129.22.1.13:43461] Traceback (most recent call last): [Thu Jan 26 15:49:00.419084 2017] [wsgi:error] [pid 2284:tid 140281335461632] [remote 129.22.1.13:43461] File "/var/www/provcare.case.edu/public_html/ProvCaRe/ProvCaRe/wsgi.py", line 17, in <module> [Thu Jan 26 15:49:00.419142 2017] [wsgi:error] [pid 2284:tid 140281335461632] [remote 129.22.1.13:43461] application = get_wsgi_application() [Thu Jan 26 15:49:00.419159 2017] [wsgi:error] [pid 2284:tid 140281335461632] [remote 129.22.1.13:43461] File "/var/www/provcare.case.edu/public_html/ProvCaRe/prov_env/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Thu Jan 26 15:49:00.419200 2017] [wsgi:error] [pid 2284:tid 140281335461632] [remote 129.22.1.13:43461] django.setup(set_prefix=False) [Thu … -
Django: Converting a GenericForeignKey Relationship to a ForeignKey Relationship
I'm working to remove an existing GenericForeignKey relationship from some models. Id like to change it to the Reformatted Model below. Does migrations provide a way to convert the existing content_type and object_ids to the respective new ForeignKey's? (to keep existing data). Basically brand new at programming, so pardon me if I'm asking a stupid question. class Donation(models.Model): amount_id = models.CharField(max_length=12, unique=True, editable=False) date_issued=models.DateField(auto_now_add=True) description=models.TextField(blank=True, null=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type','object_id') class Individual(BaseModel): first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50) suffix = models.CharField(max_length=50, blank=True, null=True) contributor = generic.GenericRelation(Donation, related_query_name='individual') class Organization(models.Model): name = models.CharField(max_length=100) contributor = generic.GenericRelation(Donation, related_query_name='organization') Reformatted Model class Donation(models.Model): amount_id = models.CharField(max_length=12, unique=True, editable=False) date_issued=models.DateField(auto_now_add=True) description=models.TextField(blank=True, null=True) contributor_group = models.ForeignKey(Organization, null=True, blank=True, on_delete=models.CASCADE) contributor_individual = models.ForeignKey(Individual, null=True, blank=True, on_delete=models -
Django as API + ReactJS - Redux: POST request with CSRF token but still response CSRF Token not set
After looking around I wanted to be sure that I'm doing it right but I start doubting and worst: I'm running out of options / ideas. So I'm using django as an API like (I do only get request for some assets) except for one POST method within a base class view to allow my user to download files. The problem is that django expect a CSRF token on my POST. So, here is what I do from my reactjs: export function sendData(endpoint, req, data) { return dispatch => { dispatch(requestData(data)); let csrfToken = Cookies.get('csrftoken'); return fetch(endpoint, { method: req, headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken, }, body: JSON.stringify(data), }) .then(checkStatus) .then(reponse => { console.log("Success!"); }).catch(err => { err.response.json().then((json) =>{ let { Errors, Result } = json; console.log('request failed: ', Errors, " ", Result); }); }); }; }; As you can see, I'm using the 'whatwg-fetch' library. I've tried to replace the X-CSRFToken by X-CSRF-Token but the request is blocked to the chrome "option" and doesn't seem to be properly sent: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response. But I still get the error I've been reading about everywhere: CSRF verification failed. Request aborted. Reason … -
What is the difference in use or inherit from APIView and Model ViewSet
I would meet the difference with respect to when use APIView and when use ModelViewSet when I want serialize my models with respect to get a list of their objects/records? For example, in the APIView documentation we have that with the ListUser class and their get method we can get the list of users class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser,) def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames) I have been get this same list of users using ModelViewSet of this way: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', ) How to can I identify when should I use APIView or ModelViewSet for this task? -
Django InlineModelAdmin gives error 'MediaDefiningClass' object is not iterable
From models.py class Indicator(models.Model): name = models.CharField(max_length=50) youtube = models.CharField(max_length=LONG_BLOG_POST_CHAR_LEN) description = models.CharField(max_length=LONG_BLOG_POST_CHAR_LEN) recommendation = models.CharField(max_length=LONG_BLOG_POST_CHAR_LEN) isPublic = models.BooleanField(default=False) methods_path = models.CharField(max_length=100,default=None) meta_description = models.CharField(max_length=150,default='') image_path = models.CharField(max_length=100,blank=True) def __str__(self): return self.name class IndicatorParameterInt(models.Model): name = models.CharField(max_length=50) value = models.IntegerField(default=1) indicator_int_parameter = models.ForeignKey(Indicator, on_delete=models.CASCADE) hidden = models.BooleanField(default=False) class IndicatorParameterFloat(models.Model): name = models.CharField(max_length=50) setting = models.FloatField(default=1) indicator_float_parameter = models.ForeignKey(Indicator, on_delete=models.CASCADE) hidden = models.BooleanField(default=False) class Comparison(models.Model): name = models.CharField(max_length=100) From admin.py from django.contrib import admin from .models import * # Register your models here. admin.site.register( MarketData ) admin.site.register( Indicator ) admin.site.register( UserProfile ) class IndicatorParameterIntInline(admin.TabularInline): model = IndicatorParameterInt fk_name = "indicator_int_parameter" class IndicatorParameterFloatInline(admin.TabularInline): model = IndicatorParameterFloat fk_name = "indicator_float_parameter" class ComparisonInline(admin.TabularInline): model = Comparison fk_name = "Comparison" class IndicatorInline(admin.ModelAdmin): inlines = [ IndicatorParameterIntInline, IndicatorParameterFloatInline, ComparisonInline, ] admin.site.unregister( Indicator ) admin.site.register( IndicatorInline ) The error TypeError: 'MediaDefiningClass' object is not iterable comes up on the final line of admin: admin.site.register( IndicatorInline ). It doesn't matter if I try to register IndicatorInline first or any of the foreign key classes. I referenced this post, which encouraged using the fk_name attribute. The error occurs regardless of whether or not I use fk_name. -
Estimate User's uptime
It is very important for me to monitor my users. In specific, I am interested to know how long time they are logged in to the site. So I want to estimate, for each user, the uptime %, that means: My first approach then, was to calculate these two values. I already have in the database the historical online time for each user, but I can't figure out how to get the historical online time of the server. I was thinking in adding a constant to the database and auto update it when the server is running but I am not sure how to this. Note that the server is not always running so I can't just save an initial datetime to get its historical online time. Maybe there is a different way to estimate the uptime % that doesn't require to calculate these two values, so if you have any alternative solution, I would be glad to hear it also. -
How to solve IntegrityError in Django rest framework?
I got an IntegrityError while doing django rest framework like this.. IntegrityError at /snippets/ NOT NULL constraint failed: snippets_snippet.owner_id Views.py from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework import generics from django.contrib.auth.models import User from snippets.serializers import UserSerializer from rest_framework import permissions from snippets.permissions import IsOwnerOrReadOnly class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(owner=self.request.user) class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly,) class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer Urls.py from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from snippets import views from django.conf.urls import include urlpatterns = [ url(r'^snippets/$', views.SnippetList.as_view()), url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()), url(r'^users/$', views.UserList.as_view()), url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns += [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) … -
Django Static and Media storage with S3 using boto
I am trying to configure the static file and media locations using boto and S3. I am able to load static files into the root of the bucket, but when I try and define separate subfolders I run into an error. Basically I want the bucket to have this folder structure: Bucket +-static | \--STATICFILES +-media \--MEDIAFILES I am using a "s3utils.py" file as described here s3utils.py from __future__ import absolute_import from storages.backends.s3boto import S3BotoStorage StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static') MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media') settings.prod AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_ACCESS_KEY = os.getenv('AWS_ACCESS_KEY') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') S3_URL = '{s3name}.s3.amazonaws.com'.format(s3name=AWS_STORAGE_BUCKET_NAME) STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 's3utils.StaticRootS3BotoStorage' STATIC_URL = "https://{url}/{folder}/".format(url=S3_URL, folder=STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://{url}/{folder}/".format(url=S3_URL, folder=MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 's3utils.MediaRootS3BotoStorage' Error 2017-01-26T15:26:20.160773+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/urls/static.py", line 24, in static 2017-01-26T15:26:20.160973+00:00 app[web.1]: raise ImproperlyConfigured("Empty static prefix not permitted") 2017-01-26T15:26:20.160991+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Empty static prefix not permitted I think its trying to load the storage module twice, but I have been banging my head against this for a little while so I might be way off. -
Django test not actualizing object
I have a django rest framework test, it is just a wrapper over regular django tests that works exactly the same way. The code looks like this: user_created = User.objects.create_user(first_name="Wally", username="farseer@gmail.com", password="1234", email="farseer@gmail.com") client_created = Client.objects.create(user=user_created, cart=cart) data_client_profile["user"]["first_name"] = "Apoc" response = self.client.put(reverse("misuper:client_profile"), data_client_profile, format="json") client_created.refresh_from_db() # Tried this too self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(client_created.user.first_name, data_client_profile["user"]["first_name"]) So, I want to update the client_created object with some data in the dict data_client_profile, then assertEqual that the client.user.first_name is "Apoc". Here is the code in the view, I added two pdb.set_trace() that will help more than just pasting all the code: pdb.set_trace() client_existing_user_obj.phone = phone client_existing_user_obj.user.email = email client_existing_user_obj.user.first_name = first_name # Updating here! client_existing_user_obj.user.last_name = last_name client_existing_user_obj.user.save() client_existing_user_obj.save() pdb.set_trace() The first pdb break shows this: (Pdb) client_existing_user_obj.user.username u'farseer@gmail.com' # Make sure I'm updating the created object (Pdb) client_existing_user_obj.user.first_name u'Wally' # First name is not updated yet The second pdb break shows this: (Pdb) client_existing_user_obj.user.first_name u'Apoc' # Looks like the first name has being updated! But, when the test runs I get the error: self.assertEqual(client_created.user.first_name, data_client_profile["user"]["first_name"]) AssertionError: 'Wally' != 'Apoc' Why does it fail? I even call refresh_from_db(). I confirm it has being updated in the view, but then in the test it looks … -
Django, where's prefetched GenericForeignKey?
qs = Foo.objects.prefetch_related('items', 'content_object') I can see qs[0]._prefetched_objects_cache contains 'items' (which is reverse lookup of foreign key) But there's no 'content_object' in the _prefetched_objects_cache. Although doc says prefetch_related works with GenericForeignKey. (https://docs.djangoproject.com/en/1.9/ref/models/querysets/#prefetch-related) So where is the prefetched content_object stored? -
Django ModalForm show validation error on bootstrap Modal form
I couldn't show django validation errors on my bootstrap modal form. I need to set client_phone field on the form was no less than 13 characters, if not - show error and highlight the field. Django - 1.10, Bootstrap 3 Here is the code: Model: class Order(models.Model): order_date = models.DateTimeField(auto_now_add=True, blank=True) client_phone = models.CharField(max_length=18) client_email = models.EmailField(max_length=50) then ModelForm: class OfferForm(ModelForm): class Meta: model = Order fields = ['client_phone', 'client_email'] widgets = { 'client_phone': TextInput(attrs={'class': 'form-control bfh-phone', 'data-country': 'UA', }), } labels = { 'client_phone': _('Контактный номер'), } Template with the bootstrap Modal form: <div class="modal fade" id="offerModalForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <form role="form" action="ordercomplete" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <div class="modal-footer"> <button type="submit" id="offerSubmitBtn" class="btn btn-primary" type="submit"> Оформить заказ </button> <button type="button" class="btn btn-primary" data-dismiss="modal"> Закрыть </button> </div> </form> </div> </div> </div> </div> -
using django cities light in template
I have installed Django city light. Now I want to populate my city field in registration form with all the cities in django city light. All the documents doesn't provide any guidance on how to do that. My model is : class UserProfile(models.Model): user = models.OneToOneField(User) email = models.CharField(max_length=255, blank=True) gender = models.CharField(max_length=16, blank=True) location = models.CharField(max_length=255, blank=True) i want to populate all the cities in location field and if possible with auto complete functionality. -
pass queryset and retrieve in template
Hate to ask such a simple question (I spent hours trying to solve it). I watched tons of tutorials and posts (also on this site) all explain the same thing but I can't access my data on the template. views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.views.generic import ListView, DetailView from .models import YTLink def ytlinks(request): queryset = YTLink.objects.all() return render(request, 'links/home.html', {'queryset':queryset}, content_type='application/xhtml+xml') home.html {% extends "links/header.html" %} {% block content %} {% if queryset %} queryset is filled {% else %} queryset is not filled {% endif %} <br> <br> <br> {% for ytlink in queryset %} <a href="{{ ytlink.link }}">{{ ytlink.link }}></a><br> {% endfor %} My queryset is never filled. What is wrong with this code? -
How do I @import a Google font in Django CSS?
I'm trying to do the following in my Django CSS: @import url('https://fonts.googleapis.com/css?family=Lora|Montserrat'); The issue is, Django is converting the url to my STATIC_URL, and expecting the font to reside locally at /path/to/static/fonts.googleapis.com/css. What do I need to do to successfully import an external font like this in my Django CSS?