Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'QuerySet' object has no attribute 'filter_on_search' Python Django
Can anyone please suggest me why I am getting this error. Following is model with Manager class Customer(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=256) customer_mobile = models.CharField(max_length=10) customer_email = models.CharField(max_length=100,null=True) customer_dob = models.DateField() customer_remarks= models.CharField(max_length=256,null=True) row_status = models.BooleanField(choices=ROW_STATUS, default=True) created_date = models.DateTimeField() updated_date = models.DateTimeField() objects = MyClassManager() def __unicode__(self): return self.customer_name def as_dict(self): """ Create data for datatables ajax call. """ return {'customer_name': self.customer_name, 'customer_mobile': self.customer_mobile, 'customer_dob': self.customer_dob, } Manager Starts here --------- class MyClassMixin(object): def q_for_search_word(self, word): """ Given a word from the search text, return the Q object which you can filter on, to show only objects containing this word. Extend this in subclasses to include class-specific fields, if needed. """ return Q(name__icontains=word) | Q(supplier__name__icontains=word) def q_for_search(self, search): """ Given the text from the search box, search on each word in this text. Return a Q object which you can filter on, to show only those objects with _all_ the words present. Do not expect to override/extend this in subclasses. """ q = Q() if search: searches = search.split() for word in searches: q = q & self.q_for_search_word(word) return q def filter_on_search(self, search): """ Return the objects containing the search terms. Do not expect to override/extend this … -
Creating dynamic Django template Variables names inside Javascript script tag [duplicate]
This question is an exact duplicate of: Creating dynamic Django Template Variables inside Javascript script tag 1 answer I have to create django variable names dynamically based on user input. Below is the snippet. The Javascript function runs at two events: 1> On Page Load 2> User increases/decreases Number of Categories OR Bar charts. Below is the context dict after user has entered his numbers (Please see screen shot). data = {'nbr_category': 2, 'nbr_bar_charts': 2, u'field11': 13, u'field12': 65, u'field13': 87, u'field21': 112, u'field22': 91, u'field23': 54, u'field31': 11, u'field32': 76, u'field33': 65} Below is the Javascript function used to create dynamic number of categories or Bar charts input fields. <script type='text/javascript'> function createMatrix() { var nbr_category = document.getElementById("nbr_category").value; var nbr_bar_charts = document.getElementById("nbr_bar_charts").value; var matrix_input_fields = ""; for (i = 1, nbr_bar_charts = nbr_bar_charts, text_charts = ""; i <= nbr_bar_charts; i++) { for (j = 1, nbr_category = nbr_category, text_category = ""; j <= nbr_category; j++) { text_category = text_category + '<input class="input form-control" id="field' + i + j +'" placeholder="Field' + i + j +'" name="field' + i + j + '" value="{{field + i + j}}' + '" type="text">'; } text_charts = text_charts + text_category + '<br/>' } … -
Django form not calling clean_<fieldname> (in this case clean_email)
I couldn't find an answer to the following question, it took me a couple of hours to find out, hence I'm adding it. I'll add my approach of solving it and the answer. I'm following a YouTube tutorial from This person. For some reason I'm typing the same code, and I checked every single letter. Yet for some reason my cleaning functions aren't called. It's probably something simple, especially since a related question showed something similar. It's probably a framework thing that I get wrong, but I wouldn't know what it is. Here is the relevant code. forms.py (complete copy/paste from his Github) from django import forms from .models import SignUp class ContactForm(forms.Form): full_name = forms.CharField(required=False) email = forms.EmailField() message = forms.CharField() class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['full_name', 'email'] ### exclude = ['full_name'] def clean_email(self): email = self.cleaned_data.get('email') email_base, provider = email.split("@") domain, extension = provider.split('.') # if not domain == 'USC': # raise forms.ValidationError("Please make sure you use your USC email.") if not extension == "edu": raise forms.ValidationError("Please use a valid .EDU email address") return email # Final part is ommited, since it's not relevant. admin.py (typed over from the tutorial) from django.contrib import admin … -
Creating hyperlinked relations when testing Django Rest Framework
When writing tests for Django Rest Framework, how are hyperlinked relations supposed to be created? I'm trying to create a Foo object with a related Bar object, but I'm not sure how I can most efficiently create that relation. # models.py import uuid from django.db import models class Foo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) bar = models.ForeignKey('Bar') class Bar(models.Model): BarUUID = models.UUIDField(primary_key=True, default=uuid.uuid4 # serializers.py from rest_framework import serializers from myapp.models import Bar, Foo class FooSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Foo fields = ('url', 'id', 'bar') class BarSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Bar fields = ('url', 'BarUUID') # views.py class FooViewSet(viewsets.ModelViewSet): queryset = Foo.objects.all() serializer_class = FooSerializer class BarViewSet(viewsets.ModelViewSet): queryset = Bar.objects.all() serializer_class = BarSerializer # urls.py from rest_framework import routers router = routers.DefaultRouter() router.register(r'foos', views.FooViewSet) router.register(r'bars', views.BarViewSet) # tests.py from rest_framework.reverse import reverse from rest_framework.test import APITestCase class FooTests(APITestCase): def test_create_foo(self): bar = Bar.objects.create() url = reverse('foo-list') data = { 'bar': # how do I get the URL? } response = self.client.post(url, data, format='json') -
Django templates: display non-empty fields only?
Django 1.10 Say, we are using DisplayView. The question seems to be more or less popular. Like this: Django templates: loop through and print all available properties of an object? The problem is that widgets are simply thrown out of the window. For example, the piece of code in the accepted answer will display: created_by => 1 Whereas in the Model: created_by = models.ForeignKey(User, on_delete=models.CASCADE) I would like for an equivalent of something like this to be produced: <p>Created by: {{ object.created_by }}</p> Could you help me solve this problem? Or maybe there is a ready made template tag or something? -
Cache staleness, even though I am not using a cache
I have uploaded my Django site on a development server at Digital Ocean and started serving it using apache2 and mod_wsgi. I am also using apache2 to serve static content. It's a fresh installation of Debian on the server, and have done minimal changes. I am using Django Haystack and Solr to support full-text search. I've checked that both the database and Solr are kept up to date. Now, if the url I use to retrieve a page contains a query string (it can be as small a ?asd, where asd is not a valid param) everything comes out fine. If however it does not contain such a query string, I get a version of the page that can be several hours (days?) old, even containing items I've deleted from the database. The issue is resolved as soon as I restart apache2. Doing apache2ctl -M | grep cache returns nothing, and settings.py does not reference caching either. Anyone have an idea what could be the cause of this? -
Django ForeignKey and associated values in initial model
First off, sorry for this somewhat crappy title: I wasn't able to find a short and explicaive title for this one . I'm currently trying to create an app where there will be players and each will have an inventory. The inventory consists of a ManyToManyField of Items. class Item(models.Model): name = models.CharField(_('Name'), max_length=67) flavor_text = models.TextField(_('Flavor text')) class Inventory(models.Model): items = models.ManyToManyField(Item, verbose_name=_('Items')) I'm trying to implement a system where a player can, for example, have 3 bananas, 1 screwdriver and 17 loafs in his inventory. As I'm very lazy, I don't want to enter manually 3 "banana" items in my inventory. However, putting a quantity field in the Item model would be counter-productive, as I would need to create an Item named "3 bananas", another "2 bananas", again and again. I also tought of creating Alice's Bananas, Bob's Bananas, and change the quantity, but still, that's creating too much banana items : especially if I need to add more players. So, here is my question: How can I associate a value (here, a quantity) to a ForeignKey, but inside the model declaring the ForeignKey? Thanks for reading! -
Passing a variable to a Django login form
I need to modify an Django application that I don't fully understand. The login is at /accounts/login/ and in the main URLs I have: url(r'^accounts/', include('formshare.apps.main.registration_urls')), The registration_urls has: urlpatterns = patterns( '', url(r'^activate/complete/$', TemplateView.as_view( template_name='registration/activation_complete.html'), name='registration_activation_complete'), # Activation keys get matched by \w+ instead of the more specific # [a-fA-F0-9]{40} because a bad activation key should still get to the view # that way it can return a sensible "invalid key" message instead of a # confusing 404. url(r'^activate/(?P<activation_key>\w+)/$', ActivationView.as_view(), name='registration_activate'), url(r'^register/$', FHRegistrationView.as_view(form_class=RegistrationFormUserProfile), name='registration_register'), url(r'^register/complete/$', TemplateView.as_view( template_name='registration/registration_complete.html'), name='registration_complete'), (r'', include('registration.auth_urls')), ) There is no view for login and logout so I assume the application is using the default Django views. My best guess is that the application authenticate using this class: class DigestAuthentication(BaseAuthentication): def __init__(self): self.authenticator = HttpDigestAuthenticator() def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'digest': return None if self.authenticator.authenticate(request): return request.user, None else: raise AuthenticationFailed( _(u"Invalid username/password")) def authenticate_header(self, request): response = self.authenticator.build_challenge_response() return response['WWW-Authenticate'] With this information I want to pass a new variable to the login and logout templates. How can I customize the both views so I can pass a new variable? Any help is much appreciated. -
How to implement forgot password on django Production environment?
How can i implement a django based forgot password functionality with gmail verification? I have gone through many tutorials. but they all for development environment. What changes should i do to work this in production environment? -
In Django, how can I have a dropdown that loads data and a submit button that commits data on the same html page?
I am working on my first Django site. I setup an html page that accepts user inputs, runs calculations, saves to the database, and displays output values into a form when the user hits a submit button. Now I would like to add functionality for a dropdown to call up one of those submissions from the database if a user selects a item from the dropdown. So, I created a second form on the same html page for the drop down and successfully populated the dropdown list, however, can't figure out how to load data to the original form when the dropdown is selected. I think this can be accomplished with form attributes, but I am not sure. Example: if request.method == 'POST' and form.is_valid(): This posts the users inputs to the db and displays the calculation elif request.method == 'GET' and 'dropdown' in request.POST: Here lies the problem. When I select an item in the dropdown nothing happens, or I get an error on the page load. I have tried lots of different approaches the above is the latest. else: A bunch of variables = None Can anyone provide some coaching or an example? -
How to avoid dependency injection in Django?
I'm trying to figure out how to avoid dependency injection in my project. There is a file notifications.py in app directory. File notifications.py contains methods for sending emails to admin and users. To get admins email, I need to check object of SystemData model. But in models, I use notifications. models class SystemData(models.Model): admin_alerts_email = models.EmailField(verbose_name=u'Emailová adresa admina') contact_us_email = models.EmailField(verbose_name=u'Adresa kontaktujte nás') waiting_threshold = models.PositiveSmallIntegerField(verbose_name=u'Maximálny počet minút čakania') class SomeModel(models.Model): .... def save(...): notifications.send_message_to_admin('message') notifications.py from django.core.mail import EmailMessage from models import SystemData def send_message_to_admin(message): mail = EmailMessage(subject, message, to=[SystemData.objects.all().first().admin_email]) mail.send() Django returns that it can't import SystemData. Do you know what to do? -
virtualenvwrapper: Command "python setup.py egg_info" failed with error code 1
When trying to install virtualenvwrapper on my mac os v10.11 using: sudo pip install virtualenvwrapper I got the following error message: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-ktzs4x/virtualenvwrapper/ Here are my logs: Collecting virtualenvwrapper Downloading virtualenvwrapper-4.7.2.tar.gz (90kB) 100% |████████████████████████████████| 92kB 243kB/s Complete output from command python setup.py egg_info: ERROR:root:Error parsing Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pbr/core.py", line 111, in pbr attrs = util.cfg_to_args(path, dist.script_args) File "/usr/local/lib/python2.7/site-packages/pbr/util.py", line 264, in cfg_to_args wrap_commands(kwargs) File "/usr/local/lib/python2.7/site-packages/pbr/util.py", line 576, in wrap_commands for cmd, _ in dist.get_command_list(): File "/usr/local/lib/python2.7/site-packages/setuptools/dist.py", line 530, in get_command_list return _Distribution.get_command_list(self) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 772, in get_command_list klass = self.get_command_class(cmd) File "/usr/local/lib/python2.7/site-packages/setuptools/dist.py", line 514, in get_command_class return _Distribution.get_command_class(self, command) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 815, in get_command_class import (module_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/command/check.py", line 13, in from docutils.utils import Reporter File "/usr/local/lib/python2.7/site-packages/docutils/utils/init.py", line 20, in import docutils.io File "/usr/local/lib/python2.7/site-packages/docutils/io.py", line 18, in from docutils.utils.error_reporting import locale_encoding, ErrorString, ErrorOutput File "/usr/local/lib/python2.7/site-packages/docutils/utils/error_reporting.py", line 47, in locale_encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1] File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 543, in getdefaultlocale return _parse_localename(localename) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/locale.py", line 475, in _parse_localename raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8 error in setup command: Error parsing /private/tmp/pip-build-ktzs4x/virtualenvwrapper/setup.cfg: ValueError: unknown locale: UTF-8 ---------------------------------------- Command "python setup.py egg_info" failed … -
Django ) Accumulative image upload with input tag
I'm developing the module to upload a post with a title , contents and multiple images(optionally). I made it to upload multiple images as below: upload.html <input accept="image/*" multiple="multiple" type="file" name="images"> views.py for image in request.FILES.getlist('images'): Image(image_url=image).save() My problem is that it is working only for the images uploaded last. I want to accumulate images the user upload for many times like facebook , not for the last time. I'm showing the thumbnails of images uploaded for user to give them a feedback of UI. It is working well , but the images really uploaded are the ones uploaded only at last time. How can I make it to accumulate images uploaded? -
How can I use a SplitArrayField in a ModelForm
I am trying to show a postgresql ArrayField as multiple input fields in a form that users can submit data. Lets say I had a model: class Venue(models.Model): additional_links = ArrayField(models.URLField(validators=[URLValidator]), null=True) That a form was using: class VenueForm(forms.ModelForm): class Meta: model = Venue exclude = ['created_date'] widgets = { 'additional_links': forms.Textarea(), } How would I make the ArrayField use a SplitArrayField in the ModelForm? I tried: class VenueForm(forms.ModelForm): additional_links = SplitArrayField(forms.TextInput(), size=5, remove_trailing_nulls=True) class Meta: .. and the same in the Meta class widgets: widgets = { 'additional_links': forms.SplitArrayField(forms.TextInput(), size=3, remove_trailing_nulls=True) } I also tried different form inputs/fields, but I always get the following error: /lib/python3.5/site-packages/django/contrib/postgres/forms/array.py", line 155, in __init__ widget = SplitArrayWidget(widget=base_field.widget, size=size) AttributeError: 'TextInput' object has no attribute 'widget' -
Django Path template Dost' not exist
i was follwed tutorial django in django doc file v10 buat in tutorial part 4 in the last chapter i found error class DetailView(generic.DetailView): model=Question templates_name="polls/detail.html i don't now where the code error -
Django - set default value from other field value
I have a problem to set a default field value. What I want to do?I want that price in class Packages be a default value of priceNoTax in class Bill. As you can see, all three classes are logically connected.Example: Account 1 has a package with id 1. Price of this package is 100. Default value of priceNoTax for Account 1 is 100.How to do that? I am relative new at this, so I need help. models.py class Packages(models.Model): #other fields price = models.IntegerField(validators=[MinValueValidator(1)], verbose_name="Price of package") class Account(models.Model): startDate = models.DateField(verbose_name="Start date") finishDate = models.DateField(verbose_name="Finish date") idPackage = models.ForeignKey(Packages, on_delete=models.CASCADE, verbose_name="Package") class Bill(models.Model): date = models.DateField(default=datetime.now()) tax = models.FloatField(default=0.20) priceNoTax = models.IntegerField() priceTax = models.FloatField(default=priceNoTax+(priceNoTax*tax)) idAccount = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account") def __str__(self): return self.date Thanks a lot!!! -
What are the difference between django-compressor and django-sass processor?
I'm using django compressor, to compress JS and CSS. As the introduction about django compressor says:"Django Compressor processes, combines and minifies linked and inline Javascript or CSS in a Django template into cacheable static files." Looks like the same goal of django-sass-processor. The problem when I use django-compressor is that during the development, my application is slow (more than 2 second to render a page that has no DB access in the view and doesn't process anything). Is that normal? I thought to speed up the apps, using the sass processor that checks the timestamp and compile the sass file only if there's some change (is this the purpose of the tool right?). By the way, I have a bit of confusion, can you explain me what are and how to use it? -
How to Implement forgot password using email in Django?
I am following this repo of github:- https://github.com/brutasse/django-password-reset and this docs :- http://django-password-reset.readthedocs.io/en/latest/quickstart.html But unable to configure it. can anyone explain how to configure it because it is not clear in the docs. If you have another way of implementing this then please share. -
Make Django not to validate redundant forms in formset
Is it possible to simply tell the Django not to validate and process data from some form? I have two forms and if the checkbox is unchecked (round trip) I want to validate and process only the first form. The problem is that Django thinks that there are errors in the second form since there are unfilled required fields. I know that Django doesn't validate the form when it's not changed but here, I have many JS which autofills fields in both forms and events etc. so it is very hard to rewrite the code. Is it possible to somehow disable whole form using JQuery? (disable all inputs didn't help) ride_two.find(':input').not(':button, :submit, :reset, :checkbox, :radio').val(''); ride_two.find(':checkbox, :radio').prop('checked', false); -
Retrieve all related objects (reverse foreign keys) efficiently with django
I have the following models: Car: name = models.CharField(max_length=50) model = models.CharField(max_length=80) Driver: name = models.CharField(max_length=50) address = models.CharField(max_length=80) car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='drivers') Now I want to retrieve all of cars including related model driver data cars = Car.objects.prefetch_related('drivers').all() Now in my template I just want to print each car and the first driver information {% for car in cars %} <tr> <td>car.name</td> <td>car.model</td> <td>car.drivers.first.name</td> <td>car.drivers.first.address</td> </tr> {% endfor %} However, this results in 2k+ queries for around 500 cards in my db and it takes a while to load. Am I doing something wrong, is there anyway to make this more efficient? -
Django showing error while saving data into a model: 1048, Column 'id' cannot be null
I am writing a script which can pull data from different API's and store into a MySQL database. This application will run from command line. So I am only using Django's ORM. But when I am creating a model which doesn't have primary key but have a column named id. When I am trying to save data in this model I am getting a error 1048, Column 'id' cannot be null I am really confused why this happens. Because from API I get values from id column and there is no chance to get null or empty value for this column. Please suggest me what I am doing wrong here. Here is my model: class Graphite(models.Model): class Meta: db_table = 'graphite' id = models.BigIntegerField() full_name = models.CharField(max_length=250, null=True) email = models.CharField(max_length=250, null=True) status = models.CharField(max_length=150, null=True) And this is the code when I am trying to save data in this model: Graphite.objects.using('database_name').create( id=row['id'], full_name=row['full_name'], email=row['email'], status=row['status']) When saving data into model I am using Graphite.objects.using('database_name'). because I have multiple database connected in this application. -
Google Indexing is Deleting My Content
I don't know if this is true or not, but after what I've seen I think it is. A week ago, I started my social networking website. I started optimizing my website for search engines. It even got listed on Google. But since 4 days, my users' content keeps getting deleted. Not everything is listed till now on Google, but whatever gets listed on Google, gets deleted from my website. For some days I thought that there was some fault in my programming, but then I turned off access for Google crawlers to crawl my website and everything works just fine now. I really need help. And I want to know what should I do? My backend is Django. -
Django Save creating two records instead of one
Django is creating two records in MySQL instead of one. I call a function via a link <a href="{% url 'markpresent' id=c.id %}"><button class="btn btn-primary">Thats Me!</button></a> The function itself is very straight forward. I take the variable via a request.get, create a new object, and finally save it. However, when I check the DB there are two records, not just one. def markpresent(request, id): new_attendance = attendance(clientid_id = id, date = datetime.datetime.now(), camp = 3) new_attendance.save() return render(request, 'clienttracker/markpresent.html', { 'client': id, }) Any help and direction would be appreciated. -
Nodejs/asp core 1.0 framework like django
I'm use nodejs and express for some type of projects, but I like the admin interface and admin-widgetof django, I googled around, but there're really huge number of frameworks for node. So I'm looking for a nodejs or Asp core 1.0 frameworks where is provided an admin interface,or widget or where is really easy and fast to create one... thanks -
Django and Boostrap: Dynamic Table of Contents with Markdown and Inclusion Tags
I'm currently working on a dynamic Table of Contents for my Django app. I'm using the "Table of Contents" Markdown extension here which not only creates a TOC, but also adds the fitting <id> to each heading and links the corresponing TOC-entry to it. Pretty neat. Also, I want to store the TOC in a database, so that it's only rendered once after saving the model. I'm using this model: class Wiki(models.Model): title = models.CharField(max_length = 100, unique = True) wiki_page = models.TextField(blank = True) # This is wiki_page_markdown parsed. Now HTML. wiki_page_markdown = models.TextField(blank = True) #User enters text here, using markdown syntax wiki_page_toc = models.TextField(blank = True) # Table of Contents def save(self): import markdown md = markdown.Markdown(extensions='markdown.extensions.toc') html = md.convert(self.wiki_page_markdown) #Converting Markdown in HTML self.wiki_page = html self.wiki_page_toc = md.toc # TOC from markdown extension gets saved into wiki_page_toc⋅ super(Mediwiki, self).save() # Call the "real" save() method. Here's my inclusion tag: @register.inclusion_tag('mediwiki/toc.html', takes_context = True) def toc(context, *args, **kwargs): entry = kwargs['entry'] # Returns title from current page toc = Wiki.objects.get(title=entry).wiki_page_toc.split('\n') return {'toc': toc} Here's it's template: <div class="well"> <ul class="nav nav-pills nav-stacked"> {# TODO #} {% for entry in toc %} {{ entry|safe}} {% endfor %} …