Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-tables2 CheckBoxColumn - only header checkbox is generated
I've got a table to generate based on a list of objects and I'd like to show one more column (checkboxcolumn) whose value would be set based on some data in my objects. I tried to use CheckBoxColumn shipped with django-tables2 but it only generates a checkbox in my header and all data rows display '- ' (minus sign with space). There is very little information about that particular column type on the Internet so I couldn't find any solution to this problem. Here is my code for the table: class MyTable(ScheduleTable): checkbox_column = CheckBoxColumn() class Meta: order_by = "-end" What I am missing? I tried adding some attributes (like td_input, input or checked parameter) but nothing worked. Daniel -
Applying Multiple Filters to Django Model Queryset
Assume I have a queryset of django models. When a user clicks a button, visible on the home page of the website, I would like to filter these models by applying some sort of parameters to one of the model fields (logic handled in view function). After the queryset is filtered. I would like to display to filtered results in a template. I have been able to accomplish this task in a variety of ways. However, I want to be able to apply multiple filters to a set of models. So my issue is, how do I access the value of the previously filtered queryset (which I passed in as a template variable when rendering) so that I can filter it again? -
UnicodeError error when calling Django i18n makemessages command
I'm working with Django's internationalisation features to generate translation strings for a webapp. A problem is arising where I try and call makemessages, and the existing language .po file contains a special character (such as $, £, etc). Where one of these exists, makemessages tries to load the existing .po file and to decode it. When it does this, I get an error: Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 325, in handle self.write_po_file(potfile, locale) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 458, in write_po_file msgs, errors, status = gettext_popen_wrapper(args) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 51, in gettext_popen_wrapper stdout = stdout.decode(stdout_encoding) File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode character u'\xa2' in position 2105: ordinal not in range(128) I've tried to dig back through the traceback here, but I'm at a loss as to what's happening. It seems as though Django tries to decode the existing .po file as UTF8, but then when re-encoding it, it's using an ASCII … -
How to do user registration in Django REST framework api
I have searched the whole web and cant find any satisfying answer I have changed my user model by adding some custom fields So now i got 'username', 'password', 'email', 'first_name', 'last_name', 'phonenumber', 'address' instead of 'username', 'password', 'email', 'first_name', 'last_name', --- (these are default)--- This is my models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class userinformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phonenumber = models.CharField(max_length=100) address = models.CharField(max_length=200) class Meta: verbose_name_plural = "User Information" def __str__(self): return str(self.user)+' - '+self.phonenumber+' - '+self.address Im trying to make a Django REST framework api on which i can post 'username', 'password', 'email', 'first_name', 'last_name', 'phonenumber', 'address' And register user with these details what should i add in my veiws.py and serializers.py -
Setting up django-allauth, receive error: Index column size too large
I am attempting to run ./manage.py migrate when installing django-allauth, which always fails with this error: django.db.utils.OperationalError: (1709, 'Index column size too large. The maximum column size is 767 bytes.') I am using MariaDB 10.1.19 and in my /etc/mysql/my.cnf file, I have added the following lines to increase the available index size: [server] innodb-large-prefix = ON However, the error still occurs. Later documentation that I have read concerning django-allauth states that this error has been resolved, but I am still experiencing it. How do I ensure that this configuration directive in the configuration is actually being read and used? How do I fix this index sizing error? Thanks! -
Coverage test django admin custom functions
I created a custom functions in django admin.py and im trying to test the using coverage : class Responsible(admin.ModelAdmin): """ Inherits of admin class """ list_display = ('user', 'Name', 'last_name', 'process',) search_fields = ('p__name', 'user__username') def User_Name(self, obj): return obj.user.first_name def User_Last_Name(self, obj): return obj.user.last_name Responsible model has a django user model foreign key...So far i tried a lot of ways to test: class AdminTestCase(TestCase): fixtures = ["initial_data.json"] def test_first_name(self): rsf = Responsible.objects.get(id = 1) Nombre(rsf) def test_first_name2(self): self.obj = Responsible.objects.get(id = 1) But nothing works....any help please ? Thanks in advance !! -
Best practices for organizing frontend folders inside django
I am using the Django framework and library React for doing my application. At Django I insert my frontend code inside assets folder, so my question is if use a vendor folder for externals css/js is a good practice? if so how do I organize my code? For example, I use the component react-dates and I have to edit .scss files. My folder structure would be /assets/vendors/scss/ ? -
Django: Template Tag unable to load image.Only reading media media image
I am trying to generate a PDF with django pisa module. views.py def reportPdf(template_src, context_dict): template = get_template(template_src) context = Context(context_dict) htmlRender = template.render(context) resultObj = StringIO.StringIO() pdfObject = pisa.pisaDocument(StringIO.StringIO(htmlRender.encode( 'utf-8')), resultObj,link_callback=fetch_resources) response = HttpResponse(resultObj.getvalue(), content_type = 'application/pdf') response["Content-Disposition"] = 'inline;filename=sample.PDF' return response def fetch_resources(uri, rel): import project.settings path = os.path.join(project.settings.MEDIA_ROOT, uri.replace( project.settings.MEDIA_URL, "")) return path class abc(): def get(self,request, *args, **kwargs): // some code return reportPdf('pdf.djhtml',{'pagesize': 'A4',"refer_data":detail} settings.py: PROJECT_PATH = os.path.realpath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.realpath(os.path.join(PROJECT_PATH, "media")) MEDIA_URL = '/media/' Template: pdf.djhtml: code for image available in media folder: <img src="/media/sample.jpg"/> Above works fine as i have incorporated media in views.py But below code doesn't load the image. refer_data.image.url = http://www.w3schools.com/images/w3schools_green.jpg (Consider this http url as sample for testing).This Image url I am getting from a API call. {% if refer_data.image.url != "" %} <img src="{{refer_data.image.url}}"/> {% else %} <img src="noimage.png"/> {% endif %} Could someone analyse and share some idea where I am missing? Any help will be appreciated. -
Django middleware autocommit cannot be used
Our code has custom middleware to record requests and responses so we can log API activity. def process_response(self, request, response): user = None try: if request.user.is_authenticated(): user = request.user the_record = Record( requestUser=user, requestPath=request.path, requestMethod=request.method) the_record.save() except: pass In process_response method, we create object and save it. If API method is marked with @transaction.atomic, log message autocommit cannot be used inside a transaction will appear. No exception in method, but simply record in database in that case for that specific API call does not exist. Is there any explanation why autocommit log message appears? Maybe to use model manager create instead of save method? -
Python- global name is not defined
I have a Django project, in which I want to display a form to the user on a particular webpage. Some of the fields of the form should be automatically populated with information from the database. At the moment, two of the 'text' fields on the form are automatically populated when the page first loads, however, the 'date' field is left blank. If I click on the text area for the 'date' field, a little calendar appears as a sort of 'drop down', and I can view a single month at a time. If I select a day from whichever month, that date is then inserted into the text area of the 'date' field. However, if I then reload the page, although the text fields retain their value, the 'date' field is blank again... I have a Python class called DepositInfoForm, which is defined in the forms.py file of my projects app. The class is defined with the following structure: class DepositInfoForm(ValidateFrom): ... date_received = mDateField(required=False, label="Date deposit received", widget=forms.DateInput(format='%d/%m/%Y', attrs=({'class':'datepicker'}))) class Meta: model = Deposit fields = ('amount_exc_vat', 'amount_inc_vat', 'date_received') def __init__(self, *args, &&kwargs): instance = kwargs.get('instance', {}) project = instance.project try: amount_exc_vat = int(round(instance.amount_exc_vat)) except TypeError: amount_exc_vat = … -
Jinja2 : proper way to write [not so] complex template
I'm trying to implement a simple calendar webpage. I'm quite new to Jinja2 but my understanding of templates is that writing HTML code in the Python sources should be avoided as templates are designed for this purpose. The problem that I'm facing I that I don't see how to write clear templates for this project. I guess there is an overall architecture problem in my project... My page template: {% extends "base.html" %} {% block title %}The title{% endblock %} {% block content %} <h1>Hey</h1> <p> I'm happy </p> <div id="calendar"> <table> <tr> {% for month in range(1, 13) %} <td valign="top" align="center">{# html code for a single month goes here... #}</td> {% endfor %} </tr> </table> </div> {% endblock %} Each month template is <table> <th>{{ month_name }}</th> {% for day_number in days %} <tr><td>{{ day_number }}</td><td>{{ weekday }}</td></tr> {% endfor %} </table> Finally, I have a Python class for a calendar that basically provides helper functions to calculate the days of the month: class Calendar: def __init__(self, year): self.year = year def monthrange(self, month): nextmonth = month % 12 + 1 nextyear = self.year + 1 if nextmonth == 1 else self.year firstday = datetime.date(self.year, month, 1) lastday … -
Import python file in Django models
I have a question about importing python file from Django models. I'm just creating a models form and I have in this one a list of country. The user can make a choice with a list. But in my models.py file, it's very ugly and I would like to know if it's possible to write the country list in a python file and call this file in the argument choices = COUNTRY_CHOICE This is my models.py : #-*- coding: utf-8 -*- from django.db import models from django.forms import ModelForm # Sexe choice CHOIX_SEXE = ( ('M', 'Mâle'), ('F','Femelle'), ) CHOIX_PAYS = ( ('AFG','Afghanistan'), ('AF','Afghanistan'), ('ZA','Afrique du Sud'), ('AL','Albanie'), ('DZ','Algérie'), ('DE','Allemagne'), ('AD','Andorre'), ('AO','Angola'), ('AI','Anguilla'), ('AQ','Antarctique'), ('AG','Antigua-et-Barbuda'), ('AN','Antilles néerlandaises'), ('SA','Arabie saoudite'), ('AR','Argentine'), ('AM','Arménie'), ('AW','Aruba'), ('AU','Australie'), ('AT','Autriche'), ('AZ','Azerbaïdjan'), ('BJ','Bénin'), ('BS','Bahamas'), ('BH','Bahreïn'), ('BD','Bangladesh'), ('BB','Barbade'), ('PW','Belau'), ('BE','Belgique'), ('BZ','Belize'), ('BM','Bermudes'), ('BT','Bhoutan'), ('BY','Biélorussie'), ('MM','Birmanie'), ('BO','Bolivie'), ('BA','Bosnie-Herzégovine'), ('BW','Botswana'), ('BR','Brésil'), ('BN','Brunei'), ('BG','Bulgarie'), ('BF','Burkina Faso'), ('CA','Canada'), ('CV','Cap-Vert'), ('CL','Chili'), ('CN','Chine'), ('CY','Chypre'), ('CO','Colombie'), ('KM','Comores'), ('CG','Congo'), ('KP','Corée du Nord'), ('KR','Corée du Sud'), ('CR','Costa Rica'), ('HR','Croatie'), ('CU','Cuba'), ('DK','Danemark'), ('DJ','Djibouti'), ('DM','Dominique'), ('EG','Égypte'), ('AE','Émirats arabes unis'), ('EC','Équateur'), ('ER','Érythrée'), ('ES','Espagne'), ('EE','Estonie'), ('US','États-Unis'), ('ET','Éthiopie'), ('FI','Finlande'), ('FR','France'), ('GE','Géorgie'), ('GA','Gabon'), ('GM','Gambie'), ('GH','Ghana'), ('GI','Gibraltar'), ('GR','Grèce'), ('GD','Grenade'), ('GL','Groenland'), ('GP','Guadeloupe'), ('GU','Guam'), ('GT','Guatemala'), ('GN','Guinée'), ('GQ','Guinée équatoriale'), ('GW','Guinée-Bissao'), ('GY','Guyana'), ('GF','Guyane française'), ('HT','Haïti'), ('HN','Honduras'), ('HK','Hong Kong'), … -
Get content of PIL.EpsImagePlugin.EpsImageFile and save as ImageField
I am using Python 2.7 Django 1.7 and TreePoem 1.0.1 (https://github.com/YPlan/treepoem) , which can generate barcode for given string. I want to save result of treepoem.generate_barcode to ImageField. I have a method: class SomeModel(models.Model): image = models.ImageField(null=True) def save_barcode_to_db(request): text = some_data_from_db(request) image = treepoem.generate_barcode(barcode_type='pdf417', data=result_as_string, options={}) # This is an instance of `PIL.EpsImagePlugin.EpsImageFile` I can do this by saving this file to a disk and loading again, but it is not good solution for this problem. I tried to create tempfile.TemporaryFile but i can't retrieve content from EpsImageFile. How to resolve this problem without storing result file on disk? -
Can't invoke celery task in Django tests synchronously
I'd like to invoke celery tasks synchronously during my Django tests without need to run celery worker. To achieve this I have specified CELERY_ALWAYS_EAGER=True in my settings.py but it doesn't seem to work. So I decided to apply override_settings decorator to specific test that looks like this @override_settings(CELERY_ALWAYS_EAGER=True, BROKER_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True) def test_foo(self): ... Unfortunately, this test still invokes task in my celery worker. What I can be missing? To be specific, I'm using Django 1.10 with Celery 4.0.0. -
How to attach a ForeignKey value in an APIView?
Im using Django 1.10 and Django Rest Framework to build an app. I want to know the "right" way to create a data object and, in the creation process, attach another object as a foreign key. Consider the following code: #MODEL class MyModel(models.Model): owner = models.ForeignKey(User) # other vars #VIEW class CreateModel(generics.CreateAPIView): queryset = MyModel.objects.all() serializer_class = MyModelSerializer def create(self, request, *args, **args): user = request.user # This User instance needs to be the ForeignKey to MyModel Question: Whats the correct way to populate a models ForeignKey field with data from the request object? -
Populating dictionaries in django
i'm a django beginner and i've got into a problem. I'm trying to make an app that will create 3 football teams. Each player has a score. Those scores are stored with the players in a dictionary called "scoruri". After that the app will copy the maximum value from scoruri to one of these dictionaries: d1 d2 or d3 depending on the sum of the values in each dictionary. My problem is that in a python file, the code works, but when i use it in django, it's not working. So what i want it to do is to get the key, value from scoruri, copy it into one of d1, d2, d3 by maximum value and after i'm poping them one by one. The code is made, maybe any of you will notice a mistake or see something. The code used in python file: import operator echipa1 = {} echipa2 = {} echipa3 = {} scoruri = {'stalone':10, 'ion':6, 'fane':9, 'vali':8, 'cristi':6, 'sobont':9, 'miu':7, 'spiri':3, 'andrei(spiri)':7, 'sket':10, 'dani':8, 'scuipy':9, 'dinaci':10, 'scorp':8, 'max':8, 'vika':9, 'filip':5, 'edy':10} stats = scoruri.copy() for key, value in stats.items(): if not echipa1 or sum(echipa1.values()) <= sum(echipa2.values()) and sum(echipa1.values()) <= sum(echipa3.values()): name, score = max(stats.items(), key=lambda … -
How to solve not null constraints
My models.py file is as following Class Project(models.Model): ABI_choices = ( ('android-tv/x86','android-tv/x86'), ('abi_2', 'google_apis/x86'), ('abi_3','google_apis/x86_64'), ) Screen_size = ( (1,"Landscape"), (2,"Prtarit") ) API_level = ( ('android-22','Lolipop'), ('android-23','kitkat'), ('android-25','marshmellow'), ) CPU_delay = ( (1,0), (2,100), (3,200), (4,300), (5,400), (6,500), ) Network_delay = ( (1,20), (2,30), (3,40), (4,50), (5,60), ) abi = models.CharField(choices = ABI_choices,max_length=100,default=None) screen = models.CharField(choices = Screen_size,max_length=100,default=None) version = models.CharField(choices = API_level,max_length=100,default=None) GSM = models.CharField(choices = CPU_delay,max_length=100,default=None) network_delay = models.CharField(choices = Network_delay,max_length=100,default=None) but when i try to run migration it show me the following error django.db.utils.IntegrityError: NOT NULL constraint failed: app_test_project__new.Network_delay -
Flower Celery format_task error
When trying to configure format_task, as described here, in the string with task.kwargs.pop('credit_card_number') I get an error AttributeError: 'str' object has no attribute 'pop' What's it? I'm using Django 1.9.6, Celery 3.1.23, Flower 0.9.1 -
Why do you need basic or digest authentication in Django?
I am struggling to set up for authentication with apache and mod wsgi in Django. I have a big question mark. It is fundamental question for me before beginning to use basic or digest authentication in apache really. Why do you need basic or digest authentication in Django in the first place? Django has own authentication system. You can manage permissions with user and permission itself in Django. I think there is a clear case that you need this apache authentication. I don't think people put effort to explains how to set up for using apache authentication with mod wsgi in Django manual if you don't need it at all. In Django manual, for example, you could: 1.Serve static/media files directly from Apache only to authenticated users. 2.Authenticate access to a Subversion repository against Django users with a certain permission. 3.Allow certain users to connect to a WebDAV share created with mod_dav. Even after reading this setence and manual repeatly, I can't come up with some situation which need to select using apache authentication for the best option. why do you need to use apache authentication in Django or in Which special situation do you need it? -
django template cannot call javascrpt
I have the following django template and I have defined a button in it so that it calls the javascript function which I added to the page like below. I have the below issues: 1) If I bring the script tags to the header section nothings shows up. 2) If press the button I get the undefined error message. (Uncaught ReferenceError: postData). What am I mssing here? Thank you very much, Mike newproduct.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>New Product</title> </head> <body> <p>Hellow</p> <a href="/">Back</a> <h2>Please enter product details:</h2> <button onclick="postData();">Send Post</button> <form action="http://127.0.0.1:8000/newproduct/" method="post"> <p>{{ message }}</p> {% csrf_token %} {{ form.as_p }} <input type="submit"/> </form> <script src="bower_components/jquery/src/jquery.js" type="text/javascript"/> <script src="scripts/main.js" /> </body> </html> main.js function postData () { $.post('/newproduct', {name:'New Product JS', price:555, }); }; -
Python/Django upload_to creates file as dir
I was working on a custom upload_to, but it seemed to create my file as a directory, or if I changed it, it did not create the file at all. class MyModel(models.Model): def upload_function(self, filename): url = 'files/%s/%s/%s/' % (a, b, c) if not os.path.exists(url): os.makedirs(url) return '/'.join([url, filename]) file = models.FileField(upload_to=upload_function) The a, b and c are fields in the model, which I did not show. This does in fact create the directories, but not the filename in the directory. -
Django Feed 'NoneType' object has no attribute 'title'
feed.py: from django.contrib.syndication.views import Feed from article.models import Article class RSSFeed(Feed): title = "RSS feed - article" link = "feeds/posts/" description = "RSS feed - blog posts" def items(self): return Article.objects.order_by('-date_time') def title(self,item): return item.title def item_pubdate(self,item): return item.add_date def item_description(self,item): return item.content urls.py: from django.conf.urls import url from . import views from article.feed import RSSFeed urlpatterns = [ ... url(r'^feed/$',RSSFeed(),name="RSS"), ] article.models.py: from django.db import models from django.core.urlresolvers import reverse # Create your models here. class Article(models.Model) : title = models.CharField(max_length = 100) category = models.CharField(max_length = 50, blank = True) date_time = models.DateTimeField(auto_now_add = True) content = models.TextField(blank = True, null = True) def __str__(self): return self.title def get_absolute_url(self): path = reverse('detail', kwargs={'id':self.id}) return "http://127.0.0.1:9000%s" % path Error_info: AttributeError at /feed/ 'NoneType' object has no attribute 'title' It is said that in feed.py the parameter item in the function of title(self,item) which returns item.title does not have the attribute title. How can I resolve this problem? -
How to save forms field in django
i have some fields in my django models. class Product(models.Model): user=models.ForeignKey(User) product_name = models.CharField(max_length=50) product_cost = models.IntegerField(default=0,null=True, blank=True) product_description = models.TextField(null=True, blank=True) quantity = models.IntegerField(default=0,null=True, blank=True) product_image = models.FileField(upload_to='images/',blank=True,null=True,) coupon_code = models.CharField(max_length=50) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.product_name or u'' when i use form to save all the data from front end in my database i can do this. class DocumentForm(forms.ModelForm): class Meta: model = Product fields = ('user','product_name','product_image','product_cost','product_description','product_description','coupon_code') Problem is this i don't want to allow user to fill user data from front-end.when user save data it save request.user to user. I am new to work with forms so facing some issues. Please help me how can i do this. Thanks in advance. -
Django attaching multiple events to a model
Consider I have a model called 'Pub'. What I want is: instances of Pub will have multiple events i.e. Pub A will have three events (events like say rock concert on 23rd June etc. name and date are important), Pub B will have 2 events and so on. Later on frontend I want to retrieve all available pubs on a specific date (i.e. pubs which do not have any event on a specific date). How do I code this in my backend? I though of creating a separate Event model taht has event_name and date as parameters. This Event I could use as a foreign key in my Pub model. Will it be a correct approach? Or any other efficient way of doing this keeping in mind what I want to achieve on my frontend? Also, what data types will I use to store such events? -
custom validation in django admin breaks datetime widget
I have a Django model that has a start and end date. The end date can be null and if the model is active it is treated as o ongoing. Each instance of the model has a field foo which is generated by a dynamic list. Foo is not unique across instances however two instances with the identical foo fields cannot be active at the same time. The database I am using is PostgreSQL, and afaik this cannot be enforced at the database level. My choice was then to enforce this at the admin level. When adds a new instance of my model I wanted to validate that there were no conflicting instances at that point and raise a validation error. When I was going to test this locally the datetime widget is not displayed at all, only a textbox. My question(s) are is this the best way to achieve what I want and if so why is the datetime widget missing and how can I get it back? code snippet: class MyModelAdmin(admin.ModelAdmin): list_display = ['name', 'foo', 'active', 'created', 'started', 'ended'] list_editable = ['name', 'active', 'ended'] def formfield_for_dbfield(self, db_field, *args, **kwargs): if db_field.name.lower() == 'foo': choices = sorted(some_dynamic_list) db_field.choices = …