Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to include css in node_modules folder from Django project?
We started using npm to install javascript libraries. We didn't have to collectstatic the javascript files under node_modules directory since webpack includes them during bundling process. How do we include css / less / sass files under node_modules from our html or javascript files? -
Improving Django Slice Step Performance
I have an application where I am using a Django instance to store logs from a number of separate entities. I then have a UX component that grabs log files from the django instance and graphs the values. To keep things reasonable, I try to only grab a sample of the log values, then increase the granularity as the user zooms in. My problem is that as the number of logs grows, the time to grab each downsampled group of logs is growing unsustainably. Here is a simplified version of the model class LogModel(models.Model): localtime = models.DateTimeField(db_index=True) value1 = models.FloatField(blank=True, null=True) value1 = models.FloatField(blank=True, null=True) value1 = models.FloatField(blank=True, null=True) owner = models.ForeignKey('auth.User', related_name='logs') Here is a sample query I use to get the data: q = LogModel.objects.filter(owner=SomeOwner).order_by('localtime') qNum = q.count() logs = q[:qNum:(qNum/1000)] Sometimes running this query takes a very long time (~16s). The number of logs in a large device right now is ~150K. If there are other things hitting the database, it can take a very long time (>1min). Other information: System: VM w/ 2 CPU, 4GB RAM DB: PostgreSQL 9.3 OS: Ubuntu 14.04 I have tried to follow the general optimizing the database guidelines, but with little … -
Django queryset behind the scenes
** Difference between creating a foreign key for consistency and for joins ** I am fine to use Foreignkey and Queryset API with Django. I just want to understand little bit more deeply how it works behind the scenes. In Django manual, it says a database index is automatically created on the ForeignKey. You can disable this by setting db_index to False. You may want to avoid the overhead of an index if you are creating a foreign key for consistency rather than joins, or if you will be creating an alternative index like a partial of multiple column index. creating for a foreign key for consistency rather than joins this part is confusing me. I expected that you use Join keyword if you do query with Foreign key like below. SELECT * FROM vehicles INNER JOIN users ON vehicles.car_owner = users.user_id For example, class Place(models.Model): name = models.Charfield(max_length=50) address = models.Charfield(max_length=50) class Comment(models.Model): place = models.ForeignKeyField(Place) content = models.Charfield(max_length=50) if you use queryset like Comment.objects.filter(place=1), i expected using Join Keyword in low level SQL command. but, when I checked it by printing out queryset.query in console, it showed like below. SELECT "bfm_comment"."id", "bfm_comment"."content", "bfm_comment"."user_id", "bfm_comment"."place_id", "bfm_comment"."created_at" FROM "bfm_comment" WHERE … -
When should I use the keyword super in Base class in python?
I am trying to understand this piece of code in python. From my understanding, super is used to call a base class function from derived class when you don't want to explicitly write the name of the base class. But as mentioned below, what does it mean if the base class itself uses super to call some function? class ReviewViewMixin(object): def dispatch(self, request, *args, **kwargs): # some code return super(ReviewViewMixin, self).dispatch(request, *args, **kwargs) class ReviewCreateView(ReviewViewMixin, CreateView): # some code def dispatch(self, request, *args, **kwargs): super(ReviewCreateView, self).dispatch(request, *args, **kwargs) I tried creating few sample classes like above but I get the expected "no such parameter" exception. -
Django Login using Google
I am creating a django project where I can let the user to login through their gmail account. Does django project have a tutorial about it? Because as much as possible I do not want to use any third party. But If there isn't, I will have to follow django all auth which is different tutorial. Thank you so much guys. I just want to know if djangproject tutorial has it or not. -
Django Model permission not in database
I am maintaining a legacy Django web application (used Django 1.6.1). I just found out that a table was created in the database, and then a model was coded in the models.py. The other developer never ran "syncdb" This means that the model/table was never setup properly in the database. What internal Django function(s) I can call to setup the model properly in the system, I want the content type and permission to be configured properly for this model. I also need this model be configured properly, so I can assign model permission to a group in Django Admin. -
How to set label class in the form __init__ for a Form ChoiceField that was added in __init__?
I know it is long question :-), but it is what I am trying to do. It seems that this solution, the one that hijacking form init, works only for a field that was previously set under class SomeForm(forms.Form), but not under form's __init__. Is there any way to make it possible, or I need to work in a template? -
Django image src not found
-project_ structure |app -project -settings.py -... -picture -panda.jpg I've uploaded the picture into picture. class Goods(models.Model): pic = models.ImageField(upload_to='picture') And the data in database is picture/panda.jpg Now,how can i show it in html? I wrote this in html: <p>{{each.pic}}</p> <img src='{{ each.pic.url }}' /> And the source codes in browser is this: picture/panda.jpg <img src='picture/panda.jpg' /> The image was linked to http://localhost:8000/my_sell/picture/panda.jpg.And couldn't show. How can i solve this,I've tried add media_root in settings.py and useless. -
Django Complex Expression Help in Template
So I am trying to make the following statement in a Django template: if (purchase wasn't refunded) OR (purchase doesn't have feedback AND purchase was not shipped) Here is the code I have generated: {% if not purchase.refunded or not purchase.has_feedback and not purchase.shipped %} SHOW CONTENT {% endif %} But it does not seem to be having the proper effect. I am familiar with the order of Python's Complex Expression hierarchy, but I can't seem to get past this one. Any ideas? -
timepicker javascript validate Date to be today or after?
I want to not accept that the date given be after now or yesterday, Im using django datepicker, i have some code: <script> $('#datepicker').datepicker({ dateFormat: 'dd/mm/yy', changeYear: true, changeMonth: true, yearRange: "1900:2100", locale:'es', }); $.datepicker.regional[ "es" ] $("#miForm").validate({ errorClass: "claserror", validClass: "clasevalida", errorElement: 'erele', rules: { date: { required: true, } </script> -
Django Elastic Beanstalk App - Cannot Set Secure Listener Port to 443: LoadBalancerHTTPSPort
I'm a pretty new developer and deployed my first Django app via Elastic Beanstalk. I want to serve https requests and have configured my SSL certificate and have my load balancer set up correctly. When I go into EB > Configuration > Secure listener port and set it to 443 I'm getting the error upon saving: LoadBalancerHTTPSPort: You have specified both the @deprecated(:default.aws:elb:loadbalancer:LoadBalancerHTTPSPort) option as well as one in the new aws:elb:listener:443 namespace. The :default.aws:elb:loadbalancer:LoadBalancerHTTPSPort option will be ignored. Not sure what I'm missing because I'm still not able to serve https requests -
ImportError: DLL load failed: %1 is not a valid Win32 application when importing _socket
I've seen this question asked already but I think my situation is unique. I recently installed MYSQL and since then whenever I run python manage.py runserver I get this error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "C:\Users\ELITEBOOK\.virtualenvs\charles\lib\site-packages\d le> from django.apps import apps File "C:\Users\ELITEBOOK\.virtualenvs\charles\lib\site-packages\d from .config import AppConfig File "C:\Users\ELITEBOOK\.virtualenvs\charles\lib\site-packages\d from django.core.exceptions import AppRegistryNotReady, Imprope File "C:\Users\ELITEBOOK\.virtualenvs\charles\lib\site-packages\d from django.utils.encoding import force_text File "C:\Users\ELITEBOOK\.virtualenvs\charles\lib\site-packages\d from django.utils.six.moves.urllib.parse import quote, unquote File "C:\Users\ELITEBOOK\.virtualenvs\charles\lib\site-packages\d result = self._resolve() File "C:\Users\ELITEBOOK\.virtualenvs\charles\lib\site-packages\d module = _import_module(self.mod) File "C:\Users\ELITEBOOK\.virtualenvs\charles\lib\site-packages\d __import__(name) File "c:\python27\Lib\urllib.py", line 26, in <module> import socket File "c:\python27\Lib\socket.py", line 47, in <module> import _socket ImportError: DLL load failed: %1 is not a valid Win32 application. Could MYSQL be interfering with my Python installation? I tried uninstalling Python, and deleting all the files. Then reinstalling 32-bit Python but to no avail -
Grouping rows with condition
I have the following models: class Datacomponent(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. composition = models.ForeignKey(Composition, models.DO_NOTHING, db_column='Composition_ID', null=True, blank=True) # Field name made lowercase. components = models.ForeignKey(Components, models.DO_NOTHING, db_column='Components_ID') # Field name made lowercase. componentvalue = models.FloatField(db_column='ComponentValue') # Field name made lowercase. class Components(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. In Datacomponent there are multiple rows of same composition (which is foreign key to Composition table). My end goal is to get set of Composition if each of its component values are in range of some values. In my approach shown below I do not get any composition_ids at all. CompositionID ComponentID ComponentValue 1 1 0.5 1 2 0.3 2 1 0.6 2 2 0.4 3 1 0.0 3 2 0.1 So the query for above table would be: 'Get all composition ids with componentid=1 and componentvalue__range=(minn[a], maxx[b]). If we want comp value gte 0.5 for componentID 1 and gte 0.3 for componentID 2 our result should be just 2 because 2's component 1 is 0.6 and component2's value is 0.4. Here's my approach which is not working: queries = [Q(componentvalue__range = … -
Saving with PrimaryKeyRelatedField django-rest
I'm trying building an endpoint that allows posting to django backend. My Deal Model has ManyToMany Relation top book runner, and my serializer by default has PrimaryKeyRelatedField below: Models.py class Deal(models.Model): book_runner = models.ManyToManyField(BookRunner, blank=True, null=True, related_name="deal_book_runner") Serializers.py class DealSerializer(serializers.ModelSerializer): book_runner = PrimaryKeyRelatedField(allow_null=True, many=True, queryset=BookRunner.objects.all(), required=False) equity = Equity.objects.create(**equity_data) def create(self, validated_data): deal = Deal.objects.create(**validated_data) return deal Views.py class DealAdminViewSet(viewsets.ModelViewSet): queryset = Deal.objects.all() serializer_class = CreateDealSerializer def create(self, request, format=None): book_runner = request.data.get('book_runner', None) #array Printing data before validation (validated_data) where the program breaks: {'book_runner': u'2'} Now when I post a deal with book runner with primary key=2, I get an error: raise TypeError(repr(o) + " is not JSON serializable") TypeError: <property object at 0x7f1559578158> is not JSON serializable I want to use both array and numbers of primary keys in the future but I can't seem to figure out this... Thanks for your help! -
How to create Team of Users model in django
I'm trying to implement team model in Django. What i want: User can be a member of multiple Teams Team can have multiple Users Team Member can be assigned to multiple categories Category can be assigned to multiple Team Members I thought i could achieve it like this: class System(models.Model): name = models.CharField(max_length = 20) #User can own multiple systems owner = models.ForeignKey(User) description = models.TextField(max_length = 250) class Team(models.Model): """ Represents a team """ #Each system can have only one team, possibility of changing in the future system = models.OneToOneField(System) ... ... class TeamMember(models.Model): """ Bounds user to team """ user = models.OneToOneField(User, null=True) #Teams can have multiple team members, team member can be in multiple teams team = models.ManyToManyField(Team) category = models.ManyToManyField(Category) But the longer i think about it, the more concerned i become if it can be done like that. I have trouble with imagining how i would perform queries like: get all members of the team, get all teams that user belongs to, get categories that user is assigned to, get users that are assigned to categories. Also i don't know if there is some kind of mistake in my code(thinking). I know that there probably … -
How do I redirect away from the login page, if the user is already logged in in Django?
I'm trying to make it so when a user that is ALREADY logged in visits the login page, they are redirect to their account page. I decided to do this by having my own Login View, that checks if the user is logged in and redirects if they are. Then if they are not logged in, it continues using the contrib login view. The issue is that I need to be able to specify the contrib login authentication_form and template_name. How do I specify those when I'm calling login() directly? Here's my code... urls.py from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from Account.views import RenderLoginPage from django.contrib.auth.views import logout urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', RenderLoginPage, name='login'), url(r'^logout/$', logout, {'next_page': '/login'}, name='logout') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import redirect from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.views import login from forms import LoginForm def RenderLoginPage(request): if request.user.is_authenticated(): return redirect(reverse("myaccount")) else: return login(request) So how do I specify the template_name & authentication_form? If I was doing this directly through URLs, without a custom Login View I would do this... but I can't because I need the custom … -
Getting all the tags associated with the parent object using django-taggit
I have models Restaurant & Review. Review has TaggableManager() I have no problem in making tags work for Reviews. But I also want to know all the tags that are associated with the Restaurant object. I can write my own function that iterates through all reviews of the restaurant to get all the tags associated with the Restaurant. But I am looking for cleaner and easy way to get the tags that accomplishes it in a single DB query. -
Add "fake" model entry to admin index
I want to add a link to the index page of the admin, where it lists the models, but I don't want to create a new model. It would be a custom view. This is my desired result. In this case, Leaderboards should point to /admin/leaderboards. Codes and Users are valid models. I tried overriding index.html page, according to the documentation, using the following template. {% extends "admin/index.html" %} {% block content %} {{ block.super }} <div class="app-{{ app.app_label }} module"> <table> <tr> <th scope="row"><a href="leaderboards">Leaderboards</a></th> <td></td> </tr> </table> </div> {% endblock %} But this is the result: I know that I can replace the full index.html and hardcode a specific row there, but many people don't recommend that. Is there any alternative? https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.AdminSite.index_template -
Django with reportlab dynamically generates only one page of PDFdocument
I am generating my invoice as pdf file however some records are generated in a loop . For this reason, I can't determine how many pages I will require. Currently, pdf file beeing generated only includes whatever fits into one page and the rest cuts off. What can be done to solve it? from io import BytesIO from reportlab.pdfgen import canvas @login_required def invoice_pdf(request,pk): ........................ ........................ # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Receipt.pdf"' buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. p.drawString(10, 800, "Invoice") p.drawString(10, 780, "*----------------------------------*") p.drawString(100, 760, "Lease id: " + str(lease.id) ) p.drawString(100, 740, "For: " + str(lease.unit) ) p.drawString(100, 720, "Lease term: " + str(activeterm) ) p.drawString(100, 700, "Current Balance: " + str(total_till_current) ) p.drawString(100, 780, "Period amount: " + str(activeterm.amount) ) p.drawString(10, 660, "*----------------------------------*") p.drawString(10, 640, "*Period Break Down*") position = 620 for field in period: p.drawString(120, position, ''+ str(field.name) ) position = position - 20 p.drawString(120, position, 'order'+ str(field.order_value) ) position = position - 20 p.drawString(120, position, 'is_payed '+ str(field.is_payed) ) position … -
Filter duplicate joined rows based on parent ID
I have the following models: Datapoint class Datapoint(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. composition = models.ForeignKey(Composition, models.DO_NOTHING, db_column='Composition', blank=True, null=True) # Field name made lowercase. value = models.IntegerField(db_column='Value') # Field name made lowercase. Composition class Composition(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. DataComponent class Datacomponent(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. composition = models.ForeignKey(Composition, models.DO_NOTHING, db_column='Composition_ID', null=True, blank=True) # Field name made lowercase. components = models.ForeignKey(Components, models.DO_NOTHING, db_column='Components_ID') # Field name made lowercase. componentvalue = models.FloatField(db_column='ComponentValue') # Field name made lowercase. And finally, Component class Components(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. All of these tables will be joined, so the rows are repeated. The following solution only filters out the rows where the row's componentName matches and componentValue is not in the range given by minn and maxx. I would like to remove the whole set of repeated rows of Datapoint if any of the rows with the components value does not fall in the range. def get_object_list(self, request): minn = json.loads(request.GET["min"]) maxx = … -
Django Model.Objects.order_by charField which can contain notes written in different languages(ENG, RUS)
I have a model: class A(models.Model): name = models.CharField(max_length=120) name can be written in two languages: English and Russian. When i use A.objects.order_by('-name'), English words stand before Russian. How can i swap it? -
Global read-only in Django Admin by group
I need to be able to allow a staff member to be able to read everything in the Admin but not edit, add or delete. We have a non-admin interface that I've already done this via Group membership. Is there something I can do for Admin without overriding every ModelAdmin? -
After upgrading Solr 4.10 to 6.3 the search stopped working and at the 'logging' page there are warnings "please use 'df'\'q.op' on request instead."
I got a task to upgrade Solr, hovewer never worked with Solr before. As in my case there is haystack, I generated schema, put it in managed-schema and modified a bit according to StackOverflow's answers, because Solr did not want to start. So, now Solr starts, but at the 'logging' page of back-end I see: [default] default search field in schema is text. WARNING: Deprecated,&#8203; please use 'df' on request instead. [default] query parser default operator is AND. WARNING: Deprecated,&#8203; please use 'q.op' on request instead. As I understand, this is because of <!-- field for the QueryParser to use when an explicit fieldname is absent --> <defaultSearchField>text</defaultSearchField> <!-- SolrQueryParser configuration: defaultOperator="AND|OR" --> <solrQueryParser defaultOperator="AND"/> from managed-schema. Where and how do I need to use df and q.op? In solrconfig.xml in the section below: <requestHandler name="/select" class="solr.SearchHandler"> <!-- default values for query parameters can be specified, these will be overridden by parameters in the request --> <lst name="defaults"> <str name="echoParams">explicit</str> <int name="rows">10</int> </lst> I tried to add: <str name="df">text</str> <str name="q.op">AND</str> After that the warnings still appear at the logging page, however because of <str name="df">text</str> the search partially started to work -> for example, there is such item INTEL … -
Django ORM compound filter with variables
I'm by no means a Django expert, and need some guidance on a problem. For background, I have a older .NET project that I've been tasked to turn into Django project. The project gets a full list of objects and then runs a large set of user set filters to end up with the desired set of objects. One of the filters in .NET might be like so ... matched.RemoveAll(x => ((x.annualIncome / 12) - x.payment) < monthlyIncome); I'm trying to figure out how I would do this with the django ORM. I'm kind off stuck on this. In a pseudo-code django ORM version (yes, this will not work): matched.exclude(((annualIncome /12)-payment)__gt = monthlyIncome) There are 30+ filters before this one so I can't re-do them all in a different manner. I can obviously go through each object and filter but I decided to ask first. I'm open to solutions here or friendly "RTFM, this pages answers it." Thanks in advance, and mods please edit with a better title as my brain is now officially fried from 3 days coding with the Flu. -
Cancel ajax calls?
I'm using the Select2 select boxes in my Django project. The ajax calls it makes can be fairly time-consuming if you've only entered a character or two in the query box, but go quicker if you've entered several characters. So what I'm seeing is you'll start typing a query, and it will make 4 or 5 ajax calls, but the final one returns and the results display. It looks fine on the screen, but meanwhile, the server is still churning away on the earlier queries. I've increased the "delay" parameter to 500 ms, but it's still a bit of a problem. Is there a way to have the AJAX handler on the server detect that this is a new request from the same client as one that is currently processing, and tell the older one to exit immediately? It appears from reading other answers here that merely calling .abort() on the client side doesn't stop the query running on the server side.