Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
which has a better performance filter / all in django queryset?
let's say I have a model named Best I am wondering if using Best.objects.all() would be a better choice or Best.objects.filter(this=that) would be better performance overall if I do not need to query everything -
How can I connect to ms sql server using setting.py in Django?
Can anyone help me in this. I want to connect SQL server using Django -
are we able to view m2m fields in both models instead of just one model? django
let's say i have two models and one of them has a m2m field. For example: class AAA(models.Model) name = models.Charfield(max_length=64) class BBB(models.Model) style = models.ManyToManyField(AAA, blank=True) if I go to django admin dashboard class BBB, I know that I will be able to see style field and with class AAA that I can multi-select. I am wonder if there's a way that in class AAA I can view style too? Instead of using coding to find out which BBB , AAA has relationship with. Hopefully my explanation is understandable. Thanks in advance. -
Django Users Authentication
En la autentificacion de django estoy utilizando un backend pero al momento de correr mi proyecto me aparece el siguiente error No module named 'user' Model Here in the model I am using AbstractBaseUser and PermissionsMixxin as a model to use the properties of the django user.In the model I am using USERNAME as the email to access the application. from __future__ import unicode_literals from time import timezone from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ from apps.people.models import People class PersonalizadoBaseUserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: now = timezone.now() raise ValueError('Debe tener un email') email = self.normalize_email(email) user = self.model(email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class User(AbstractBaseUser,PermissionsMixin): User = models.OneToOneField(People, blank=True, on_delete=models.CASCADE) username = models.CharField(max_length=50, unique=True) email = models.EmailField(blank=True, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'User'] objects = PersonalizadoBaseUserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_absolute_url(self): return "/users/%$/" % … -
Django do I use query or url path to pass a parameter
If I have two urls: url(r'^maker/$', views.maker_list) #lists a car makers url(r'^model/$', views.model_list) #lists of car models If I click on the URL for models it gives me a list of models. If I click on the URL for makers it gives me a list of makers. I was thinking if I click on a maker e.g. CarMaker I want it to take me to a subset of all models ie. the ones that are made by the maker eg. CarMaker. Is the best way to have it in the path like model/CarMaker/ or as a query like model/?maker=CarMaker. I have read if its unique put it in the path, however, this feels like a search/refinement, which are queries. I am a bit confused where to draw the line. Side question: Should it be model/CarMaker/ or CarMaker/model/? -
Display a schedule from a list of times?
I have two models (https://pastebin.com/8WgWRM19, and below). At the moment the second - the student has a list of (school) classes, each of which has a start time, end time, and a set of days it appears on. I'm trying to efficiently translate this into a schedule or 'calendar' that shows in segmented time blocks and per day what classes the student has. Any help would be appreciated. (Model for Student: class Student(auth.models.User,auth.models.PermissionsMixin): classes = models.ManyToManyField(SchoolClass) def __str__(self): return self.username def getClassTimes(self): times = {} for c in self.classes.all(): days,start_time,end_time=c.getTimes() for d in days: if not (d in times): times[d] = [(start_time,end_time,c)] else: times[d] += [(start_time,end_time,c)] return times ) -
How to Generate Order List Item from List in python
I tried to create an order list item (<ol></ol>) from a list in python. My list is as following: listItem = [ ['101','Dashboard'], ['102','Potential Customer'], ['102-01','Potential Customer Activity'], ['102-02','Potential Customer Report'], ['102-99','Potentail Customer Detail'], ['102-99-01','Potential Customer Detail Listing'], ['102-99-02','Potential Customer Follow Up'], ['102-99-02-01','Follow Up PAR'] ] From this list, I wish to make it as order list item according to itemID such as 101,102,102-01,..etc that would like this: <ol> <li data-itemID="101">Dashboard</li> <li data-itemID="102">Potential Customer <ol> <li data-itemID="102-01">Potential Customer Activity</li> <li data-itemID="102-99">Potential Customer Detail <ol> <li data-itemID="102-99-01">Potential Customer Detail Listing</li> <li data-itemID="102-99-02">Potential Customer Follow Up <ol> <li data-itemID="102-99-02-01">Follow Up PAR</li> </ol> </li> </ol> </li> </ol> <li> <ol> I have tried my code as following: from flask import * import re app = Flask(__name__) @app.route('/', methods=['GET','POST']) def checkName(): orderList = '' listItem = [ ['101','Dashboard'], ['102','Potential Customer'], ['102-01','Potential Customer Activity'], ['102-02','Potential Customer Report'], ['102-99','Potentail Customer Detail'], ['102-99-01','Potential Customer Detail Listing'], ['102-99-02','Potential Customer Follow Up'], ['102-99-02-01','Follow Up PAR'] ] print "List Item: ",listItem orderList += '<ol>' for item in listItem: if item[0].find('-') > 0: # list has sub-list item orderList += '<ol>' orderList += '<li data-itemID=%s>'%(item[0]) orderList += item[1] orderList += '</li>' orderList += '</ol>' else: # list has no sub-list item orderList … -
Django MySQL Error (1146, "Table 'db_name.django_content_type' doesn't exist")
I am getting the error django.db.utils.ProgrammingError: (1146, "Table 'db_name.django_content_type' doesn't exist") when trying to do the initial migration for a django project with a new database that I'm deploying on the production server for the first time. I suspected the problem might be because one of the the apps had a directory full of old migrations from a SQLite3 development environment; I cleared those out but it didn't help. I also searched and found references to people having the problem with multiple databases, but I only have one. Django version is 1.11.6 on python 3.5.4, mysqlclient 1.3.12 -
How to sort objects by a derived calculation?
I have a class called Team that has wins and losses. I want to be able to sort teams by a win_pct which should be the ratio of wins to total games played (i.e. wins.count() + losses.count()). class Team(TimestampModerated): name = models.CharField(max_length=80, blank=False, null=False) wins = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='related_wins') losses = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='related_losses') def num_wins(self): return self.wins.count() def num_losses(self): return self.losses.count() def win_pct(self): return self.wins.count()/(self.wins.count() + self.losses.count()) So, in my view I would have something like this: @list_route def teams_list(self, request): teams = Team.objects.all().order_by('-win_pct') page = self.paginate_queryset(teams) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(teams, many=True) return Response( data=serializer.data ) This just gives an error: django.core.exceptions.FieldError: Cannot resolve keyword 'win_pct' into field. Choices are: created, id, losses, moderation_code, related_losses, related_wins, name, updated, wins -
DRF BooleanField in ModelSerializer causes IntegrityError
I am having trouble with my ModelSerializer class Recall(models.Model): thermal_step = models.BooleanField() have_inventory = models.BooleanField() have_adverse = models.BooleanField() class OrderRecallSerializer(serializers.ModelSerializer): class Meta: model = Recall fields = ['thermal_step', 'have_inventory', 'have_adverse'] s = OrderRecallSerializer(data={}) s.is_valid() >>> True s.save() >>> django.db.utils.IntegrityError: null value in column "thermal_step" violates not-null constraint In django BooleanField is always set to blank=True due to browsers don't send unchecked checkbox in POST data. ModelForm sets model field to False in this case. When using DRF ModelSerializer, generated BooleanField is created with required=False, and when the field is not present in data, passed to serializer, model field is set to None and raises IntegrityError when saving model. Should I explicitly specify BooleanField(default=False) in my ModelSerializer, or I am missing something? I would expect ModelSerializer to behave similar to ModelForm - set value to False when it is not present, which is equal to generating BooleanField with default=False automatically. -
Navbar selection option
I am using a navbar-inverse using bootstrap, in a django project, that contain a 4 "li" buttons. The thing is, I want the firth one to have a 2 choices (select from one of them), here is the code of the "li" : <ul class="nav navbar-nav"> <li class="{% block home_active %}{% endblock %}"><a href="{% url 'music:home' %}"><span class="glyphicon glyphicon-home" aria-hidden="true"></span>&nbsp; Home</a></li> <li class="{% block cloud_active %}{% endblock %}"><a href="{% url 'music:cloud' %}"><span class="glyphicon glyphicon-cloud" aria-hidden="true"></span>&nbsp; Cloud</a></li> <li class="{% block albums_active %}{% endblock %}"><a href="{% url 'music:index' %}"><span class="glyphicon glyphicon-cd" aria-hidden="true"></span>&nbsp; Albums</a></li> <li class="{% block songs_active %}{% endblock %}"> <a href="{% url 'music:songs' 'all' %}"><span class="glyphicon glyphicon-music" aria-hidden="true"> </span>&nbsp; Songs</a> </li> </ul> -
GET Method Returns Different Errors With Values
I want to get values from a form with 'GET' method and perform an operation with it. Now, my html is like this, <form action="{% url 'myman' %}"> <input type='hidden' name='agname' maxlength='300' value='{{mac.user.username}}' /> <input type='text' name='amount' maxlength='300' required /> <input type="submit" value="Send" /> </form> The views is like this, @login_required def myman(request): yoname=request.GET.get('agname') print yoname # did this to see the value in terminal, debugging purposes damount = request.GET.get('amount') print damount # did this to see the value in terminal, debugging purposes requested_decimal_amount=Decimal(damount) # other code follows return redirect('dashboard') I got this error Cannot convert None to Decimal In my terminal, the url is like this; " GET example.com/main/agname=jesse&amount=200 HTTP/1.1" None None I changed my views.py function to this, @login_required def myman(request): yoname=request.GET['agname'] print yoname # did this to see the value in terminal, debugging purposes damount = request.GET['amount'] print damount # did this to see the value in terminal, debugging purposes requested_decimal_amount=Decimal(damount) # other code follows return redirect('dashboard') I got this error; MultiValueDictKeyError at /main/ "'agname'" In the terminal I got; " GET example.com/main/agname=jesse&amount=200 HTTP/1.1" jesse 200 For the second function, it returned the values but I don't get why it's giving me an error! What am I … -
Django: Use ugettext_lazy in templates
Hello I want to know if I can use ugettext_lazy as _ in the templates of django because I want to replace the tags of {% trans %} and {% blocktrans %} because I don't want to make the messages. I want to do something like this: <h1>_('hello')</h1> Instead of this: <h1>{% trans 'hello' %}</h1> Thanks -
Django Migrations: Same migrations being created with makemigrations
Django is creating the same migrations file repeatedly when calling: ./manage.py makemigrations The same migrations will be created in a new migrations file every time makemigrations is run regardless of if the changes are migrated or not. The process looks like so: ./manage.py makemigrations app Migrations for 'app': project/app/migrations/0007_auto_20171010_1837.py - Alter field charge_type on charge - Alter field fee_type on fee - Alter field event_type on orderevent ./manage.py migrate app Running migrations: Applying mws.0007_auto_20171010_1837... OK ./manage.py makemigrations app Migrations for 'app': project/app/migrations/0008_auto_20171010_1838.py - Alter field charge_type on charge - Alter field fee_type on fee - Alter field event_type on orderevent ./manage.py makemigrations app Migrations for 'app': project/app/migrations/0009_auto_20171010_1839.py - Alter field charge_type on charge - Alter field fee_type on fee - Alter field event_type on orderevent I am curious why new identical migrations continue to be created with updated migration file names when no changes are being made to the models between makemigrations and migrate commands. -
get def unicode string information in django
Hi I have a model that has a return statement like this. def __unicode__(self): return u'Car from: %s' % self.car_from If I call the model and print it, it shows. mymodel = CarFromData.objects.filter(user = self.user ) <QuerySet [<CarFromData: Car from: CarRoom 1>]> I would like to access the self.car_from in my view. So I can store the CarRoom1 inside a variable. I tried this way x = mymodel.model.__name__ but that does not give me that string information. -
django cms admin looks weird on heroku and unable to function
I'm having a problem with django cms after pushing to heroku. Django cms admin page is showing up without styling (plain html). Kindly refer to picture. It should look like this. It looks correct on local host. Django cms is also not functioning- such as unable to add pages. For your advice please, thank you. -
Changing the group of a model in Django Admin
For whatever reason I have three models related to authentication, but in Django Admin they show up in two different groups. For example: AUTHORIZATION ------------- Security Questions Users AUTHORIZATION AND AUTHENTICATION -------------------------------- Groups Seems like they should be under one group and I would like to move them to be under one group. I came across this Q/A from a few years ago: Adding a model in Django Admin to the User/Group models? Wonder if there is an easier way now in Django 1.11 like using a class Meta: in the model or in admin.py. Looking through the documentation and haven't come across anything yet. -
Using Django "rules" with CBVs doesn't seem to work
Each restaurant can have multiple managers. class Restaurant(models.Model): ... managers = models.ManyToManyField(User, related_name='restaurants_which_they_manage') Only restaurant managers can change a restaurant listing. I'm using django-rules to enforce this. I've got a predicate that creates a nice verbose "is_restaurant_manager" reference : @rules.predicate def is_restaurant_manager(user, restaurant): return user in restaurant.managers.all() And here is the permission : rules.add_perm('restaurants.change_restaurant', is_restaurant_manager) Finally, here is my view : class RestaurantChange(PermissionRequiredMixin, UpdateView): model = Restaurant permission_required = 'restaurants.change_restaurant' fields = ['name', 'description', ] I've got two tests. Test A checks that the permission works properly : self.assertEqual(rules.has_perm('restaurants.change_restaurant', self.user, self.restaurant), True) This first test passes successfully. Test B attempts to access the url with a valid user : url = reverse('restaurants__restaurant_change', kwargs={'pk': self.restaurant.key,}) response = self.client.get(url) self.assertEqual(response.status_code, 200) Test B fails, as I get a redirection. This also happens if I try to access the url via the browser. The redirection goes to the login process, as though the user didn't have permission to access the view. What's wrong with my code ? -
Cleared static and now collect static won't work
My static files wouldn't stay updated so I just ran python manage.py collectstatic --noinput --clear on my server to clear everything. Now when I run python manage.py collectstatic nothing happens. I have tried service unicorn restart and service gninx restart but still nothing changes. Here is a link to my website so you can what is happening. Obviously I would like it look styled, which it does not. http://evverest.com -
Getting name+otherinfo out of querset django
I am trying to get a dict out of a Queryset. I have a query set called showroom. When I just print showroom it gives this information. <QuerySet [<LeadFormData: Lead form: testing 2 leadform>]> When I use shoowroom.value() it shows me this. <QuerySet [{'last_updated': datetime.datetime(2017, 10, 9, 10, 5, 33, 182308), u'id': 5,'created': datetime.datetime(2017, 10, 9, 10, 5, 33, 182296)}]> I am trying to learn how filters work in a query set but I am not sure on how to get the information out of this above code and put it in a dict like this. {u'testing 2 leadform': [{'count': 5, 'ts': datetime.date(2017, 10, 9)}, {'count': 0, 'ts': datetime.date(2017, 10, 9)}]} Since I have to append to another dict which takes in the data in the above format. This is what I have currently, I am no way sure on how to take out the name from the Queryset since the error I get is Querset does not contain .name dictToStore = {} for s in showroom: dictToStore[s.name] = {'count' : s.id , 'ts':last_updated ,'ts' : last_updated} -
Unable to generate migrations in Django 1.11
On a blank MySQL database, I generated migrations for a Django 1.11 project with: python manage.py makemigrations I have several custom inter-dependent apps, but all the migrations generated without error. However, when I tried to apply these migrations with: python manage.py migrate it applies most app migrations just fine, but with some custom FeinCMS migrations with: Applying page.0001_initial...Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 93, in __exit__ self.execute(sql) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "/usr/local/myproject/.env/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute … -
How to filter object by list of parametrs Django?
If I try to filter some object by list of parameters, it doesn't work, how do I filter it? I have some list for example: brands_list = ['Nike', 'HBO'] how to filter object by this list product = Product.objects.filter(brand__name_of_brand=brands_list) If I run this it gives me nothing empty query set, how can I filter by list parameters and output all in one variable? If i try to filter some object by list of parameters, it doesn't work, how to filter it? -
How do I compare if the value obtained from a radio button is equal to that of a column of a table in Django?
I am doing a questionnaire system in Django and would like to check if the value obtained on the radio button is equal to that of the {{gabarito.gabarito}}, which is present in the system. I would like this to be checked and the user to stay on the same page, without the option of the user replying again. index.html <form method="post"> <div> <input id="radioA" type="radio" name="radios" value="A"> <label for="radioA"><span><span></span></span>a) {{opcao.aOpcao}}</label> </div> <div> <input id="radioB" type="radio" name="radios" value="B"> <label for="radioB"><span><span></span></span>b) {{opcao.bOpcao}}</label> </div> <div> <input id="radioC" type="radio" name="radios" value="C"> <label for="radioC"><span><span></span></span>c) {{opcao.cOpcao}}</label> </div> <div> <input id="radioD" type="radio" name="radios" value="D"> <label for="radioD"><span><span></span></span>d) {{opcao.dOpcao}}</label> </div> <div> <input id="radioE" type="radio" name="radios" value="E"> <label for="radioE"><span><span></span></span>e) {{opcao.eOpcao}}</label> </div> <input type="submit" id="btnSubmit"> </form> <script type="text/javascript"> $(function(){ $('#btnSubmit').click(function(){ var radioValue = $("input[name=radios]:checked").val(); alert(radioValue); $.ajax({ url: '/submit', data: {value:radioValue}, type: 'POST', success: function(response){ console.log(response); }, error: function(error){ console.log(error); } }); }); }); -
django-import-export override not working
I am overriding the django-import-export resource's methods. But only parent methods are executed. models.py class Model(models.Model): modelField1 = models.CharField( modelField2... modelField3... admin.py class ResourceClass(resources.ModelResource): def before_import(self, dataset, using_transactions, dry_run, **kwargs): print("INside BEfore IMport") dataset.headers = ('modelField1', 'modelField2', ...) del dataset[0] def get_instance(self, instance_loader, row): print("Inside get instance") return False def get_or_init_instance(self, instance_loader, row): print("INside Get or init") instance = self.get_instance(instance_loader, row) if instance: return (instance, False) else: return (self.init_instance(row), True) @admin.register(Model) class ModelAdmin(ImportExportModelAdmin): class Meta: model = MOdel resource_class = ModelResource list_display = ('modelField1', 'modelField2', ...) search_fields = ('modelField1', 'modelField2', ...) I am not at all getting print statements in console. Error is thrown directly from the parent methods. They should not be executed at all. AM I right ? Line number: 1 - u"Column 'id' not found in dataset. Available columns are: [u'Col1', u'Col2', u'Col2', ...]" Traceback (most recent call last): File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 434, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 258, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/resources.py", line 252, in get_instance return instance_loader.get_instance(row) File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/instance_loaders.py", line 32, in get_instance params[field.attribute] = field.clean(row) File "/home/aswin/projects/mastercityenv/local/lib/python2.7/site-packages/import_export/fields.py", line 63, in clean list(data.keys()))) KeyError: u"Column 'id' not found in dataset. Available columns are: [u'Col1', u'Col2', u'Col2', … -
how to get specific list with all data from a queryset django?
on server sends this data: Object { categoryes: Array[2], brands: Array[2], discount_list: "all", category_slug: "accessories", category_of_relationsheep: "m" } if i print request.POST in server side i got this: <QueryDict: {'categoryes[]': ['Accessories', 'Bands'], 'brands[]': ['Nike', 'HBO'], 'discount_list': ['all'], 'csrfmiddlewaretoken': ['S7MXVEdQLd6u0fr4FugEwlupa45oChmw3TeItB4BEUHUHSsxrmVRuAcAhFxYQfpk'], 'category_slug': ['accessories'], 'category_of_relationsheep': ['m']}> hot i can get a list for example "categoryes[]" (but why it called like this with brackets?) ok if i do like this: print(request.POST.get("categoryes[]")) it will give the only last object, how to get full list? specific like cotegoryes? if make like for keys, values in request.POST.items(): print(values) it print me all values in this dict, but i don't know from where this values? if i make this: for keys, values in request.POST.items(): if 'categoryes[]' == keys: print(values) it give the same only one object related to categoryes but in this list more than 1 object