Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Removing django default permissions from auth models
guys im trying to remove default django permissions i'll never use in my project but with no success. When I make migration it states that migration is made with success but there's no effect, like it skipped the function. I'm pretty sure code is ok because i tested it in shell. Any ideas? Here's code for migration: from django.db import migrations def remove_redundant_permissions(apps, schema_editor): Permission = apps.get_model('auth.Permission') app_labels = ['admin', 'reversion', 'contenttypes', 'sessions', 'sites'] Permission.objects.filter(content_type__app_label__in=app_labels).delete() class Migration(migrations.Migration): dependencies = [ ('users', '0014_auto_20160808_0738'), ] operations = [ migrations.RunPython(remove_redundant_permissions), ] -
Django get list of Classes defined in an application
I am creating django permissions based on django views rather than basic model based permissions. Hence I want to get the list of all the classes in a view. I tried the following: from django.apps import apps apps.get_app_config('my_app') And also: import sys, inspect inspect.getmembers(sys.modules['my_app'], inspect.isclass) But I didn't get classes object. Can anyone please help me out with the same. Thanks. -
django - UNIQUE CONSTRAINED FAILED error
This is what my models.py looks like: from django.db import models from django.core.validators import RegexValidator # Create your models here. class Customer(models.Model): customer_id = models.AutoField(primary_key=True,unique=True) full_name = models.CharField(max_length=50) user_email = models.EmailField(max_length=50) user_pass = models.CharField(max_length=30) def __str__(self): return "%s" % self.full_name class CustomerDetail(models.Model): phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778") date_regex = RegexValidator(regex = r'\d{2}[-/]\d{2}[-/]\d{2}', message = "Invalid format! E.g. 05/16/91") address = models.CharField(max_length=100) date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True) company = models.CharField(max_length=30) home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True) work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True) customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE) I added customer_id to Customer after I added the same in CustomerDetail as foreign key. Why do I still get this error after running migrate, even after I added unique=True to customer_id? Error: Rendering model states... DONE Applying newuser.0003_auto_20160823_0128...Traceback (most recent call last): File "/home/krag91/Documents/djangodev/virtualenv /lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/krag91/Documents/djangodev/virtualenv /lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: newuser_customer.customer_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File … -
How to filter result with another model values - django restframework
I have 4 table: Book: - id - name - user_id #(ForeignKey) - visitor_id #(ForeignKey) Car: - id - name - user_id #(ForeignKey) - visitor_id #(ForeignKey) Pen: - id - name - user_id #(ForeignKey) - visitor_id #(ForeignKey) Role: - id - obj_type #(ChoicesField. equals `1`,`2` or `3`) - obj_id - obj_role #(Boolean) - visitor_id #(ForeignKey) Now I have this in serializer: class BookSerializer(serializers.ModelSerializer): queryset = Book.objects.filter(?!?!?) # Here I need help serializer_class = BookSerializer I want to check Role table and filter Book according to Role results. How I can do this? What's best solution? -
Django error: unsupported operand type(s) for *: 'NoneType' and 'float'
I have some problem with my code. I was looking have to solve it, but I didn't find similar problem. I want to multiple and then sum some field values, but I get error from a title. Have to solve this problem? I suppose that is problem with data type, but I don't know how to define equation. Please help me. class Bill(models.Model): date = models.DateField(default=datetime.now()) tax = models.FloatField(default=0.20) priceNoTax = models.IntegerField()#integer that I get from other class priceTax = models.FloatField() idAccount = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account") def save(self, *args, **kwargs): if self.priceTax is None: self.priceTax = self.priceNoTax+(self.priceNoTax*self.tax)#here is an error super(Bill, self).save(*args, **kwargs) def __str__(self): return self.date Thanks a lot! -
How can I implement custom user manager in django?
I create custom User models inheriting AbstractUser in Django : class ChachaUser(AbstractUser): birth = models.DateField() gender = models.CharField(max_length=1, choices=GENDER_CHOICES) and my CustomUserCreationForm : GENDER_CHOICES = ( ('M', '남'), ('F', '여'), ) class MyUserCreationForm(UserCreationForm): birth = forms.DateField( widget=forms.SelectDateWidget( years=range(1970, 2015) ), required=True, ) gender = forms.ChoiceField(choices=GENDER_CHOICES, initial='M') class Meta(UserCreationForm.Meta): model = ChachaUser fields = UserCreationForm.Meta.fields + ('birth', 'gender') But I want create superuser by python manage.py createsuperuser, I have to implement CustomUserManager, too. I googled it but there aren't any examples. Any idea or example please? -
Shall I use django-dynamic-formset or there is a bettor solution?
A newbie's question. There is a django-dynamic-formset. We can see that the project was last updated 8 month ago: https://github.com/elo80ka/django-dynamic-formset/branches As far as I can see, this application was well known some time ago. I mean that in the Internet I can find discussions and examples. But all materials are published some of years ago. And there is a respectable site https://djangopackages.org/grids/g/forms/ There is no mentioning of django-dynamic-formset. This makes me a bit skeptical about the app. Could you tell me what is the mainstream solution for dynamically adding a form to a Django formset? By the way Django 1.10. -
html selector option selected based on django provided variable value
I have a django app that returns a list of table rows into a html table and one of the fields is supposed to be an selector with a set of predefined values and selected value has to be the one provided as a variable from django app. Here's the code: <table> <thead>stuff here</thead> <tbody style="font-size: 10px"> {% for ticket in scope %} <tr> <td id="tId" name="tId">{{ ticket.0 }}<input type="checkbox" id="accept" name="accept" value="{{ ticket.0 }}"/> <br />Select</td> <td hidden><input name="list_{{ ticket.0 }}" value="list_{{ ticket.0 }}"/></td> <td> <select id="lvl4" name="lvl4"> <option id="ticket1" value="{{ ticket.1 }}">{{ ticket.1 }}</option> </select> </td> <td>{{ ticket.2 }}</td> <td>{{ ticket.3 }}</td> <td>{{ ticket.4 }}</td> <td>{{ ticket.5 }}</td> </tr> {% endfor %} </tbody> </table> Set of available values: value1 value2 value3 value4 "wrong ticket type" Set of values retreived from the sql table: value1 value2 value3 value4 (select the "wrong ticket type" option) value5 (select the "wrong ticket type" option) What I want to achieve with this select field is to select {{ ticket.1 }} matching option or the "wrong ticket type" if there is no matching option. Please let me know if more information is needed. Thank you for your support. -
How can I evaluate a View context variable as a Template variable in Django?
I'd like to pass a context variable from a view into my template to direct what the template should display. I have a context list variable column_headers that dictates the number of columns in a list page table, along with the header text that should be used. context['column_list'] = [ _('Animal'), _('Owner'), _('Reason'), _('Time'), _('Vet'), _('Status') ] I'd like to include a related list variable that tells the template which variable to include for each cell in the corresponding column, for example: context['cell_vars'] = [ 'patient', 'client', 'reason', 'start_time', 'attending_staff', 'status' ] such that the variable FOO.client would appear in the 'Owner' column, and FOO.attending_staff would appear in the 'Vet' column, etc. Doing this allows me have a single list.html page to handle all of my lists. So, my question is whether this is a good idea, and if so, how would I go about evaluating a 'string' presented as a context variable i.e. {% for row in rows %} #loop over list data {{ row.attending_staff }} #work fine, but... {{ row.SOME_VARIABLE_THAT_HAS_VALUE_OF_'attending_staff' }} #doesn't {% endfor %} So, if x='attending_staff' I need to be able to evaluate the variable row.x such that it actually evaluates row.attending_staff The use case for … -
How to make an API from django model?
I have one form from django model, from which data is coming(through) post, and I'm saving that data in the model. I'm confuse about the serializer for model so i have to save the post data to serializer at same time, OR model will handle all this task(of initiate the serializer) How to handle put, post, get ? -
Django DateField increment
The task is to display Personal and Pensionar today birth day in one template and to have a hiperlink to display the case of tomorrow birth day. Of course yesterday option will be the opposite from tomorrow. In case of current date it works perfect but I do not know how to increase the date variable, then transmit to view. model.py class Personal(models.Model): nume = models.CharField(max_length=40) prenume = models.CharField(max_length=40) dataNastere = models.DateField(blank=True, null=True) def __str__(self): return self.nume class Pensionar(models.Model): nume = models.CharField(max_length=40) prenume = models.CharField(max_length=40) dataNastere = models.DateField(blank=True, null=True) def __str__(self): return self.nume url.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^omagiatulZilei/$', views.omagiatulZilei_list, name='omagiatulZilei_list'), url(r'^omagiatulZilei_next/$', views.nextDate, name='nextDate'), ] views.py def omagiatulZilei_list(request): today = timezone.now().date() personals = Personal.objects.order_by('nume').filter( dataNastere__month=today.month, dataNastere__day=today.day) pensionars = Pensionar.objects.order_by('nume').filter( dataNastere__month=today.month, dataNastere__day=today.day) context = {'personals' : personals, 'pensionars' : pensionars} return render(request, 'blog/omagiatulZilei_list.html', context=context) def nextDate(request, ??): # ?? is a datefield variable nextD = ?? + 1 # increment by 1 (the meaning is next day) personals = Personal.objects.order_by('nume').filter( dataNastere__month=nextD.month, dataNastere__day=nextD.day) pensionars = Pensionar.objects.order_by('nume').filter( dataNastere__month=nextD.month, dataNastere__day=nextD.day) context = {'personals' : personals, 'pensionars' : pensionars} return render(request, 'blog/omagiatulZilei_list.html', context=context) omagiatulZilei_list.html {% load staticfiles %} <html> <head> <title>Omagiatul Zilei</title> </head> <body> … -
ObjectDoesNotExist vs. .filter().first() and check for None
In Django 1.6 they introduced .first() to get the first element of a queryset. [Source] Now there are 2 ways to get a single element: user_id = 42 try: obj = User.objects.get(id=user_id) except ObjectDoesNotExist: raise Exception("Invalid user id given") and: user_id = 42 obj = User.objects.filter(id=user_id).first() if not obj: raise Exception("Invalid user id given") Following the pythonic way to ask for forgiveness, the first one would be more appreciated way to use. However, the second one might be easier to understand and it is one line shorter. Q1: Is there any difference in speed between these two code snippets? Q2: Which one is the preferred way to get a single object? -
Django deserialization of JSON stored in a model field
I'm new to Django/Python and currently im working on a project with a friend. His android app sends data to me in JSON format that looks like this: "datum_isteka": "2", "e_mail": "null", "adress": "null", "goods": "[ {\"price\":\"2\", \"good\":\"dobro1\", \"tax_value\":\"2\", \"quantity\":\"pdv %1\"}, {\"price\":\"3\", \"good\":\"dobro 2\", \"tax_value\":\"3\", \"quantity\":\"pdv %3\"} ]", "taxes": 5, "order_num": 477456, "store_user": 2 In my models this is stored in one field and in my view i get this whole "goods" part of this JSON represented like this up here... My question is how do i turn this JSON field "goods" to something that is readable to a user. I'm using DRF for communication with android app. -
Regular Expression for a paragraph
I need a regular expression which can be used in Comment, Description or Summary without a newline in a single line. Ex: I adsa da kjkjkj, jjj sdkasjhdjah. asdkajhsd,ASDASd5555, sadasd.a asdfasdf 8768, asdhajks. kahsdfjha,sjsjsjs. -
django middleware to intercept request, add header for certain url DRF
I need to intercept certain requests going to docs/api-docs/ and add a header x-forwarded-host. I thought about writing a middleware but I don't know how to proceed in this specific case. thank you -
How to query max to min in Django?
I want to query from max entry to min entry in a topic. Such that: models.py class Topic(models.Model): title = models.CharField( max_length=140, unique=True, verbose_name=_("Title") ) created_at = models.DateTimeField( auto_now=True, verbose_name=_("Created at") ) And other model is : class Entry(models.Model): topic = models.ForeignKey( Topic, verbose_name=_("Topic") ) content = models.TextField( verbose_name=_("Content") ) created_at = models.DateTimeField( auto_now=True, verbose_name=_("Created at") ) Firstly, I want to filter only today's entries from Topic.py. Is that correct? : def get_topic_today(self): return self.filter(date=datetime.date.today()).order_by('title') And also I want to query popular topic max to min. I think we can use select_related with reverse foreign keys from entry to topic models. But I can not do it. For example, the topic which has most entry number must be first and going on lowest. Thank you. -
How to validate a particular link in python Django?
I created a login page in HTML,Javascript.When I logged into the dashboard, a particular link address(url) will appear.When I copy that link address and paste it on another browser or a new tab,it will work..How can I prevent it in Python Django? -
How to create breadcrumb of django-sitetree package in django
I could not use "treesite_breadcrumb from "MENU_BLOCK_NAME" temlplate "TEMPLATE_PATH_AND_NAME" " in django. How cna I use this feature of the django-treesite package? -
Documenting API with Django Rest Framework and Django Rest Swagger
I'm using Django Rest Swagger to documenting my DRF API, but I can't find where to set the values marked in red in the attached image. I tried the options in the DRF docs page but doesn't work. The latest Django Rest Swagger doc says that Django Rest Framework handle this part. Does anyone tried this before? Swagger screenshot -
viewing github biostar-central code with graphviz
I am trying to use biostar code make a website. Biostar code seems amazing. But having hard time trying to wrap my mind around the models. pygraphviz seems like the way to go. But finding it hard to generate those model images. Could anyone help with this model images generation with graphviz for django biostar-central? currently trying to follow http://django-extensions.readthedocs.io/en/latest/graph_models.html https://github.com/ialbert/biostar-central Any help appreciated. I got the manage.py to see the graph_models command-line argument but i end up getting (biostar)root (master)*[biostar-central]$ ./manage.py graph_models -a -g -o my_project.png Traceback (most recent call last): File "./manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/root/websites/django-tutorial/virtual-envs/biostar/lib/python2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/root/websites/django-tutorial/virtual-envs/biostar/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/websites/django-tutorial/virtual-envs/biostar/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command klass = load_command_class(app_name, subcommand) File "/root/websites/django-tutorial/virtual-envs/biostar/lib/python2.7/site-packages/django/core/management/__init__.py", line 75, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/root/websites/django-tutorial/virtual-envs/biostar/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module __import__(name) File "/root/websites/django-tutorial/virtual-envs/biostar/lib/python2.7/site-packages/django_extensions/management/commands/graph_models.py", line 9, in <module> from django_extensions.management.modelviz import generate_graph_data, generate_dot File "/root/websites/django-tutorial/virtual-envs/biostar/lib/python2.7/site-packages/django_extensions/management/modelviz.py", line 16, in <module> from django.apps import apps ImportError: No module named apps -
Currency symbols is not rendering properly on attached pdf in email
I have a django model where I can add the Currency symbols such as $, €, ₹ , etc. But these symbols are not showing in attached PDF in email. I tried with static symbols but does't work. Any way the $ symbol works fine. Please someone help me out this issue. -
MySQL with Django - Python
I'm integrating MySQL as backend with my django application. At the time of installation i'm running following command export PATH=$PATH:/usr/local/mysql/bin start server from settings (i'm on mac os) brew install mysql-connector-c sudo pip install MySQL-python while running last command i'm getting following error, Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/tmp/pip-build-wd69ia4g/MySQL-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/tmp/pip-build-wd69ia4g/MySQL-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ImportError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-wd69ia4g/MySQL-python/ I google the error and got the solutions as run following command export PATH=$PATH:/usr/local/mysql/bin But it doesn't solve my error. Can any body help me to get out of it or let me know the steps for the initial MySQL setup. -
Not update foreign key fields in templates django
I have a models related by ForeignKey and Form for my code, I try to display in one page: All Quotes and their items, also i want to update this fields. Model class Quote(models.Model): number = models.IntegerField(null=False) class Quote_detail(models.Model): quote = models.ForeignKey(Quote) stock = models.IntegerField(null=True) Form class QuoteForm(forms.ModelForm): class Meta: model = Quote fields = '__all__' View def quotes(request): cotiFormSet = modelformset_factory(Quote,form=QuoteForm) if request.method == 'POST': formSet = QuoteForm(request.POST,request.FILES) if formSet.is_valid(): formSet.save() return redirect('quotes') else: formSet = cotiFormSet() return render(request,'supplierweb/quotes.html', {'formset':formSet}) and Template {% for item in form.instance.quote_detail_set.all %} <tr> <td> <input for={{ item.stock }} value = {{ item.stock }} type="number" /> </td> </tr> {% endfor %} But, when i submit this page, fields not update. Thanks for your help! -
Query excluding duplicates in Django
I'm using distinct() QuerySet to get some data in Django. My initial query was Point.objects.order_by('chron', 'pubdate'). The field chron in some cases is a duplicate so I changed the query to Point.objects.order_by('chron', 'pubdate').distinct('chron') in order to exclude duplicates. Now the problem is that all empty fields are considered duplicates. To be accurate, the chron field contain integers (which behave similar to ids), in some cases it can be a duplicate, in some cases it can be NULL. | chron | |-------| | 1 | I want this | 2 | I want this | 3 | I want this | 3 | | NULL | | 4 | I want this | NULL | I want to exclude all the chron duplicates but not if they are duplicate of NULL. Thank you. -
Django dal autocomplete light POSTs 4 times when creating new choices in the autocomplete form
I've created this model: class TitleDescriptionLazyModel(models.Model): class Meta: abstract = True title = models.CharField(max_length=255) description = models.TextField(blank=True) def __str__(self): return self.title class Jobsite(TitleDescriptionLazyModel): pass Which is used in this autocomplete view as described in the documentation (views.py): class JobsiteAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Jobsite.objects.none() qs = Jobsite.objects.all() if self.q: qs = qs.filter(title__istartswith=self.q) return qs and my urls.py have the title field set as the "create_field": urlpatterns = [ JobsiteAutocomplete.as_view(create_field='title'), name='jobsite_autocomplete'), ] But when I run it I get the autocomplete view passing the get requests until I click on the create button at which point it POSTs 4 times creating 4 new items in the database when I expect it to create 1: > [22/Aug/2016 20:44:04] "GET /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 356 [22/Aug/2016 20:44:10] "GET /worklogs/jobsite-autocomplete/?q=som HTTP/1.1" 200 252 [22/Aug/2016 20:44:11] "GET /worklogs/jobsite-autocomplete/?q=some HTTP/1.1" 200 254 [22/Aug/2016 20:44:12] "GET /worklogs/jobsite-autocomplete/?q=somewhere HTTP/1.1" 200 116 [22/Aug/2016 20:44:13] "POST /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 31 [22/Aug/2016 20:44:13] "POST /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 31 [22/Aug/2016 20:44:13] "POST /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 31 [22/Aug/2016 20:44:13] "POST /worklogs/jobsite-autocomplete/ HTTP/1.1" 200 31 django = 1.9 python = 3.4 django-autocomplete-light (3.1.8)