Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Keyword Not Passing in Function
I am working with django models. I want to pass a model field as a variable. Given my function: from django.models import models def updatetable(value, fieldtitle, tablename, uid, refname): workingobj = tablename.objects.get(refname=uid) currentvalue = getattr(workingobj, fieldtitle) setattr(workingobj, fieldtitle, currentvalue + value) workingobj.save() return I have tried: updatetable(len(sr), 'posts_added', managementmetrics, startdtg, refname=update_dtg_start) updatetable(len(sr), 'posts_added', managementmetrics, startdtg, refname='update_dtg_start') and even updatetable(len(sr), 'posts_added', managementmetrics, startdtg, {refname:update_dtg_start}) I get the error: Cannot resolve keyword 'refname' into field. Choices are: length_of_update, update_dtg_finish, update_dtg_start I've tried switching out refname for **kwargs but still can't seem to get it to take the field value. -
"python-social-auth" or "django-social-auth"
I am new in social networks. I have a project on django (v1.10.1). I'm trying to add authorization. What better to use "python-social-auth" or "django-social-auth"? -
How to re-render django template code on AJAX call
I have a view which sends paginated object (on a queryset) to a template, which I further render in template as a table. What I am trying to do is on clicking a page number on pagination bar on template, it should make an ajax call to get paginated output for that page number and update the content of table with it dynamically. View: def accounts(request): #Including only necessary part accounts_list = Accounts.objects.all() paginator = Paginator(accounts_list, 25) page = request.GET.get('page') try: accounts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. accounts = paginator.page(1) except EmptyPage: # If page is out of range, deliver last page of results. accounts = paginator.page(paginator.num_pages) context['accounts'] = accounts return render(request, template, context) Template loads this as: {% if accounts %} <table id="acc"> <tr> <th>Field 1</th> ... <th>Field N</th> </tr> {% for item in accounts %} <tr> <td>{{ item.field1 }}</td> ...<!-- Some complex logic with template tags too in here --> <td>{{ item.fieldN }}</td> </tr> {% endfor %} </table> {% endif %} Now for pagination bar, I am using Bootpag's library, and I can render stuff as: $('.pagination_top').bootpag({ /*bootpag logic here */ }).on("page", function(event, num){ //$.ajax loading here where I … -
Django check if model has related object before deleting the model
After looking for a way to check if a model instance can be deleted in django , i came across many sample, but was not working as expected. Hope this solution can help. Let start by creating an Abstract model class which can be inherited by other model class ModelIsDeletable(models.Model): name = models.CharField(max_length=200, blank=True, null=True, unique=True) description = models.CharField(max_length=200, blank=True, null=True) date_modified = models.DateTimeField(auto_now_add=True) def is_deletable(self): # get all the related object for rel in self._meta.get_fields(): try: # check if there is a relationship with at least one related object related = rel.related_model.objects.filter(**{rel.field.name: self}) if related.exists(): # if there is return a Tuple of flag = False the related_model object return False, related except AttributeError: # an attribute error for field occurs when checking for AutoField pass # just pass as we dont need to check for AutoField return True, None class Meta: abstract = True Example So let say we have three model Organization and Department and StaffType So many Department can be in an Organization And an Organization has a particular StaffType class StaffType(ModelIsDeletable): pensionable = models.BooleanField(default=False) class Organization(ModelIsDeletable): staff_type = models.ForeignKey(to=StaffType) class Department(ModelIsDeletable): organization = models.ForeignKey(to=Organization, to_field="id") so let say after adding some information you want to … -
How do I change my weblate site url
I installed my own weblate server somewhere, then I switched my nginx configuration to a domain name. I went into weblate's django admin, in sites section and updated the site entry to point to the right location. After doing this, urls to projects were still using old url. -
Split CSV file using Python shows not all data in Excel
I am trying to dump the values in my Django database to a csv, then write the contents of the csv to an Excel spreadsheet which looks like a table (one value per cell), so that my users can export a spreadsheet of all records in the database from Django admin. Right now when I export the file, I get this (only one random value out of many and not formatted correctly): What am I doing wrong? Not sure if I am using list comprehensions wrong, reading the file incorrectly, or if there is something wrong with my for loop. Please help! def dump_table_to_csv(db_table, io): with connection.cursor() as cursor: cursor.execute("SELECT * FROM %s" % db_table, []) row = cursor.fetchall() writer = csv.writer(io) writer.writerow([i[0] for i in cursor.description]) writer.writerow(row) with open('/Users/nicoletorek/emarshal/myfile.csv', 'w') as f: dump_table_to_csv(Attorney._meta.db_table, f) with open('/Users/nicoletorek/emarshal/myfile.csv', 'r') as f: db_list = f.read() split_db_list = db_list.split(',') output = BytesIO() workbook = xlsxwriter.Workbook(output) worksheet_s = workbook.add_worksheet("Summary") header = workbook.add_format({ 'bg_color': '#F7F7F7', 'color': 'black', 'align': 'center', 'valign': 'top', 'border': 1 }) row = 0 col = 0 for x in split_db_list: worksheet_s.write(row + 1, col + 1, x, header) -
401 error for tastypie for api_client
Hi I am trying to write a test case for my app. URL = '/api/project/'. I have enabled get, post and put methods along with authentication. But still i get 401 error for post request class EntryResourceTest(ResourceTestCaseMixin, TestCase): class Meta: queryset = Project.objects.all() resource_name = 'project' allowed_methods = ['get', 'post', 'put'] authentication = Authentication() authorization = Authorization() def setUp(self): super(EntryResourceTest, self).setUp() # Create a user. self.username = 'daniel' self.password = 'pass' self.user = User.objects.create_user(self.username, 'daniel@example.com', self.password) def login(self): return self.api_client.client.login( username=self.username, password=self.password) def get_credentials(self): return self.create_basic(username=self.username, password=self.password) def test_post_list(self): self.login() req_get = self.api_client.get('/api/project/', format='json', authentication=self.get_credentials()) # -> get works and i get 200 status code req_post = self.api_client.post('/api/project/', format='json', data=self.post_data, authentication=self.get_credentials()) I run the test case using following command , and here get works fine but not the post request. And get request works even if i don't pass authentication parameter as it uses the default login which i have defined in self.login() django-admin test myapp.api.project.tests -
How to add checkboxes to a list in html/django
I am developing a django/html application where I have a table of data. I have to make a way for my users to delete multiple rows in a table. Therefore, I have decided to add checkboxes in a list. I know that I can include it as <tr> <td><input type="radio" name="item1" /></td> <td>Item1</td> </tr> <tr> <td><input type="radio" name="item2" /></td> <td>Item2</td> </tr> for each item. Then in the end, I can add: <input type="submit" name="delete" value="Delete Items" /> But this will mean that I will have to enclose my list within a <form></form> Is this an ethical way of doing it? I want to add this feature to my site but I also want to do it in the most professional way. Can anyone tell me if I am going in the right direction? -
Sending byte response from Django API to JAVA code
I have a Django API which created an excel.I want to send the created excel as a byte stream to JAVA code. views.py: def generate_utilisation_report(request): response = get_utilisation_report(request) print("Printing response and type of response in view") print(response, type(response)) return response models.py: def get_utilisation_report(request): output = io.BytesIO() workbook = Workbook(output, {'in_memory': True}) workbook.close() output.seek(0) response = HttpResponse(output.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = "attachment; filename=ABC.xls" return response The print statement in views.py gives this: <HttpResponse status_code=200, "application/vnd.ms-excel"> <class 'django.http.response.HttpResponse'> How can I send a byte stream to JAVA code? -
How to authenticate user for a specific object rather than whole class in django?
I am working on making an app to add clubs in website. This is my model.py file from django.db import models from stdimage import StdImageField # Create your models here. class Club(models.Model): ClubName = models.CharField(max_length=200) ClubLogo = StdImageField(upload_to='club_logo', variations={'thumbnail':(150, 200, True)}) ClubDetails = models.TextField() ClubStartDate = models.DateField() def __str__(self): return self.ClubName class Notice(models.Model): NOTICE = 'NOTICE' UPDATES = 'UPDATES' EVENTS = 'EVENTS' NOTICE_IN_CHOICES = ( (NOTICE, 'Notice'), (UPDATES, 'Updates'), (EVENTS, 'Events'),) NoticeType = models.CharField( max_length=20, choices=NOTICE_IN_CHOICES, default=NOTICE) NoticeTag = models.CharField(max_length=30) NoticeStartDate = models.DateField(auto_now_add=True) NoticeEndDate = models.DateField() NoticeFile = models.FileField(default='#', upload_to='notice/%Y/%m/%d') NoticeContent = models.TextField(default='NA') NoticeClub = models.ForeignKey(Club) def __str__(self): return self.NoticeTag class Members(models.Model): MemeberName = models.CharField(max_length=200) MemberImage = StdImageField(upload_to='member_photo', variations={'thumbnail':(150, 120, True)}) MemberEmail = models.EmailField() MemberClub = models.ForeignKey(Club) def __str__(self): return self.MemeberName Now when i am making users via django's inbuilt admin panel i have option to give permission to users to change member of any club but i want to give access to change members of only that particular club which he is member of. As you can see in this picture that all club are in dropdown option when someone who has access to add notices adding otices. But instead of that i want only one option in the … -
Django filter query week day wise(Friday to Thursday consecutively in a month)
HI Guys I have a datas in the model like this Date Day Amount ------------------------------ 01/09/2016 Thursday 2500 02/09/2016 Friday 300 03/09/2016 Saturday 600 04/09/2016 Sunday 7500 05/09/2016 Monday 9800 06/09/2016 Tuesday 2800 07/09/2016 Wednesday 3600 08/09/2016 Thursday 580 09/09/2016 Friday 352 10/09/2016 Saturday 950 11/09/2016 Sunday 780 12/09/2016 Monday 650 13/09/2016 Tuesday 440 14/09/2016 Wednesday 25 15/09/2016 Thursday 39 16/09/2016 Friday 500 17/09/2016 Saturday 51 18/09/2016 Sunday 65 19/09/2016 Monday 99 20/09/2016 Tuesday 350 21/09/2016 Wednesday 280 22/09/2016 Thursday 782 23/09/2016 Friday 98 24/09/2016 Saturday 785 25/09/2016 Sunday 965 26/09/2016 Monday 1500 27/09/2016 Tuesday 3650 28/09/2016 Wednesday 85 29/09/2016 Thursday 70 30/09/2016 Friday 980 I want to write a filter query in django which filters the data like Sum of Friday to Thursday consecutively following next, of every month. i.e sum(02/09/2016(Friday) To 08/09/2016(Thursday)) , sum(09/09/2016(Friday) To 15/09/2016(Thursday)) and so on.... -
Django 1.9 pushing our code to go live today but have static directory issue
We are pushing our code up to go live today, and before we do I need to figure out where to put my static files. I have in the project directory a folder called static. Inside I have an admin and an image folder. When looking through the docs it looks like these should not be placed inside the actual project. But instead should be outside the project. These are the files that come with django when running the code python manage.py collectstatic. But for the css I have used on the site itself, it looks like I should have another folder called static, to place it all in. So my question is: Should I have a folder in my project directory called static where I house my css, and should I also have the collectstatic files folder, but held elsewhere? -
How do you convert normal time to Django time?
I have program that enables users choose day(s) in which they would want to be sent notifications. days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] time_otd = ['1am', '2am', '3am', '4am', '5am', '6am', '7am'] Assuming a user selects mon and 6am, how do you convert it to Django TimeField so that the program sends notification to the user every Monday by 6am? -
how to collapse/expand a django-mptt list ideally using CSS and no JS in template
I need to collapse/expand a django-mptt list ideally using CSS (and no JavaScript) in my template: Following guidance from http://django-mptt.github.io/django-mptt/templates.html, I got a basic view, and have consulted the below SO posts: SO#6037469:show-children-nodes-depending-on-selected-parent only seems to work at the first hierarchical level(I'd prefer for this to be recursive down the list. SO#26334107:expand-collapsible-list-of-objects threw an error: Could not parse the remainder: '==0' from 'node.level==0' Wonder if someone could please post an elegant CSS solution to templating such lists in a collapsible/expandable format? -
Python / Django: sending emails resulting in 535 (for gmail email works)
For sending the form I have a script in AJAX, which runs the e-mail trigger function. The following error is returned: EMAIL_HOST='mail.example.com' EMAIL_HOST_USER='no-reply@example.com' EMAIL_HOST_PASSWORD='xxx' EMAIL_PORT='25' For sending the form I have a script in AJAX, which runs the e-mail trigger function. The following error is returned: SMTPAuthenticationError at /vendas/contato/ (535, 'Incorrect authentication data') Request Method: POST Request URL: http://example.com/vendas/contato/ Django Version: 1.3 Exception Type: SMTPAuthenticationError Exception Value: (535, 'Incorrect authentication data') Exception Location: /usr/local/lib/python2.7/smtplib.py in login, line 622 Python Executable: /usr/bin/python Python Version: 2.7.9 Python Path: ['/home/example/pythonenv/lib/python2.7/site-packages', '/usr/local/lib/python2.7/site-packages/setuptools-12.1-py2.7.egg', '/usr/local/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages', '/home/example/pythonenv/lib/python2.7/site-packages', '/home/example/src/myproject'] Server time: Seg, 26 Set 2016 17:08:45 -0300 After some testing, I found that when sending a message to a gmail email for example, it is sent normally, other areas such as example.com or example.net result in error 535. Does anyone have any idea what might be causing this? -
Django: UUIDField has no attribute uuid4
Here is my model from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class PiO(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # surrogate person = models.ForeignKey(Person, on_delete=models.PROTECT, max_length=25, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) # for the various organization types object_id = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) # the uuid of the specific org content_object = GenericForeignKey('content_type', 'object_id') object_id = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) # the uuid of the specific org Here is my traceback AttributeError: 'UUIDField' object has no attribute 'uuid4'. Note this is specifically referencing the object_id field, not the uuid (pk) field. As a test, I commented out the object_id field. I did not get an error for not having an object_id field, and the check went on to a new error 12 lines away. I googled the exact phrase and got No results found for "AttributeError: 'UUIDField' object has no attribute 'uuid4'". What I did looks consistent with the docs to me. https://docs.djangoproject.com/en/1.10/ref/models/fields/#uuidfield What am I missing? Does the presence of the generic foreign key and or the contenttype have anything to do with it? Python 2.7.12 Django 1.9 Ubuntu 16.04 Postgresql 9.4.8 -
Python Multiprocessing Process isn't getting killed even after the task is done
I have written a python script which will read from an Amazon SQS and create as many parallel processes as user wanted. It inherits Django BaseCommand, and this is the code. def handle(self, *args, **kwargs): self.set_up(*args, **kwargs) process_queue = JoinableQueue(self.threads) process_pool = Pool( self.threads, self.worker_process, (process_queue,) ) is_queue_empty = False while not is_queue_empty: message = self.get_next_message() if len(message) == 0: is_queue_empty = True else: process_queue.put(message[0]) process_queue.join() raise CommandError('Number retries exceeded retry limit') def worker_process(self, process_queue): while True: message = process_queue.get(True) message_tuple = (message) self.process_message(message_tuple) process_queue.task_done() This is working fine and all the processes are getting killed once the tasks are done. But not for one particular activity, where I use boilerpipe to extract some data. from boilerpipe.extract import Extractor extractor = Extractor(extractor='DefaultExtractor', html=soup_html) extractor.getText() When I looked into the boilepipe code I could see that, in the constructor of Extractor there is this code, lock = threading.Lock() class Extractor(): def __init__(): # code try: # code lock.acquire() # code finally: lock.release() full code is this Why the processes are not getting killed,Is there something wrong with my way of doing multi processing. Or is this thread locking is creating the issue (I am not all sure, just thinking about all … -
foreign key constraint not letting delete row from table in django
I create below model in Django. class UserModel(AbstractBaseUser): # custom user class SYSTEM = 0 TENANT = 1 parent_type_choices = ( (SYSTEM, 'System'), (TENANT, 'Tenant') ) sys_id = models.AutoField(primary_key=True, blank=True) parent_type = models.PositiveIntegerField(choices=parent_type_choices, null=False, blank=False) parent_sys_id = models.ForeignKey('tenant.TenantModel', on_delete = models.SET_NULL, null=True, blank=True) last_name = models.CharField(null=False, blank=False, max_length=40) # and few more rows.... Here parent_sys_id is a foreign key. I set on_delete = models.SET_NULL, which means if I delete any entry from TenantModel (lets say entry1) then column parent_sys_id in all rows having parent_sys_id as entry1 should be set to null. I am right here? If yes- Then here is next question. If I try to delete an entry from tenants table from mysql then it is throwing me below error. mysql> delete from tenants where sys_id = 1; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`sanstha_db`.`clients`, CONSTRAINT `Clients_tenant_sys_id_id_52191b87_fk_Tenants_sys_id` FOREIGN KEY (`tenant_sys_id_id`) REFERENCES `tenants` (`sys_id`)) Here is the table structure. mysql> show create table users\G *************************** 1. row *************************** Table: users Create Table: CREATE TABLE `users` ( `password` varchar(128) NOT NULL, `last_login` datetime DEFAULT NULL, `sys_id` int(11) NOT NULL AUTO_INCREMENT, `parent_type` int(10) unsigned NOT NULL, `last_name` varchar(40) NOT NULL, `first_name` varchar(40) NOT … -
ID/Class/ng-click does not work in dynamic html table generated with python Django
here is my code : def html_firm_table(result_set): result_set = {v['ID']:v for v in result_set}.values() html_table = '<table><tr><th>NAME</th><th>FIRM-CODE</th></tr>' for results in result_set: html_table = html_table+'<tr><td ng-model = "firm-details.NAME">'+results['NAME']+'</td><td ng-model = "firm-details.CODE" id="CODE">'+results['CODE']+'</td>' html_table = html_table+'<td ng-click = "showDetails()"><a name="clickable" target="_blank" id="clickable">view more info</a></td></tr>' html_table = html_table+'</table>' return html_table HTML table is successfully viewng at webpage, but when I click 'view more information',ng-click does not call angularjs function showDetails(), also only onclick method of jquery is working on it, even the element's ID or class is returned blank values or no values when I tried with an onclick jquery method named as ShowDetails(). I want to fetch value of CODE when I do click on 'view more information'. To Add into the information, I have also tried to pass JSON as response to angular via HttpResponse to convert it into an HTML table at client site, but it does not succeed as well. you can see code of that at return mongodb search results in a list to angular js Django Please suggest me an appropriate solution to this problem. Thanks !! -
Bold text with asterisks
In my Django project I want to make text bold if asterisks * are there at the start and end of text, the same feature we have here on Stack Overflow. Although I convert ** to <b>, due to output escaping it becomes &lt;b&gt;. What is the right approach to achieve this? -
Form wizard with ModelForms having parameters in __init__
I am using python 2.7, Django 1.9.4 on Ubuntu 14.04. I have been struggling with django-formtools (specifically form wizard) for quite a few days now. The scenario is as follows: The form wizard is just a 2 step process: 1st step: I have a ModelForm based on a Model. The form's __init()__ requires a parameter (the id of logged in user which is an integer) 2nd step: A simple check box that asks user of he/she wants to submit the form. The source for forms.py: from django import forms from publishermanagement import models from localemanagement import models as locale_models from usermanagement import models as user_models class AddPublisherForm(forms.ModelForm): def __init__(self, user_id, *args, **kwargs): super(AddPublisherForm, self).__init__(*args, **kwargs) permitted_locale_ids = ( user_models .PublisherPermission .objects .filter(user=user_id) .values_list('locale', flat=True)) self.fields['locale'].queryset = ( locale_models .Locale .objects .filter(pk__in=permitted_locale_ids)) class Meta: model = models.Information fields = ( 'channel_type', 'current_deal_type', 'locale', 'name', 'contact_primary', 'contact_auxiliary', 'website', 'phone', 'is_active',) class ConfirmPublisherForm(forms.Form): confirmation = forms.BooleanField( label="Check to confirm provided publisher data") I overwrote the get_form_instance() in line with the suggestions in various forums including Stack Overflow. Information is the Model class based on which AddPublisherForm is created. views.py from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from publishermanagement import models as publisher_models … -
Tree view in django template
I try to create simple TODOList app. Where you can create Project, then create tasks for project, subtasks for tasks and subtasks. I create a template to show task: <li class='task'> <div class="collapsible-header" id="task-name"> {{task.title}}</div> <div class="collapsible-body" data-task-pk='{{task.pk}}' id="task-details"> {% include 'ProjectManager/views/control-block.html' %} <p>{{task.description}}</p> <ul class="collapsible popout" data-collapsible="expandable" id="subtasks"> {% for sub_task in task.subtasks.all %} {% include "ProjectManager/views/task_view.html" with task=sub_task %} {% endfor %} </ul> </div> </li> You can see i try to create a list of subtask, by using this template recursively, but I got an error: 'RecursionError' object has no attribute 'token' I found some informations, that i should use variable to store template name, like this: <li class='task'> <div class="collapsible-header" id="task-name"> {{task.title}}</div> <div class="collapsible-body" data-task-pk='{{task.pk}}' id="task-details"> {% include 'ProjectManager/views/control-block.html' %} <p>{{task.description}}</p> <ul class="collapsible popout" data-collapsible="expandable" id="subtasks"> {% for sub_task in task.subtasks.all %} {% with node=sub_task template_name="ProjectManager/views/task_view.html" %} {% include template_name with task=node%} {% endwith %} {% endfor %} </ul> </div> </li> I got an error: maximum recursion depth exceeded But at start I wrote wrong: {% with node=**subtask** template_name="ProjectManager/views/task_view.html" %} And template display list of subtasks with empty elements (without task.title and description). Then I tried to put some if condition: <li class='task'> <div class="collapsible-header" id="task-name"> {{task.title}}</div> … -
How can I check logs in AWS?
How can I check the logs in Amazon web service? I am using Linux , Nginx , MySQL , Django . I read so many questions on StackOverflow that check logs in \var\log\nginx\ views.py def index(request): print request.POST.get('type','') return JsonResponse({'status':'true'} I want to check where print statement prints POST data ? Any helpful suggestion will be appreciated . -
array is not JSON serializable
First array is created in this manner: a = np.arange(9) a.shape = (3,3) a[:,0] = 1 a[:,1] = resultP a[:,2] = resultN The second array is created in this manner: array = ([ ['Jan', 0, -12], ['Feb', 12, -12], ['Mar', 12, -20] ]); I have returned both to my template using: context = { 'array': json.dumps(array), 'a' : json.dumps(a), I have returned them individually. When I return array, it works but when I return a it returns this error: array([[ 1, 50, 0], [ 1, 100, 0], [ 1, 25, 0]]) is not JSON serializable What am I doing wrong here? Any help or direction would appreciated, Thanks -
How can I add class into all fields of my form?
How can I add class form-control into all fields of my form? class AddOfferForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddOfferForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.form_method = 'post'