Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python/django/wagtail/puput/hallo/non-responsive_images_under_Bootstrap3.rant
I am part editor and part developer and not utterly advanced at either career. But I am carrying out only a small-scale project. I'm thinking that in the blog that I recently added to my Django site (as yet only on the development server), with Wagtail and Puput, I might want to upload, say, two ~50KB images per week for five years, after which I'll be doing something else. There will never be a huge number of readers or a need for vast storage. Those being the circumstances, I specifically want to know if what I'm doing to overcome the problems that I encountered with uploaded images not resizing to small screens in the Puput blog, non-responsive design, looks feasible. Or, did I make some stupid mistake and, say, just use the Puput/Wagtail editor incorrectly? When you click into the "body" textbox in the Puput editor to insert an image, it's quite simple. You just browse for your file, give the image a name, and select whether you want full-width or aligned on the left or right. And upon doing that your image will be uploaded into your previously established "media" folder and the database will simply be updated to … -
when i upgrade django-debug-toolbar at 1.6 is does not working
Hi I'm create study project using django==1.9.7 when I use django-debug-toolbar==1.4, i works find and I upgrade 1.4 => django-debug-toolbar==1.6, and restart runserver, I doesn't woking.. my django-debug-toolbar setting is settings.py INSTALLED_APPS = [ # ... # 'debug_toolbar', # ...# ] MIDDLEWARE_CLASSES = [ #...#, 'debug_toolbar.middleware.DebugToolbarMiddleware', ] STATIC_URL = '/static/' DEBUG = True(of course!) when I settings these three parts, 1.4versions works find, but when I upgrade 1.6(and settings no change) it does not working, So, I see document document Support for automatic setup has been removed as it was frequently problematic. Installation now requires explicit setup. The DEBUG_TOOLBAR_PATCH_SETTINGS setting has also been removed as it is now unused. See the installation documentation for details. It seems automatic setup has been removed I see Install ducoment(stable version) but I can't find what is different with Install document(1.4 versions) I needs some advise. thank you -
relation "social_auth_usersocialauth" does not exist. Migrate does not create these tables
I am using python-social-auth. But when I run makemigrations and migrate. The tables "social_auth-*" are not created. My settings.py looks like this INSTALLED_APPS += ( 'social.apps.django_app.default', ) AUTHENTICATION_BACKENDS += ( 'social.backends.facebook.FacebookOAuth2', 'social.backends.google.GoogleOAuth2', 'social.backends.twitter.TwitterOAuth', ) SOCIAL_AUTH_USER_MODEL = AUTH_USER_MODEL # Rausnehmen wenns Probleme mit der Auth. gibt SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.social_auth.associate_by_email', # <--- enable this one. to match users per email adress 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', ) from sharadar.soc_auth_config import * The same does work on another machine without any flaw. But on a new Computer I allways receive Exception Value: relation "social_auth_usersocialauth" does not exist LINE 1: ...er"."bio", "myauth_shruser"."email_verified" FROM "social_au... When using google auth in my running django app Any help is appretiated. Kind regards Michael -
Django query multiple summed values
I have two tables: Ticket Table id paid_with_tax location 1 5 A 2 6 B 3 7 B TicketAdjustment Table id ticket_id value_with_tax 1 1 2 2 1 1 3 1 2 4 1 3 5 2 5 The query I use: Ticket.objects.all().annotate( paid_amount=Sum( F('paid_with_tax') + Coalesce(F('ticketadjustment__value_with_tax'), 0) ) ).values( 'paid_amount', 'location' ).annotate( Count('id) ) the query would return the following: [ { id__count: 6, paid_amount__sum: 28, location: A }, { id__count: 2, paid_amount__sum: 18, location: B }, ] but the above is incorrect since the Ticket Table id=1 values are duplicated by the TicketAdjustment Table values. how can i get the query to sum the TicketAdjustment Table values before adding them up and return the following: [ { id__count: 1, paid_amount__sum: 13, location: A }, { id__count: 2, paid_amount__sum: 18, location: B }, ] -
How to understand Django templates?
Here is official Django tutorial, templates section: First, create a directory called templates in your polls directory. Django will look for templates in there. Within the templates directory you have just created, create another directory called polls, and within that create a file called index.html. In other words, your template should be at polls/templates/polls/index.html. Because of how the app_directories template loader works as described above, you can refer to this template within Django simply as polls/index.html. ...and explanation of "namespacing": Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another polls subdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself. but different app has different absolute path of templates directory. Is there any problems with such project structure? my_project | +--first_app … -
Django greedy characters missing in reverse urls
I am trying to use the following rule to map urls in django url(r'^(?P<permalink>[a-zA-Z0-9_-]*)/?$', views.page, name='page'), This should match pages like site.com site.com/super-awesome-page/ This works however the reverse urls provided by the url template tag are missing the trailing / i.e. "site.com/page" these do get captured pattern but I want my links to show up in my page correctly how can I get this to work correctly. I would have expected since the trailing slash is greedy it should be included in the reverse url. -
I can't get my leaflet popup to show the data I want
I'm trying to display two fields from my model in a popup. (The name and photo). I can only get one field to display or nothing. I can't figures out how to make it work. If anyone can point in the right direction, I would be happy. Attempt #1 This was my starting point, this will only display name or photo or whatever I append to layer.bindPopup(feature.properties.whatever); but only one. models.py from django.contrib.gis.db import models class Marker(models.Model): name = models.CharField(max_length=250) photo = models.ImageField(blank=True) geom = models.PointField(blank=True, null=True, verbose_name='marker') def __str__(self): return self.name map/views.py from django.core.serializers import serialize from django.http import HttpResponse from django.views.generic import TemplateView from map.models import Marker def marker_view(request): markers_as_geojson = serialize('geojson', Marker.objects.all()) return HttpResponse(markers_as_geojson, content_type='json') class MapView(TemplateView): template_name = 'map/map.html' map/urls.py from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from django.contrib import admin from map import views from map.views import MapView urlpatterns = [ url(r'^$', MapView.as_view()), url(r'^map.data/', views.marker_view, name='markers'), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) map/map.html {% load staticfiles %} {% load static %} <!DOCTYPE html> {% load leaflet_tags %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Map</title> {% leaflet_js %} {% leaflet_css %} <link rel="stylesheet" href="{% static 'css/map.css' %}"> <script src="{% static 'js/leaflet.ajax.min.js' %}"></script> … -
Can i exclude the gunicorn cProfiling output?
I am running cProfile with gunicorn and i receive two ouputs - One of my program and the other of the gunicorn. Is there any ways i can exclude the gunicorn output? When i try to save the results into a file (using the -o with cProfile). Only the gunicorn output gets saved. Is there anyways to save both or to exclude the last one? -
how to remove NOT NULL constraint failed in django rest framework
I am trying to make a Post Request for adding a Hotel but i am getting this error NOT NULL constraint failed: hotels_hotel.location_id. how ever my form data include location id form data name: my hotel location:1 #id of location object discription:some discription bla bla if i remove the StringRelatedField from the hotelSerializer then objects get saved into database. 1)My goals is not to create a Location object but to refer it from Hotel Object 2)do i am getting this error because StringRelatedField is read only?then What is Alternate? models class Location(models.Model): country = models.CharField(max_length=60) city = models.CharField(max_length=60,db_index=True) zipcode = models.CharField(max_length=10 class Hotel(models.Model): name =models.CharField(max_length=200,db_index=True) discription = models.TextField(blank=True,null=True) location = models.ForeignKey(Location,related_name='hotels') serializer class HotelSerializer(serializers.ModelSerializer): location=serializers.StringRelatedField() #this line Cause Problem class Meta: model = Hotel fields= ('id','name','discription','location',) -
Django filter if an optional key in json exists
I have a model X with a custom json fied data which may or may not have these keys: key1, key2, key3. I need a way to filter all instances with key1. I have tried doing this: queryset = X.objects.all() queryset = queryset.annotate( has_key1=( Case( When(~Q(data__key1__in=[None, '']), then=True), default=False, output_field=models.BooleanField()) ) ) But queryset.filter(has_key1=True) returns nothing yet there are some records with key1. A direct filter: queryset.filter(data__key1__in=[1]) works okay. Anyone with a solution to this? Thank you. -
Testing abstract model with ForeignKey to another app in django test framework
I want to test an abstract model that has a ForeignKey to a model defined in another app: from otherapp.models import Person class ModelMaster(models.Model): slave = models.ForeignKey(Person) class Meta: abstract = True The problems arises when I just define a model inheriting from ModelMaster in tests.py: from .models import ModelMaster class Master(ModelMaster): pass The python manage.py test breaks with the following error: django.db.utils.ProgrammingError: relation "otherapp_person" does not exist But when I define the Person model in the same app as the ModelMaster, there is no error. Is there a way to make it working, so that model from another app referenced in an abstract model is properly recognised during the test? -
Django, deploying on Azure (IIS) django.core.wsgi.get_wsgi_application() could not be imported
i'm trying to deploy django on my azure web App and have followed some tutorials regarding this matters.The problem is that i always get "The page cannot be displayed because an internal server error has occurred." page instead. After checking on kudu and log files here's what i get: here is my web.config file <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\Python27\python.exe|D:\Python27\Scripts\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> </system.webServer> <appSettings> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="PYTHONPATH" value="D:\home\site\wwwroot;D:\home\site\wwwroot\testbenda2" /> <add key="DJANGO_SETTINGS_MODULE" value="cpcapung.settings" /> </appSettings> </configuration> i've checked and make sure that the project runs fine on localhost, it even runs fine on travis, the only problem seems to be when i deploy it to azure with an ISS based sever. Thank you for your help! -
django-tables 2 M2M field not shown
I am trying to show a M2M field in a django-table2 as seen in Django-tables2: How to use accessor to bring in foreign columns? and Accessing related models with django-tables2 Using: foreigncolumn = tables.Column(accessor='foreignmodel.foreigncolumnname'), I only see a '--'... # The models: class Organism(models.Model): species_name = models.CharField(max_length=200) strain_name = models.CharField(max_length=200) eukaryotic = models.BooleanField(default=True) lipids = models.ManyToManyField('Lipid',blank=True) class Lipid(models.Model): lm_id = models.CharField(max_length=100) common_name = models.CharField(max_length=100,blank=True) category = models.CharField(max_length=100,blank=True) #The tables class OrganismTable(tables.Table): name = tables.LinkColumn('catalog:organism-detail', text=lambda record: record.species_name, args=[A('pk')]) lp = tables.Column(accessor='Lipid.common_name') class Meta: model = Organism sequence = ['name','lp'] exclude = ['id','species_name'] Any idea what I'm doing wrong? -
Download a text/csv file from django app that populates HTML table from a database query
I currently have a django app which I can search to query my database which populates a html table from a query. My app_home.html looks like this: {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>RESULTS APP</title> </head> <form method="get" action="results/"> <div class="SearchBar"><input type="text" name="lab_number"></div> <input class='input_button' type='submit'> </form> <body></body> </html> This is my views.py: def from_samrun(request): if request.GET: lab_query = request.GET['lab_number'] var_list = VarSamRun.objects.filter(sample=lab_query) if var_list: return render(request, 'results/varlist.html', {'var_list': var_list}) else: return render(request, 'results/varlist.html', {'query': [sam_query]}) else: return render(request, 'results/varlist.html' {'error': 'Error'}) which takes me to my varlist.html template: {% load staticfiles %} <!DOCTYPE html> <html> <head><title>Results page</title></head> <body> <div> {% if var_list %} {% for v in var_list %} <tr> <td class='varsrow' width='100'>{{v.sample}}</td> <td class='varsrow' width='100'>{{v.gene}}</td> <td class='varsrow' width='200'>{{v.variant}}</td> <td class='varsrow' width='150'>{{v.cds}}</td> <td class='varsrow' width='150'>{{v.protein}}</td> <td class='varsrow' width='200'>{{v.consequence}}</td> <td class='varsrow' width='200'>{{v.run}}</td> <td class='varsrow' width='300'>{{v.annotation}}</td> </tr> {% endfor %} {% elif query %} <h5>Search using: " {% for q in query %} {{q}} {% endfor %} " did not return any results</h5> {% else %} <h5>{{annotation}}</h5> {% endif %} </table> </div> </body> </html> my urls are: urlpatterns = [ url(r'^results/$', views.results_app, name='results_app'), url(r'results/varlist/$', views.from_samrun, name='from_samrun'), I want to have a download button on my varlist.html page so that … -
How to add placeholder text to search box in Django Admin?
I have a bunch of instances of ModelAdmin defined in admin.py file and many of them use the search_fields parameter. However, they all don't use the same variables to search by, and so I'm wondering what might be the most Pythonic/easiest way to add some placeholder text to the input to make it clear to the system admins what they're searching by. I'm using Django 1.10. Thanks! -
Django template for loop implicit string cast
I am facing a wierd issue with django's built-in template engine. In a seperate function I am generating a list of Model classes based of one common abstract base model. This list of classes is added to the context of a template. By printing this list I can confirm that it is applied correctly to the context. But as soon as I try to iterate over this list I got empty string variables instead of classes. For debugging purposes I wrote a custom filter: @register.filter(name='console') def print_console(item,arg=None): if arg: item = item[int(arg)] print("Type:",type(item)) pp = pprint.PrettyPrinter(indent=4) print("Value:") pp.pprint(item) return item The template snippet causing the error: {% block modal_content %} <ul class="list-group"> {{form_documents|console}} {{form_documents|console:"0"}} {% for el in form_documents %} {{el|console}} <li class="list-group-item">{{el|verbose_name}}</li> {% endfor %} </ul> {% endblock %} Running the corresponding test results in following output: ... Type: <class 'list'> // form_documents|console Value: [ <class 'my_app.models.A'>, <class 'my_app.models.B'>, <class 'my_app.models.C'>, <class 'my_app.models.D'>, <class 'my_app.models.E'>, <class 'my_app.models.F'>] Type: <class 'django.db.models.base.ModelBase'> // form_documents|console:"0" Value: <class 'my_app.models.A'> Type: <class 'str'> // el|console Value: '' ... At this point I can't figure out what's going on. It seems that an implicit cast of class to string is happening somehow. But then I … -
QuerySet working in shell but not in Views.py - Django 1.10
When executing the following QuerySet in the Django shell (python manage.py shell): Employee.objects.filter(restaurant__pk = 1) I get a result back: <QuerySet [<Employee: Joyce McDonnals>]> Please excuse me, because I am new to Django. I am trying to implement this queryset dynamically in my webpage through the PK. The get_queryset which I have defined in the views.py is: class EmployeeList(ListView): template_name= "Restaurants/employee_list.html" model = Employee def get_queryset(self, **kwargs): queryset = Employee.objects.filter(pk= restaurant.pk) return queryset But this returns the error: NameError at /restaurant/1/employees/ name 'restaurant' is not defined Request Method: GET Request URL: http://127.0.0.1:8001/restaurant/1/employees/ Django Version: 1.10.5 Exception Type: NameError Exception Value: name 'restaurant' is not defined I have tried some variants for the queryset in my views.py, but I can't seem to get it to work. Could someone help me to define this queryset? -
Get objects in which today date lies between two dates in table
I have a django model like this class AthleteSubscription(models.Model): user = models.ForeignKey(User, related_name="user_subscription", default='') subscription_start = models.DateField(default=datetime.date.today) subscription_end = models.DateField(default=datetime.date.today() + timedelta(30)) Where subscription_start is start date of subscription and subscription_end is the end date of subscription. I want to get those records in which current date (date today) lies between subscription_start and subscription_end. How can I do this with django ORM. -
Django changing url by value passed to template
This is my first project on Django and what i want to do is that i have a variable 'a' passed from a view in my template and i am using it like this <a href="{% url 'login:updateComplaint'%}{{a.id}}"> to go to a particular url in this case say http://127.0.0.1:8000/login/updateComplaint/4 but instead of this my code is sending me to this url http://127.0.0.1:8000/login/updateComplaint/0/4 Can someone help me fix this If you want any other part of code please comment -
List append not working in python, keeps resetting
I am trying to create a list of days within a duration I have calculated in python. For some reason, when I use append(), it only appends a few times then resets and continues this way. I'll do my best to explain: I have objects that I get based on the start date. I then find all of the days between the start date and the end date (both fields in the object) of the object and create a list - this is working fine. I then create another list, that takes the items in the previous list and finds only the .day() part of it. This part isn't working. duration = [] # find the duration they are on holiday day_delta = timedelta(1,0,0) next = holiday_object.start_date day_ending = holiday_object.end_date while (day_ending - next) > day_delta: next = next + day_delta duration.append(next) # add start and end... this could be tidier day_beginning = holiday_object.start_date duration.append(day_beginning) duration.append(day_ending) # get the day part of the date only, probably longwinded but if I combine the two I get a NoneType error days_away = [] for item in duration: print item day_only = item.day print day_only days_away.append(day_only) print days_away For some reason it seems … -
Why I am Getting KeyError in Scrapy?
I am using Scrapy spiders inside Celery and I am getting this kind of errors randomly Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/twisted/internet/base.py", line 428, in fireEvent DeferredList(beforeResults).addCallback(self._continueFiring) File "/usr/lib/python2.7/site-packages/twisted/internet/defer.py", line 321, in addCallback callbackKeywords=kw) File "/usr/lib/python2.7/site-packages/twisted/internet/defer.py", line 310, in addCallbacks self._runCallbacks() File "/usr/lib/python2.7/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) --- <exception caught here> --- File "/usr/lib/python2.7/site-packages/twisted/internet/base.py", line 441, in _continueFiring callable(*args, **kwargs) File "/usr/lib/python2.7/site-packages/twisted/internet/base.py", line 667, in disconnectAll selectables = self.removeAll() File "/usr/lib/python2.7/site-packages/twisted/internet/epollreactor.py", line 191, in removeAll [self._selectables[fd] for fd in self._reads], exceptions.KeyError: 94 The number changes from case to case (94 could be 97 in another case and so on) I am using: celery==3.1.19 Django==1.9.4 Scrapy==1.3.0 This is how I run Scrapy inside Celery: from billiard import Process from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings class MyCrawlerScript(Process): def __init__(self, **kwargs): Process.__init__(self) settings = get_project_settings('my_scraper') self.crawler = CrawlerProcess(settings) self.spider_name = kwargs.get('spider_name') self.kwargs = kwargs def run(self): self.crawler.crawl(self.spider_name, qwargs=self.kwargs) self.crawler.start() def my_crawl_manager(**kwargs): crawler = MyCrawlerScript(**kwargs) crawler.start() crawler.join() Inside a celery task, I am calling: my_crawl_manager(spider_name='my_spider', url='www.google.com/any-url-here') Please any idea why this is happening? -
Django annotate queryset depending on another query
class TradeItem(models.Model): ... class Wishlist(models.Model): user = models.ForeignKey(User, related_name='wishlist_user') item = models.ForeignKey(TradeItem, related_name='wishlist_item') I need to make TradeItem queryset annotated with a Boolean of whether an item is in this user's wishlist. Something like items = TradeItem.objects.all().annotate(wishlist= <heresy> if Wishlist.objects.filter(user=request.user, item={current_item}: True else: False </heresy> ) Is it possible to do the said thing with annotate/aggregate, and what would be the most efficient way for that in general? -
Using gunicorn with cprofile
I am trying to run cProfile with gunicorn but it gives me two Profile outputs - One of my program and the other is gunicorn Master (i am guessing). When i try to save this output in a file it only saves one output : that of the gunicorn. Is there any way i can save only the output of my program? -
Django imageField
I'm trying to set an imageField for upload an image on the admin page, but this error raises. no such column: series_serie.serie_image This is the model: class Serie (models.Model): serie_name = models.CharField(max_length=100) serie_image = models.ImageField(upload_to='/') def __str__(self): return (self.serie_name) I've made the following: python manage.py flush python manage.py makemigrations python manage.py migrate Then I try to access the Serie model from admin side but got that error. What I could do? Thanks. -
Embeded serializers in DRF for mongo and django
I am trying to create a non model embeded serializer in Django Rest Framework. I'm stuck here. Need you help. Thanks in advance. class IPNetwork(serializers.ListSerializer): network_netmask = serializers.IPAddressField(required=False) network_gateway = serializers.IPAddressField(required=False) network_mac = serializers.CharField(required=False) network_dns = serializers.ListField(required=False) network_ip = serializers.IPAddressField(required=False) class RouterInfoSerializer(serializers.Serializer): router_name = serializers.CharField(required=False) router_ip_networks = IPNetwork(many=True) router_devices = serializers.ListField(required=False)