Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change html layout (list, thumbnails, tiles..) for the same Django View
What is the simplest way to change some html dynamically (i.e. on a button press) to create different layouts for a Django (python) view? I have a view that presents a list of records. And I would like the User to be able to quickly flick between a text list and thumbnail images etc. Thanks! -
class httpresponse results in 405 - django
I am new to django and I am trying to understand class views. In urls.py (main) I have: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('webapp.urls')), ] in webapp folder I have: urls.py (webapp): from django.conf.urls import url from webapp.views import Firstapp urlpatterns = [ url(r'^whatever$', Firstapp.as_view()), ] views.py (webapp): from django.shortcuts import render from django.views import View from django.http import HttpResponse class Firstapp(View): def something(self): return HttpResponse('Yes it works!') As I have said, I am trying to use class views and I would appreciate if you could help me understand why class returns 405 error. Thank you. CMD returns 0 problems. -
Django-filer, Relating a record to a stored image without using Admin (Django)
I have made a script that will convert a CSV into data and insert it into my table. Now this table has a imagefilerfeild, from django-filer. I need to bypass the admin widget and just pass in a primery key or some peice of information that can be used to relate the image to the record. entry.image = Image.objects.get(file='filer_public/e3/83/e383cd94-c28a-485b-8307-f4107698ad1d/keypad-sm-keypad.jpg') Is there a way to assign a record an image within filer without selecting it from the widget in the admin? -
Unable to print array into HTML
I have a program which is pulling data from the database like so. Views.py def final(request): total = [] name = [] k = 0 for i in Question.objects.raw("SELECT name, question1, question2, question3, question4, question5, question6, question7, question8, question9, question10 FROM music_question"): name.append(str(i.name)) total.append(int(i.question1) + int(i.question2) + int(i.question3) + int(i.question4) + int(i.question5) + int(i.question6) + int(i.question7) + int(i.question8) + int(i.question9) + int(i.question10)) return render(request, 'music/final.html', {"totals": total, "names": name, "rows": Question.objects.all()}) From here I'm trying to print into HTML like so final.HTML </body> <script type=text/javascript> data = {{totals}} console.log(data) </script> </html> I can see that the data from the database has returned to the console in Chrome but it won't persist onto the web page and I'm not sure where I'm going wrong. -
Transfer data from a view to another django
Hello. I want to ask how can i recover a data from a form to be treated in other view. this what i want to do -
using grappelli theme in django made some items unable to view due to home bar
while developing a website using django used grappelli theme which helps in changing theme of admin site but in grappelli theme the home bar is blocking the items as shown in second image and i can see those items only if i pull the page little down by mouse what is the solution for it , thank you -
ASP.NET api post nested model
i was a django user and recently transfered to ASP.NET . currently my api post works like this. POST : http://localhost:55974/api/trades/ { "id": 1, "baseProduct": { "id": 1, "productID": "sample string 2", "tags": [ "sample string 1", "sample string 2" ] }, "productDescription": "sample string 2", "images": [ "QEA=", "QEA=" ], "price": 3, "estimatedShippingDate": "2017-03-31T20:41:03.2760924+09:00" } but what i want is to link the existing data with its id something like this. { "id": 1, "baseProduct": 1, "productDescription": "sample string 2", "images": [ "QEA=", "QEA=" ], "price": 3, "estimatedShippingDate": "2017-03-31T20:41:03.2760924+09:00" } you can note that baseProduct has changed to its id. but when i try to do this, i get this error { "Message": "The request is invalid.", "ModelState": { "tradeModel.baseProduct": [ "Error converting value 3 to type 'EodiRoad.Models.BaseProductModel'. Path 'baseProduct', line 2, position 19." ] } } well this worked fine on django so.. i guess that it will have its way on asp.net to.. any possible solutions? -
Django - how many views and templates
I've got some script generating CSV files and I would like to present these data on the web page. I'm new at Django and I'm wondering how I can use Django for my project. Please refer to this scheme https://drive.google.com/open?id=0ByiuoauCCrVrMkg1bHdjMUE4amM. For now in searchengine.py I'm typing prices, sizes and brand manually and running script manually. I'm not going to use models so I need only views and one template. Do I need only one template? I need only one page but with multiple subpages beacuse of pagination. I don't want to display all 200 tiles on one page. How many views do I need? Is one view common for every tile on any subpage? Is any search field or button or pagination elements a separate view or I should create all elements inside one view? Can you point me some exaple of similar simple Django project? -
Import a string value from first loop to second loop in template?
Is it able to import a string value from first loop to second loop in template? In second loop, "mydata.data.room" should be mydata.A.room, mydata.B.room, mydata.C.room and mydata.D.room In dictionary {'mydata': {u'A': {'room': [u'1-1']}, u'B': {'room': [u'1-1', u'1-2']}, u'C': {'room': [u'1-1', u'1-2', u'1-3']}, u'D': {'room': [u'1-1']}} In template {% for data in mydata %} <div id="{{ data }}" class="tab-pane fade"> {% for room in mydata.data.room %} <h3>{{ room }}</h3> <p>Some content.</p> {% endfor %} </div> {% endfor %} -
Django queries: get dictionaries together with model instances
The documentation for .values says .. Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. .. with following the example: >>> Blog.objects.values('id', 'name') <QuerySet [{'id': 1, 'name': 'Beatles Blog'}]> I'm looking for a way where I get both, i.e. something like this <QuerySet [(<Blog: Beatles Blog>, {'id': 1, 'name': 'Beatles Blog'})] Note: yes, it's a dump example and it mustn't be a tuple inside a list, it's just a way to express my needs. -
Django mongoadmin apps arent loaded
Traceback (most recent call last): File "manage.py", line 8, in <module> django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/dist-packages/mongoadmin/__init__.py", line 1, in <module> from .options import * File "/usr/local/lib/python2.7/dist-packages/mongoadmin/options.py", line 6, in <module> from mongoadmin.contenttypes.models import ContentType File "/usr/local/lib/python2.7/dist-packages/mongoadmin/contenttypes/models.py", line 1, in <module> from .utils import has_rel_db, get_model_or_document File "/usr/local/lib/python2.7/dist-packages/mongoadmin/contenttypes/utils.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "/usr/local/lib/python2.7/dist-packages/django/contrib/contenttypes/models.py", line 138, in <module> class ContentType(models.Model): File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. https://github.com/jschrewe/django-mongoadmin/issues i have installed mongoadmin as instructed but im not sure how to get the app loaded in my manage.py import os import sys import django if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "htweets.settings") django.setup() try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: … -
ImportError: No module named 'django.core.urlresolvers'
Hi I am working on Dajngo project where I need to create a form for inputs i tried to import reverse from django.core.urlresolvers I got an error stating that.... line 2, in from django.core.urlresolvers import reverse ImportError: No module named 'django.core.urlresolvers' and I am using Python 3.5.2 , django 2.0 and mysql -
How to show choices of field in another table(model) value?
How to show choices of field in another table value? I want to Nutritionalkey show on the NutritionalValues choice field class Nutritionalkey(models.Model): key = models.CharField(max_length=1000) def __unicode__(self): return self.key class NutritionalValues(models.Model): key = models.CharField(max_length=100, choices=Nutritionalkey.key) value=models.FloatField(null=True, blank=True, default=None) product=models.ForeignKey(Product,null=True, blank=True) class Meta: verbose_name_plural = 'NutritionalValues' verbose_name = 'NutritionalValue' def __unicode__(self): return '%s %s' % (self.product.productName,self.key) -
Everytime I reboot my laptop I have to setup Django in Pycharm again. Error Please enable Django Support for the project
I'm using pycharm and everytime I restart my laptop I have to always configure the Django root folder and the settings in pycharm. I always get this error before trying to run my django server: This are the fields I always have to configure: -
how can I split a string and store it in a temporary variable
I have a data, which is nothing but a string b'365,7,7675962680, 4040.I want to split this data and want to store only 7675962680 to any temporary variable.I don not know, how to split and pick that particular data in python. I have a small code, please help me to solve these issue manage.py def data(self, data): data1 = data # b'365,7,7675962680, 4040 # want to split these and store 7675962680 in a variable -
Django 1.10.6 - MP3 Upload and player
For a job interview I need to code a website consisting of at least 3 pages for a fictional band's website using Django. My idea is to: have a front page with blog posts from the band, the most recent one on top. have an admin page where I can upload the band's songs. have a page with a list of songs that can be played by clicking on the song. I know very basic html and css (did some one codecademy). I did the Django tutorial up until part 6 https://docs.djangoproject.com/en/1.10/intro/tutorial06/ I'm just not very sure how to go about doing this. (Would I use "static files" for the mp3's? How does one set up a blog format page?) So I'm just hoping for a nudge in the right direction. Any links to tutorials or books or anything that might be useful would be much appreciated. -
Organizing grid in a Django template
I'm looking at a table (grid) in a django template, it's almost like I want ... I want to leave the 'douglas' and 'douglas2' variables more right but I'm horrible with front-end (html / Css) I'm just having to break a branch, how can I make these two elements get more right? I have tried to set a class css for them and use the "margin-left" but it is loading all ... file.html {% load staticfiles %} </!DOCTYPE html> <html> <head> <title></title> <link href="{% static 'css/app.css' %}" rel="stylesheet"> </head> <body> {% for m in matrice %} <div class="fp"> {% for n in m %} <p class="sp">{{n}}</p> {% endfor %} </div> {% endfor %} </table> </body> </html> file.css body { background-color: #dbffdb } .div { background-color: #42f453; } .tr { font-size: 20px; background-color: black; } .sp { display: inline-block; margin-left: 50px; font-size: 20px; color: red; padding:10px; } -
install django setup file in python 2.7
i am install diango setup up file than eroor is hari@hari-HP-Pavilion-g6-Notebook-PC:~/Downloads/django-master$ sudo python setup.py install Traceback (most recent call last): File "setup.py", line 32, in version = import('django').get_version() File "/home/hari/Downloads/django-master/django/init.py", line 1, in from django.utils.version import get_version File "/home/hari/Downloads/django-master/django/utils/version.py", line 60, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' how to fix this error plz help me.... -
What template is loaded by Django?
I was following Django tutorial, and got stuck where it asked me to replace the default template for administrative part of the site with my own. The problem was a typo in the template's name. I suspected there must be a problem like that, but to troubleshoot the problem it'd be very helpful to see some kind of report from Django on what template it used to render a particular page. Is there any way to do this? -
Testing Django Views with an ImageField
I have the following Model and Form class AdImage(models.Model): advertiser = models.ForeignKey(Advertiser) picture = models.ImageField('Ad picture', upload_to='ad_pics/%Y-%m-%d/') class AdImageForm(forms.ModelForm): class Meta: model = AdImage exclude = ['advertiser'] helper = FormHelper() helper.layout = Layout( Div('picture'), FormActions( Submit('submit', "Sichern") ) ) This is presented via : class CreateAdImage(LoginRequiredMixin, CreateView): form_class = AdImageForm template_name = 'advertis/adimage_form.html' def form_valid(self, form): slug = self.kwargs.get('slug', None) advertiser = Advertiser.objects.get(slug=slug) form.instance.advertiser=advertiser form.save() ret = render(self.request, 'modal_form_success.html', { 'success_message': "Bild gespeicher fuer %s gespeichert" % (advertiser.user.get_full_name()), 'reload' : True, }) return ret This works pretty well. I can Test the Form with class AdImageFormTestCase(TestCase): def setUp(self): self.creator = ShrUser.objects.create_user(username="foo", email="hallo.ich@localhost.de", password="bla") self.advertiser = Advertiser.objects.create(user=self.creator, city='Chicago') self.uploaded_image = get_temporary_image() self.form_data = {} self.file_dict = { 'picture': self.uploaded_image, } def test_AdImageCreate(self): form = AdImageForm(self.form_data, self.file_dict) self.assertTrue(form.is_valid()) Where self.uploaded_image is def get_temporary_image(): io = BytesIO() size = (200,200) color = (255,0,0,0) image = Image.new("RGBA", size, color) image.save(io, format='JPEG') image_file = InMemoryUploadedFile(io, None, 'foo.jpg', 'jpeg', image.size, None) image_file.seek(0) return image_file But I cant get the view Test to run. I allways run into field required with : def test_create_adimage(self): advertiser = Advertiser.objects.create(user=self.user) response = self.client.get(reverse('create_adimage', kwargs={'slug' : advertiser.slug,})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'advertis/adimage_form.html') self.uploaded_image = get_temporary_image() post_data = { } file_dict = { … -
Python/Django displaying images
I'm new in django and i got a problem. I have a html table with images and some data and depending on which one you select image should be displayed on next page, but i have problem with displaying the image, all i get is broken icon. Images work on first page but something is wrong with the selected page. Could anyone help me? (I'm using django 1.10) models.py class Tags(models.Model): tag_name = models.CharField(max_length=250) tag_chip_type = models.CharField(max_length=250) tag_size = models.CharField(max_length=250) tag_frequency = models.CharField(max_length=250) tag_standards = models.CharField(max_length=250, null=True, blank=True) tag_memory = models.CharField(max_length=250) tag_reading_distance = models.CharField(max_length=250) tag_environment = models.CharField(max_length=250) tag_mounting_method = models.CharField(max_length=250) tag_operating_temperature = models.CharField(max_length=250, null=True, blank=True) tag_storage_temperature = models.CharField(max_length=250, null=True, blank=True) tag_chemical_and_environmental_resistances = models.CharField(max_length=500, null=True, blank=True) tag_image = models.FileField() def __unicode__(self): return self.tag_name + ' ' + self.tag_image.url def get_absolute_url(self): return reverse('tag:index') views.py def selected(request): tags = request.GET.getlist('selected') return render(request, 'tag/selected.html', {'all_tags':tags}) urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) index.html <form action="{% url 'tag:selected' %}" method="get"> <table id="selected" class="white-table table-bordered table-hover" style="width:95%; margin: 3% auto;"> <thead> <tr> <th style="text-align:center;"><input type="checkbox" onClick="toggle(this)"></th> <th></th> <th style="text-align:center;">Name</th> <th style="text-align:center;">Chip Type</th> <th style="text-align:center;">Size</th> <th style="text-align:center;">Frequency</th> <th style="text-align:center;">Memory</th> <th style="text-align:center;">Reading distance</th> <th class="null" style="text-align:center;">Environment</th> <th class="null" style="text-align:center;">Mounting method</th> </tr> </thead> <tbody> {% … -
how can I convert a string to ip address in python
how can i convert a string ip address to a decimal number. e.g I have a data bytes= b'363,3,1778952384,7076' , here 1778952384 is my ip address and 7076 is my port. How can I convert my IP address to decimal number. below is my code, please help me to solve these problem /app.py import socket from tornado.tcpclient import TCPClient from tornado import gen @gen.coroutine def f(self, message): global stream client = TCPClient() stream = yield client.connect('192.168.8.108', 2620, max_buffer_size=int(1e9)) msg = '192.168.8.101, 8000'.encode('utf-8') yield stream.write(msg) data = yield stream.read_bytes(21) print("bytes=",data) #bytes= b'363,3,1778952384,7076 -
Bootstrap-select not working with dynamically populated dropdown
My Form looks like: <form action="/submit/" method="post" >{% csrf_token %} <div class="col-lg-4 col-lg-offset-4"> <div class="form-group has-feedback"> <label class="control-label" for="inputSuccess2">Enter twitter username</label> <input type="text" class="form-control" id="inputSuccess2", name='user'/> <span class="glyphicon glyphicon-search form-control-feedback"></span> <div class="text-center"> <label class="control-label" for="inputSuccess2">Select Job Type</label><br> <select class="selectpicker" id="type" name="type"></select> <br> <div class="btn-group"> <select name="specialization" id="specialization"></select> <br/></div> <script language="javascript"> populateCountries("type", "specialization"); </script> <br/> <input class="btn btn-primary" type="submit" value="Submit"> </div> </div> </div> </form> and the js file for the drop down looks like this: var country_arr = new Array("Social Service and Education","Business and Sales","Language and Arts","Engineering and Technology", "Information Technology" ); // States var s_a = new Array(); s_a[0] = "Please Select One"; s_a[1]="Counselor|School or Career Counselor|Community Service Manager|Social Worker|Preschool Teacher|Librarian|Professor|Psychologist"; s_a[2]="Sales Agent|Real Estate Agent|Accountant|Budget Analyst|Cost Estimator|Sales Engineer"; s_a[3]="Graphic Designer|Musician|Editor|Photographer|Translator|Artist"; s_a[4]="Chemical Engineer|Civil Engineer|Electronics Engineer|Environmental Engineer|Mechanical Engineer"; s_a[5]="Computer Programmer|Database Administrator|Software Developer|Web Developer"; function populateStates(countryElementId, stateElementId) { var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex; var stateElement = document.getElementById(stateElementId); stateElement.length = 0; // Fixed by Julian Woods stateElement.options[0] = new Option('Select Specialization', ''); stateElement.selectedIndex = 0; var state_arr = s_a[selectedCountryIndex].split("|"); for (var i = 0; i < state_arr.length; i++) { stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]); } } function populateCountries(countryElementId, stateElementId) { // given the id of the <select> tag as function argument, it inserts <option> tags … -
How can I register a custom management command that is tied to the project, not the app?
I have a django project whose functionality is split into several interdependent apps. I want to write a custom management command that deletes data from the database and files from the media directory for easy testing in the dev environment. My management command works if I put my management/commands/custom_command.py in an app directory, but it won't work it it's in the base project directory. That feels wrong, as it deletes model instances from several apps, not just the one in whose directory it resides. The docs don't seem to cover what to do in this case. What's best practice in my situation? -
How to replicate Microsoft Word, by being able to add images to text editor?
I'm currently using django pagedown for my text editor: https://github.com/timmyomahony/django-pagedown, which has a <textarea> as the body of the editor. However i'd like to be able to add images within the actual editor, similar to Microsoft Word. Though I've been told I can't add divs to a <textarea>, so would I have to make a text editor myself? Really don't think i'm capable of doing that so is it possible to implement this feature to my current text editor or maybe another one that already has this feature? How would I do this? PS: All text editors can add images which displays the file path of the image, which then renders after the post has been posted. However like I said I want the actual image to show before the post is submitted, like Microsoft Word which shows the image instantaneously.