Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mutators for Django
I'm looking for a Django mutator wich will translate True and False to Yes or No before it will be passed to the template. I've build a very generic form-app and this is very annoying not to have a mutator (which can edit a model variable in the view in Laravel). I hope you have good suggestions! -
what's the meaning of using patterns in Django urls
in my django project, i find the project urls.py resolve urls directly urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test/', include('test.urls')), ] but i find the app urls.py solution always use urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^new$', views.new, name='new'), ) when i try to change app's urls.py to urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^new$', views.new, name='new'), ] or urlpatterns = patterns('', url(r'^$', views.index, name='index'), ) urlpatterns += patterns('', url(r'^new$', views.new, name='new'), ) also works.so i want to know the meaning of using patterns and which one is better -
i am getting error django and GoogleOAuth2
i am trying to login in google with Oauth and django Exception Type: TypeError Exception Value:unsupported operand type(s) for +: 'NoneType' and 'int' -
django celery and main app on one core cpu vps server?
I'm new in celery. Can i run django celery and main app on one core cpu vps server? I need update infornation at website each hour from queue wich will keep in Radis cache. And also I need make some calculations(not so hard but it takes time) in background, result of each I want put to queue. The question is, will I able to do it all on the single core? -
Order by operation cost
I have a 73 GB big table table1 . Most of my queries involve fetching the latest 100 entries in the table which satisfy some condition. I am using django as my backend for this web app. My query is something similar to this : table_object = table1.objects.filter(first_filter_field=6) order_by = '-created_on' table_object = .filter(not_null_field__isnull=False).order_by(order_by) table_object = table_object[offset:(offset + limit)] I think this query takes too much time . 1)How can i measure the time taken by this query. (in Postgres) 2)How can i improve its performance . I just need latest 100 creatives which satisfy some condition (basically where statement addition in normal query) . I am new to djanogo, so please be descriptive and give links to the related material wherever possible. -
Register View as a Section in Django Admin Panel
I have some problem with my admin panel. I need to add some view as a section there, without models but I cannot register it there using admin.site.register. I don't want to install django-adminplus. Is there a way to register such a view in my admin panel? Or something else... Could I unpack django-adminplus and wield it in my project? Thanks there. -
Check Items for checkbox checked in Django
I am working on a view. I am trying to create a html file that will display a form based on the records model. In the html file I added code that will display all of the members with the group. Next to each of the members, there is a checkbox. In the view.py file, I want to go through each of the members and if the checkbox is checked, I want to create a new transacition object and save it to the database if it is infact checked. I am getting an error and it looks like this... ERROR: KeyError at /23/addRecord/ 'omar' Request Method: POST Request URL: http://127.0.0.1:8000/23/addRecord/ Django Version: 1.8.6 Exception Type: KeyError Exception Value: 'omar' Exception Location: C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in addRecord, line 237 Python Executable: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Server time: Mon, 3 Jul 2017 07:02:20 +0000 Traceback Switch to copy-and-paste view C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars C:\Users\OmarJandali\Desktop\opentab\opentab\tab\views.py in addRecord username = cd[member.user.username] ... ▶ Local vars Request information GET No GET data POST Variable Value csrfmiddlewaretoken 'vIg5KKWVNpoc2ijkwmBB9I28aDt7QOSA' split '2' omar 'checked' hani 'checked' submit 'submit' Here are the files that i … -
Django 1.8 : ImportError: No module named 'allauth'
I am working in Django 1.8 and python 3.5. I tried to installallauth by following the guide here, but as soon as I run python3 manage.py runserver I got ImportError: No module named 'allauth' I tried to search the web, but I am unable to resolve it. Can anyone please help me with it. -
Putting a search bar on admin model Python/Django
I am new with python and django, i want to know how can i implement the admin search bar on my project model? i notice that the user model has it by default. My code is below, after the makemigration command still no search bar i think i am missing something. sorry for the noob question. class Todo(models.Model): search_fields = ('title', 'text', 'created_at',) title = models.CharField(max_length=200) text = models.TextField() created_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.title -
Python-Django utf-8 csv.writer
im using python csv library for exporting my models into a csv file in django. codes are like this : import csv from django.http import HttpResponse def some_view(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(response) writer.writerow(['First row', 'Foo', 'Bar', 'Baz']) writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) return response My problem : in my database i have some persian characters that just works with utf-8 encoding format , so when i open generated csv file in excel the persian characters not shown correctly. -
How does Pyscada connect with Modbus Device?
I am not able stabilize communication between Pyscada and Mpdbus device? Pyscada is using Pymodbus to send dataenter link description here -
Django Admin - Model Add/Edit Page is blank
I am relatively new to Django and I'm having issues getting the admin view on one of my Models showing up properly. I have successfully listed out all of the "Game Class" objects (listed as "Specialist Cards") - but when I select one to edit OR I select to add a new record, the resulting page is blank as below: I don't have this issue with any of my other Models. For reference, my models.py looks like this: I have tried searching through various other SO answers and have not yet come up with a result in fixing this issue. The model is registered in my admin.py - and I can see all of the items listed correctly in my Admin view, I just do not have any facility to add or edit via the Django Dashboard (as per these screenshots). Any help is greatly appreciated! -
'Lower' object has no attribute 'partition'
There is a model that extends django-polymorphic: class FooQuerySet(PolymorphicQuerySet): .. now when trying to use Django's Lower to make sure order_by is case insensitive qs.order_by(Lower('name')) getting: *** AttributeError: 'Lower' object has no attribute 'partition' Question: is it possible that PolymorphicQuerySet is causing this error (since it works fine on regular querysets)? -
Can `clean` and `clean_fieldname` methods be used together in Django ModelForm?
I am trying to implement registration with email and phone on a website. A user can register with either phone or email or both. If a user keeps both phone and email field empty, a ValidationError is raised, "You cannot leave both phone and email fields blank. You must fill at least one of the fields." We have separate clean methods for username, email, phone, password. I do not want to implement the above-mentioned validation on save(). I don't want to define a clean method in the User model, either. I have written tests for this form, and they pass. But what errors could possibly arise if I use both clean and clean_fieldname together? Could it become a problem when working with views? I have 3 questions: Can I use both clean_fieldname and clean methods in a form? In what other way can I make sure that user registers with at least phone or email? How do clean() and validate() works? I have read django documentation, but I don't understand it completely. Here's the code I implemented. class RegisterForm(SanitizeFieldsForm, forms.ModelForm): email = forms.EmailField(required=False) message = _("Phone must have format: +9999999999. Upto 15 digits allowed." " Do not include hyphen or … -
Convert excel file to pdf in django
I want to convert excel file to pdf in django. I have found this code, from openpyxl import load_workbook from PDFWriter import PDFWriter workbook = load_workbook('fruits2.xlsx', guess_types=True, data_only=True) worksheet = workbook.active pw = PDFWriter('fruits2.pdf') pw.setFont('Courier', 12) pw.setHeader('XLSXtoPDF.py - convert XLSX data to PDF') pw.setFooter('Generated using openpyxl and xtopdf') ws_range = worksheet.iter_rows('A1:H13') for row in ws_range: s = '' for cell in row: if cell.value is None: s += ' ' * 11 else: s += str(cell.value).rjust(10) + ' ' pw.writeLine(s) pw.savePage() pw.close() But it does not import PDFWriter and it is not a django module so cant be installed using pip install. How can I convert the file in pdf by any way? -
django model admin add form gets stuck
Consider this @admin.register(Personal, site=admin_site) class PersonalAdmin(admin.ModelAdmin): form = ChangePersonalForm add_form = AddPersonalForm def get_form(self, request, obj=None, **kwargs): if not obj: self.form = self.add_form return super(PersonalAdmin, self).get_form(request, obj, **kwargs) The first time you try creating or changing an object, it will work fine. But, after you create the object, every time you try to change an object, you will get the add_form instead of the form I fixed that by adding an else block @admin.register(Personal, site=admin_site) class PersonalAdmin(admin.ModelAdmin): form = ChangePersonalForm add_form = AddPersonalForm def get_form(self, request, obj=None, **kwargs): if not obj: self.form = self.add_form else: self.form = self.form return super(PersonalAdmin, self).get_form(request, obj, **kwargs) As if there was some sort of class caching. Anyone knows why? -
Store Transaction Logs on Blockchain
Currently I've a Prepaid Wallet in Latin America. So far we work as a centralized alternative for SMS/App Micro-Payments. Users needs to make a deposit to our bank accounts and minutes later they can use it and transfer it to another user. So far I've encountered with the BlockChain technology. And I would like instead for storing the data of user transactions let them create a wallet (sha-256) account; And log transactions this way users wont deposit their money to our bank accounts but load money on authorized establishments. But handle their local currency. No interest on working with other currencies. So this users can store their money on their wallet in their local currency. So money that is digitalized is carried on their wallet. but exists in real life. By this I mean.. that money gets digitalized as someone buys this digital currency exchange. so no money exists in digital but only for transaction. My Knowledge in programming is: Redis Python Django PostgreSQL -
Pass object from admin to view to manipulate with javascript django
I need to pass an object from admin.py to the view so as to manipulate using javascript. Particularly I need to pass several object {lat: x, long: y} and manipulate with javascript. One solution is to put the list of objects as display object and hide with CSS and then parse with Javascript, however, this is not a nice solution. Any piece of advice is welcoming. -
Django AttributeError ('tuple' object has no attribute '_committed')
I'm downloading a image from the web and then setting that image to the imageField, but i get this error. 'tuple' object has no attribute '_committed' view if form.is_valid(): instance = form.save(commit=False) url = 'http://image.jpg' image = urllib.request.urlretrieve(url, 'name') instance.image = image return redirect() model def upload_location(instance, filename): filebase, extension = filename.split(".") return "%s/%s.%s" %('name', uuid.uuid4(), extension) class Image(models.Model): image = models.ImageField( upload_to=upload_location, null=False, blank=False, ) -
django - local variable 'results' referenced before assignment
I want to include my variable "results" in the context but it's giving me the "local variable error..." How can I rework my logic to be able to use that variable in my template? Here's my view: @login_required def search(request): if request.method == 'GET': form = Search(request.GET) if form.is_valid(): query = request.GET.get('query') results = Book_Product.objects.filter(book_title__icontains=query) else: form = Search() return render(request, 'search.html', {'form': form, 'results':results}) -
delete checked item from database Django
I am trying to delete the selected row when "Delete" button has been selected after the checkbox for the row-to-be-deleted has been checked. I have no idea which part of my code is wrong and cause the particular row wasn't deleted from database when the checkbox has been checked and "Delete" button has been selected. Right now, when the "Delete" button has been selected, i still can see the particular row in my table. (This means that it hasn't been deleted from Database as my table only display data stored in database.) Could anyone please identify any error in my code provided ? add_remove_scholarship.html <input type="submit" name="delete" value="Delete Selected Scholarship" > <form method="POST" action=""> {% csrf_token %} <table id="example" class="display" cellspacing="0" width="100%" border="1.5px"> <tr align="center"> <th style="border-top: none;border-right: none;border-left: none"></th> <th> Scholarship </th> <th> Faculty </th> <th> Open Date </th> <th> Close Date </th> </tr> {% for item in query_results %} <tr align="center"> <td style="border: none;"><input type="checkbox" name="item" value="{{item.doc}}"> <td>{{item.doc}}</td> <td>{{item.faculty}}</td> <td>{{item.openDate}}</td> <td>{{item.closeDate}}</td> </tr> {% endfor %} </table> </form> views.py def scholarship(request, id=None): query_results = [] if request.POST.get('delete'): Scholarship.objects.filter(id__in=request.POST.getlist('scholarship')).delete() return redirect('/hrfinance/lscholarship/') elif request.POST.get('add'): form = ScholarshipForm(request.POST) if form.is_valid(): scholarship = form.save(commit=False) scholarship.save() return redirect('/hrfinance/lscholarship/') else: form = ScholarshipForm() id = … -
Subclassing DecimalField
I'm trying to create a DecimalField subclass, using the code below class PositiveMoneyField(DecimalField): def __init__(self, verbose_name=None, name=None, **kwargs): super().__init__(self, verbose_name, name, max_digits=9, decimal_places=2, validators=[MinValueValidator(Decimal(0.0)), ], **kwargs ) But it give me this error: TypeError: init() got multiple values for argument 'max_digits' Any help is appreciated. Thanks, Eric -
How to RUN Python/Django combined with Apache
I have a running apache/PHP site using XAMPP on my locahost, and i am learning the basics of python/django and have a python manage.py runserver on port 8000, i read about configuring the virtual host on xampp http-vhost.conf but cannot make it work, i just need to run both and somehow remove the port number on my python site, don't know if configuring apache is the best way any advice would be great! My apache site is running using below url. http://localhost/myPHPwebiste My python/django site is running using below url. http://localhost:8000/myPythonwebiste My http-vhost.conf on apache server (i saved my python files inside the htdocs) <VirtualHost 127.0.0.1:8000> DocumentRoot "D:/xampp/htdocs/myPythonwebiste" <Directory "D:/xampp/htdocs/myPythonwebiste"> Options All AllowOverride All Require all granted </Directory> </VirtualHost> My goal is to make my python site run on url below. http://localhost/myPythonwebiste -
Downloading images from web and setting the path to MEDIA_ROOT (django)
How to add file path to the MEDIA_ROOT when downloading a image from the web in a django project. import urllib.request url = 'https://image.jpg' urllib.request.urlretrieve(url, 'name') -
How to correct Django server from loading basic html on web browser instead of standard html?
Django bug Hi, please I'm new to Django, how can correct the basic html display I get when I load admin page, just as shown in the snipshot attached? Thank you.