Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django save checked
I'm trying to make a checkbox for each user, add the checked users to a list and after into data['checked_users']. I've done that, my problem is after logging out and back in, nothing is saved. The list is empty. home.html <form method="POST" action="">{% csrf_token %} {% for user in users %} <tr> <td><input type="checkbox" name="checks[]" value="{{ user.username }}" title="selected_players">{{ user.username }}<br></td> </tr> {% endfor %} <tr><td><input type="submit" name="submit" value="Submit"></td></tr> </form> views.py data['checked_users'] = dict() list_of_checks = request.POST.getlist('checks[]') data['checked_users'] = User.objects.filter(username__in=list_of_checks) If i check users, it shows them, if i refresh everything is fine, if i log out and back in, they are gone. -
How do I display data from MongoDB in an HTML page?
Django Version - 1.10.5 I have uploaded the file on MongoDB, with a few fields like e-mail, employee_id and of course the file from an HTML page. I can see it in mongoDB. What I want to do is retrieve the data on an another HTML page using one of those fields(for example putting in a email id that was used to upload the article will give the entire article on the same HTML page.) . How do I go around that? -
How I show a calculation to the individual product
class attributes(models.Model): attribute_name = models.CharField(max_length = 200, db_index = True) price_update = models.DecimalField(max_digits = 10, decimal_places = 2) class Product(models.Model): attribute = models.ManyToManyField(attributes) This is my models.py I have a calculation... Product.objects.filter(id=product_id).aggregate(Sum('attribute__price_update')) -
Condition in the queryset does not work
I want to add a condition into a queryset of a form, this is my source code : class ContainerForm(forms.ModelForm): vehicle = forms.ModelChoiceField(required=False,queryset=Vehicle.objects.filter(id = vehicle.id),widget=forms.Select(attrs={'class':'form-control'})) but while debugging it says vehicle.id is not defined! Any help would be appreciated! my objective is to have dynamic field into my form -
i am new to angularjs 2.ineed help to understand this
How can i integrate angularjs 2 framework to my django project where i have used bootstrap.please help if you are good in angularjs 2 and bootstrap.thank you. how to use this because on my side its not working npm install -g angular-cli and npm install -g @angular/cli ng new project-title cd project-title ng serve this the error i am getting when i use these commandsnpm install -g angular-cliand npm install -g @angular/cli Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\harrugg>npm install -g @angular/cli npm ERR! Windows_NT 6.1.7600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\ node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "@angular/cli" npm ERR! node v7.8.0 npm ERR! npm v4.2.0 npm ERR! Cannot read property 'path' of null npm ERR! npm ERR! If you need help, you may report this error at: npm ERR! <https://github.com/npm/npm/issues> npm ERR! Windows_NT 6.1.7600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\ node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "@angular/cli" npm ERR! node v7.8.0 npm ERR! npm v4.2.0 npm ERR! code ECONNRESET npm ERR! network socket hang up npm ERR! network This is most likely not a problem with npm itself npm ERR! network and is related to network connectivity. npm ERR! network In most cases you are behind … -
lgdal = CDLL(lib_path) WindowsError: [Error 126] The specified module could not be found
i've installed geonode in Windows 10. I already installed GDAL Core and Gdal. When i try to runserver I am getting the following error. File "C:\Python27\lib\site-packages\django\contrib\gis\gdal\prototypes\ds.py", line 8, in <module> from django.contrib.gis.gdal.libgdal import lgdal File "C:\Python27\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 47, in <module> lgdal = CDLL(lib_path) File "C:\Python27\lib\ctypes\__init__.py", line 362, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] The specified module could not be found -
Celery tasks to update two databases
We have two micro services. one with django and mysql for user actions and another one with bottle and mongodb for geo calculations. For the background we need to update/look at both mysql and mongodb. How can we do this in celery ? tasks can be execute from Django app or bottle app. Thanks. -
How to add Latex editor to django application?
I want add Latex editor on my web application. Is there any open source Latex editor package available ? I mean a good latex editor which includes all the packages and DVI, PDF rendering features? Any suggestion please.. -
How to use javascript variables with django or vice versa?
I am trying to generate random numbers between 1 to 132 (inclusive) using JavaScript, when a user clicks on a button. So far so good, it generates the value and I am able to get the desired output. The problem: I was to use the generated value in a custom Django filter (or whatever it is called). Let me explain it better with my code: <script type="text/javascript"> function random_generator() { var rand = []; var i; var j; var text = ""; for(i = 0; i < 5; ++i) { rand[i] = Math.floor((Math.random() * 132) + 1); text += rand[i]; } document.getElementById('rand1').innerHTML = text; //Just trying to see if the numbers are generated properly var text2 = "{%for i in allb %}{%if i.id == " + text + "|add:0 %}<p>{{ i.name }}</p>{% endif %}{%endfor%}"; document.getElementById('rand2').innerHTML = text2; document.writeln(rand[0]); } </script> Here's what else I tried doing: <div id="b005" class="modal"> <div id="rand1"></div> <div id="rand2"></div> {%for i in allb %} {%if i.id == **WANT TO USE THE JS VARIABLE HERE**|add:0 %} <p>{{ i.name }}</p> {% endif %} {%endfor%} </div> Note:allb is an object that I have passed from my views.py Is there any other way of doing the same? Thank you in … -
default entry for for dropdown in django Form
In a form I have a dropdown list , the default behaviour of django seems to fill the first entry with ----------. How can I remove this, so it will just use the firs entry as the default? model: class Job(models.Model): ... category = models.ForeignKey(Category, on_delete=models.PROTECT) -
How to tell `djcelery` to register on a custom `AdminSite` instance?
I've got a custom AdminSite instance declared in myproject/admin.py such as from django.contrib.admin import AdminSite from django.views.decorators.cache import never_cache class MyAdminSite(AdminSite): @never_cache def index(self, request, extra_context=None): # do some stuff return super(MyAdminSite, self).index(request, extra_context=extra_context) admin_site = MyAdminSite() and later in app1/admin.py, app2/admin.py, etc.: from myproject.admin import admin_site class MyModelAdmin(admin.ModelAdmin): model = MyModel list_display = [f.name for f in MyModel._meta.fields] admin_site.register(MyModel, MyModelAdmin) I also updated my urls.py according to the Django documentation. Now everything looks good except that I can't see the djcelery admin interface anymore, probably because djcelery is registering its models on the old django.contrib.admin.site instance rather than my own AdminSite. How do I tell djcelery (and any other app actually) to register on myproject.admin.admin_site rather than django.contrib.admin.site? -
Crazy Django Error - Variable referenced before assignment
Trying to create a django application but getting an UnboundLocalError at /search/ local variable 'results' referenced before assignment error. I can't see the problem as in my code results is assigned - have a look: def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all() # count total results total_results = results.count() return render(request, 'blog/post/search.html', {'form': form, 'cd': cd, 'results': results, 'total_results': total_results}) -
Why coverage doesn't report anything on Djangos views.py?
I have a class based view in a Django app that looks something like this : class CBView(View): def get(self, request, client, *args, **kwargs): output1 = self.method1(argument1) output2 = self.method2(argument2) # Rest of the method implementation def method1(self, argument1): # Implementation return output1 def method2(self, argument2): # Implementation return output2 And I'm trying to write unit tests for the 'easy' class methods, namely method1 and method2. The tests looks like this : class TestCBView(TestCase): def setUp(self): self.view = CBView() def test_method1(self): # Testing that output1 is as expected self.assertEquals(output1, expected_output1) def test_method2(self): # Testing that output2 is as expected self.assertEquals(output2, expected_output2) After that, I run: coverage run ./manage.py test django_app.tests.test_cbview Which runs all the tests successfully, then I try to run: coverage report -m django_app/views.py And I get : Name Stmts Miss Cover Missing ------------------------------------- No data to report. Am I doing something wrong ? I'm using Coverage.py, version 4.0.3., Django 1.8.15 and Python 2.7.13. -
How calculate the total price of a product attribute
class attributes(models.Model): attribute_name = models.CharField(max_length = 200, db_index = True) price_update = models.DecimalField(max_digits = 10, decimal_places = 2) class Product(models.Model): attribute = models.ManyToManyField(attributes) -
Django - Comparing DateTime Field with server time in template tags
I have an app with the following models.py file: from django.db import models import datetime class Event(models.Model): name = models.CharField(max_length=255) description = models.TextField() event_date = models.DateField(auto_now_add=False) today_date = models.DateField(default=datetime.date.today) class Meta: ordering = ('event_date',) def __unicode__(self): return self.name And in my templates I have a list of events and I want the page to check everytime it loads if the date of the event is in the past or in the future from today's date. So if tomorrow I access the page, the today's date it would be 12th April 2017 and so on. My template code is like this: {% extends "base.html" %} {% block page_title %} Events {% endblock %} {% block content%} <ul> {% for event in object_list %} {% if event.event_date <= event.today_date %} <li> <a href="{% url "events:details" %}"> {{ event.name }} | <span class="event_past">PAST EVENT</span> </a> </li> {% else %} <li> <a href="{% url "events:details" %}"> {{ event.name }} | </a> </li> {% endif %} {% endfor %} </ul> {% endblock %} </body> </html> Is that the correct approach? -
Selecting related model: Left join, prefetch_related or select_related?
Considering I have the following relationships: class House(Model): name = ... class User(Model): """The standard auth model""" pass class Alert(Model): user = ForeignKey(User) house = ForeignKey(House) somevalue = IntegerField() Meta: unique_together = (('user', 'property'),) In one query, I would like to get the list of houses, and whether the current user has any alert for any of them. In SQL I would do it like this: SELECT * FROM house h LEFT JOIN alert a ON h.id = a.house_id WHERE a.user_id = ? OR a.user_id IS NULL And I've found that I could use prefetch_related to achieve something like this: p = Prefetch('alert', queryset=Alert.objects.filter(user=self.request.user)) houses = House.objects.order_by('name').prefetch('alert', prefetch) The above example DOES NOT work though ("Cannot find 'alert' on House object"). And if it did, houses.alert would be a list, not an Alert object. I only have one alert per user per house, so what is the best way for me to get this information? select_related didn't seem to work. Oh, and surely I know I can manage this in multiple queries, but I'd really want to have it done in one, and the 'Django way'. Thanks in advance! -
django - Use loop variables as a dictionary key
I have some issues with access of a specific key in my template. Here is my code : {% for rsim,couples in zipped_formated_rxnsim_pairedsim %} -{{rsim.xxx_fk.xxx_code_char}} #ex : toto {% for rsim2,couples2 in mydict.{{rsim.xxx_fk.xxx_code_char}}%} <li> {{rsim2}} - {{couples2}}</li> {% endfor %} {% endfor %} It gives me this error, Could not parse the remainder: '{{rsim.xxx_fk.xxx_code_char}}' from 'mydict.{{rsim.xxx_fk.xxx_code_char}}' I do not understand this behaviour, because if I hard code the line {% for rsim2,couples2 in mydict.{{rsim.pdb_fk.pdb_code_char}}%} to {% for rsim2,couples2 in mydict.toto %} it works ... I really need this loop structure, because I want to go through "rsim2,couples2" tuples only for a specific "rsim,couple" tuple. In others words, "rsim2,couples2", are extra data linked with "rsim,couples". What a better solution than a dictionary using a key ? I tried using the {{with}} tag, adding a variable to use directly as a key, but it did not work. Thank you ! -
Mezzanine: thumbnails not created when image in subfolder
For better organisation I want to put photos for each blog post in a separate folder like so: static/media/uploads/blog/test/img.jpg but in this case thumbnails are not created for this image. If I put the image inside: static/media/uploads/blog/img.jpg than thumbnails are created. But in this case all photos would need to be in the blog folder... any hints? -
Django session aren't updated
I have question about django sessions. I update session using SessionStore out of view, but request.session is same. (in settings SESSION_SAVE_EVERY_REQUEST = True). -
Django Middleware Error - Middleware changed for 1.7
Whenever I run my local server with my django project I am getting a warning and an error message saying that in Django 1.7 the global middleware classes were changed - even though I am using 1.8. My blog, at http://127.0.0.1:8000/, loads fine, but when I try to load the admin site I get AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user', which as far as I can tell is to do with the Middleware. Thanks for your help in advance -
Getting search error when using elastic search
I am getting TypeError at /search/ search() got an unexpected keyword argument 'fields' I am using saleor for the e-commerce and the elastic search for searching. Here is the stack trace: Traceback: File "/home/zack/.environments/sports/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/home/zack/.environments/sports/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/zack/.environments/sports/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/zack/.environments/sports/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/zack/sportsnstuff/sportsnstuff/saleor/search/views.py" in search 26. print(results) File "/home/zack/sportsnstuff/sportsnstuff/saleor/search/backends/base.py" in __repr__ 187. data = list(self[:21]) File "/home/zack/sportsnstuff/sportsnstuff/saleor/search/backends/base.py" in __iter__ 181. return iter(self.results()) File "/home/zack/sportsnstuff/sportsnstuff/saleor/search/backends/base.py" in results 147. self._results_cache = self._do_search() File "/home/zack/sportsnstuff/sportsnstuff/saleor/search/backends/elasticsearch.py" in _do_search 447. hits = self.backend.es.search(**params) File "/home/zack/.environments/sports/local/lib/python2.7/site-packages/elasticsearch/client/utils.py" in _wrapped 73. return func(*args, params=params, **kwargs) Exception Type: TypeError at /search/ Exception Value: search() got an unexpected keyword argument 'fields' -
Django models – Setting up Categories, optional subcategories and products
I am working on a Django application with products where each product belongs to a main category and ≥0 optional subcategories. For example: Product: Brandname All-stars Subcategories: Sneakers, Lo-tops, trainers Category: Shoes For some generic products, we do not want a Subcategory, only a main Category. My attempt allows the subcategory relation to be optional. However, when adding a new Product in the admin or in forms, all subcategories are available but I would like only the subcategories applicable to the chosen Category to be available. E.G when adding a new raincoat, I do not want the Subcategories Sneakers or lo-tops available. Any suggestions? From django.db import models class Category(models.Model): name = models.CharField(max_length=64) class SubCategory(models.Model): name = models.CharField(max_length=64) category = models.ForeignKey(Category) class Product(models.Model): name = models.CharField(max_length=64) category = models.ForeignKey(Category) subcategory = models.ManyToManyField(Subcategory, blank=True) -
Getting total calculations from Django database
I'm trying to get the 10 cars with the most calculations on them in Django. Calculations model is as follows: class Calculations(models.Model): user = models.ForeignKey(to=User) category = models.CharField(max_length=127) make = models.CharField(max_length=127) model = models.CharField(max_length=127) first_registration = models.CharField(max_length=127) body = models.CharField(max_length=127) facelift = models.CharField(max_length=127) engine = models.CharField(max_length=127) drive = models.CharField(max_length=127) transmission = models.CharField(max_length=127) trim = models.CharField(max_length=127, null=True, blank=True) mileage = models.IntegerField() vat_inclusive = models.NullBooleanField(null=True) price_date = models.DateTimeField(auto_now_add=True) market_days_identical = models.CharField(max_length=6, null=True) market_days_similar = models.CharField(max_length=6, null=True) sales_price = models.DecimalField(max_digits=8, decimal_places=2, null=True) sales_price_currency = models.CharField(max_length=10, null=True) purchase_price = models.DecimalField(max_digits=8, decimal_places=2, null=True) purchase_price_currency = models.CharField(max_length=10, null=True) adjusted_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) customer = models.ForeignKey(to=Customer, null=True, blank=True, on_delete=models.SET_NULL) data = models.TextField(null=True, blank=True) Query that I use is as follows: calculations_list = Calculations.objects.values_list('make', 'model',first_registration', 'body', 'facelift', 'engine', 'drive','transmission', 'mileage') .distinct() .annotate(num_calculations=Count('make')) .order_by('-num_calculations')[:10] This query gives me: <QuerySet [ ('BMW', 'M3', '1/2017', 'SALOON / 4 doors', '2014', 'M3', 'RWD', 'MANUAL ', 70000, 6), ('Audi', 'A4', '1/2017', ' SALOON / 4 doors', '2012', '2.0 TDI', 'FWD', 'MANUAL ', 70000, 4), ('BMW', '7 series', '1/2017', ' SALOON / 4 doors', '2008', '730 d', 'xDrive FOURWD', 'AUTOMATIC Steptronic', 70000, 4), ....... ]> But that is not true. When I in the query use values_list('make', 'model') instead of values_list('make', 'model',first_registration', … -
Django Filterset with foreign key and Unicode
My code is too long and I am sure what should I show. So please look at my code through github. Here is my GitHub address. https://github.com/changja88/FastCampus 1> First, when I try to search using owner field like this //127.0.0.1:8000/estimate?onwer=changja88, it does not work. 2> Second, //127.0.0.1:8000/shop?zone=apt1 is working, but 127.0.0.1:8000/shop?zone=한글 is not working. How can make filter set accept Korean. Thank you very much!! -
How to get information from SQLite using JQuery with Django?
I have a project in Django. In a Python view script i made an array and add this value to my SQLite database "db.sqlite3" by request.user.profile.some_array = some_array Next i sent this array to HTML file this way: return render(request,'field.html',{'some_array': some_array}) The "field.html" is connected with the "app.js" with: I need to get the access from 'app.js' to "some_array" that is stored in database "db.sqlite3" (at the position "user.profile.some_array" if using Python), make several changes with JavaScript and save it. The Internet community advices to use AJAX, but i can't find example i need. Could you help me? P.S. I use the Pycharm