Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unique constraint on a pair of fields, bidirectional
Take this model for example class Relationship(models.Model): user1 = models.ForeignKey(User) user2 = models.ForeignKey(User) class Meta: unique_together('user1', 'user2') The unique_together constraint will only work in one direction. The same relationship can be represented in 2 different ways: user1 = Foo user2 = Bar AND user1 = Bar user2 = Foo Is it possible to use unique_together to enforce a bidirectional constraint at the database level? -
How correctly add permissions to User model of Django?
I am tring to add custom permissions to User model (django.contrib.auth.models). To __init__.py file of my users app I add: from django.db.models.signals import pre_migrate from django.contrib.contenttypes.models import ContentType from django.contrib.auth import models as auth_models from django.contrib.auth.models import Permission from django.conf import settings from django.dispatch import receiver @receiver(pre_migrate, sender=auth_models) def add_user_permissions(sender, **kwargs): content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL) Permission.objects.get_or_create(codename='view_user', name=' Can view users', content_type=content_type) Permission.objects.get_or_create(codename='change_user_password', name=' Can change user password', content_type=content_type) settings.py: INSTALLED_APPS = [ 'users', # "users" application ] ERROR: Traceback (most recent call last): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/local/Cellar/python/2.7.14/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Applications/Projects/web/dashboard.kase.kz/users/__init__.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/contrib/contenttypes/models.py", line 139, in <module> class ContentType(models.Model): File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/Users/nurzhan_nogerbek/Virtualenvs/py2714/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Question: How to fix this error? -
CSS + Django - Displaying list of items with grid?
I am trying to display a list of questions (think Stack Overflow's question list), and using grid to display them. I want to display all the questions in the content section and have a separate sidebar section for other stuff. The web page will basically look like this; A=content, B1=sidebar. The thing is, I can't figure out how I can repeat a list of questions in the content section without also repeating content in the sidebar section. My content section is itself a grid. What should I do? This doesn't work, because the content class repeats <div class="body"> {% for question in questions %} <div class="content"> <div class="content1"> ... content here </div> <div class="content2"> ... content here </div> </div> {% endfor %} <div class="sidebar"> ... content here </div> </div> This works, but it is not optimal because the sidebar section repeats as well {% for question in questions %} <div class="body"> <div class="content"> <div class="content1"> ... content here </div> <div class="content2"> ... content here </div> </div> <div class="sidebar"> ... content here </div> </div> {% endfor %} CSS .body { display: grid; grid-template-columns: 3fr 1fr; } .content { display: grid; grid-template-columns: 40px 500px 200px; } -
Append filename and line to Django queries as SQL comment
I'm interested in using this as a profiling technique - I have various ways of observing queries in my DB (slow query logs, etc.) which don't integrate with Python stacktraces (as you'd get with Django Debug Toolbar or similar tools). The idea is that if I were to look at queries in my DB, I would see e.g. SELECT foo FROM bar # my_django_model.py:132 and I'd be able to look at my_django_model.py and see the line that the Django queryset execution came from. Has anyone already figured out a good way to accomplish this? -
Plot result of SVM in Django wep app
I'm working with sklearn.svm to handle the Support vector machine (SVM). And most examples used pylab or matplotlib to plot the result. Please give me an example how I can plot the result of SVM in django web app. Something like this: -
Displaying django-recurrence in template
I've been banging my head about this for a week or so in my spare time, I currently have in my model import recurrence.fields . . . course_recurring = recurrence.fields.RecurrenceField(null=True) I can add recurrences and retrieve them in the admin console, but this in the template: {{ course.course_recurrence.rrules }} returns nothing. -
Why HttpResponseRedirect.set_cookie is not working when i use in django project?
When I use Google OAuth to verify my user, After verify is passed, I want to redirect to the page which user visit before authority, So I want to save the page path to user's cookie, so I implementation like this: def get_login_resp(request, redirect): print(redirect) auth_url = "https://accounts.google.com/o/oauth2/auth?" + urlencode({ "client_id": GOOGLE_CLIENT_ID, "response_type": "code", "redirect_uri": make_redirect_url(request, redirect), "scope": "profile email", "max_auth_age": 0 }) resp = HttpResponseRedirect(auth_url) max_age = 3600 * 24 expires = datetime.strftime(datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT") print(expires) resp.set_cookie('google_auth_redirect', redirect, max_age=max_age, expires=expires, domain=LOGIN_COOKIE_DOMAIN, secure=True, httponly=True) print(resp._headers) print(resp.cookies) return resp ps: redirect is the page path which I want to save But when request the login url with Postman, I can only see this headers: response headers And these cookies: Cookies So how can i do with this problem? There is not any error info for me. -
Django NoReverseMatch Reverse for 'search' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Error: In template *\web_blog\web_blog\templates\blog\index.html, error at line 80 Reverse for 'search' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] and the line 80 is: 78 {% endif %} 79 {% if page_obj.has_next %} 80 <li><a href="?page={{ page_obj.next_page_number }}">»</a></li> 81 {% endif %} the strange thing is that i didn't modify the index.html when i tried to add a search function of my blog by Haystack. I doubt that maybe it's the problem in my urls.py after searched in Google. Here is my code. main urls.py: from django.conf.urls import url, include from django.contrib import admin from blog.feeds import AllPostsRssFeed urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('blog.urls')), url(r'', include('comments.urls')), url(r'^all/rss/$', AllPostsRssFeed(), name='rss'), url(r'^search/', include('haystack.urls')), ] my urls.py in blog app: from django.conf.urls import url from . import views app_name = 'blog' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^post/(?P<pk>[0-9]+)/$', views.PostDetailView.as_view(), name='detail'), url(r'^archives/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$', views.ArchivesView.as_view(), name='archives'), url(r'^category/(?P<pk>[0-9]+)/$', views.CategoryView.as_view(), name='category'), url(r'^tag/(?P<pk>[0-9]+)/$', views.TagView.as_view(), name='tag'), # url(r'^search/$', views.search, name='search'), ] the commented one 'search' is a simple search function i achived before. and the related views function was also commented. the complete code of the project is failed_haystack ps: 1. I have successfuly runed rebuild_index 2. I once deleted the line in index.html … -
create custom role in django to employees
I have created a role model for Employee so that employee will be assigned to control the overall app based on his/her role. I mean if the role of employee is given can_create_only, then the employee should be able to create inventory, orders, items etc and if employee is given can_create_edit_and_delete, then the employee would be like one of the admin and etc. For this I have designed the model as below but I want to know what is the best way to handle such and why? Should I go with middleware or decorator way? Can anyone give me an example, please? class Role(models.Model): name = models.CharField(max_length=100, blank=False, null=False) class Meta: verbose_name = 'Role' verbose_name_plural = 'Roles' class Employee(models.Model): office = models.ForeignKey( OfficeSetup, blank=False, null=False, on_delete=models.CASCADE) name = models.CharField(max_length=150, blank=False, null=False) designation = models.ForeignKey(Designation, blank=False, null=False) section = models.ForeignKey(DepartmentSetup, blank=True, null=True) phone_number = models.CharField(max_length=150, blank=True, null=True) mobile_number = models.CharField(max_length=150, blank=True, null=True) email = models.EmailField(max_length=150, blank=False, null=False) gender = models.CharField( max_length=4, choices=GENDER, blank=True, null=True) role = models.ForeignKey(Role, blank=True, null=True) username = models.CharField(max_length=100, blank=False, null=False) password = models.CharField(max_length=100, blank=False, null=False) avatar = models.ImageField( null=True, blank=True, upload_to=upload_employee_image_path) class Meta: verbose_name = 'Employee' verbose_name_plural = 'Employees' def __str__(self): return self.name When creating an employee … -
Extend Django FloppyForms RadioSelect with an other option
I'm trying to extend the django floppy forms class TextInput to include an 'other option'. So basically something like the following: Please enter your gender [ ] Male [ ] Female [ ] Other Please specify: I'm trying to create a separate class in fields.py called ListTextWidget as follows: class ListTextWidget(TextInput): def __init__(self, data_list, name, *args, **kwargs): super(ListTextWidget, self).__init__(*args, **kwargs) self._name = name self._list = data_list self.attrs.update({'list':'list__%s' % self._name}) def render(self, name, value, attrs=None): text_html = super(ListTextWidget, self).render(name, value, attrs=attrs) data_list = '<datalist id="list__%s">' % self._name for item in self._list: data_list += '<option value="%s">' % item data_list += '</datalist>' return (text_html + data_list) Which in turn is used in a class in forms.py called ListTextForm: class ListTextForm(Form): char_field_with_list = CharField(required=True) def __init__(self, *args, **kwargs): _option_list = kwargs.pop('data_list', None) super(ListTextForm, self).__init__(*args, **kwargs) self.fields['char_field_with_list'].widget = ListTextWidget(data_list=_option_list, name='option-list') However, if I try to create a ListTextWidget class in models.py: GENDER_CHOICES = ('Male', 'Female', 'Other (Please Specify)') gender = ListTextForm(data_list=Constants.GENDER_CHOICES)' I run into this error: django.core.exceptions.FieldError: Unknown field(s) (gender) specified for Respondent I don't know where I'm making a mistake in extending TextInput, or whether I should be trying to extend RadioSelect instead, but I would be grateful for any help. Thank you! -
Can't I add some columns to User model of django.contrib.auth.models?
I wanna add birthday & sex data column to User model of django.contrib.auth.models.However,I wrote views.py like from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm from .models import User class RegisterForm(UserCreationForm): class Meta: model = User fields = ('username', 'email','password1','password1','birthday','sex',) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['email'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' self.fields['birthday'].widget.attrs['class'] = 'form-control' self.fields['sex'].widget.attrs['class'] = 'form-control' and when I run codes,django.core.exceptions.FieldError: Unknown field(s) (birthday) specified for User error happens. I searched Django document,so I found kinds of User objects' field is limited like only username & email & password & is_staff & last_login etc.But now I wanna add birthday & sex data column, so how can I do it?Can't I do it?How should I write it? -
Custom Django ForeignKey field to a defined model class
Using Django 1.11 I'd like to make a custom model field that inherits from ForeignKey. With a normal ForeignKey, you can do something like the following: class Car(models.Model): manufacturer = models.ForeignKey(Company) Instead, I'd like to make a model field that is largely the same as the ForeignKey field, but 1) uses a different default widget for the formfield and 2) doesn't require the model name to be placed as a positional parameter. # myapp/models.py from otherapp.fields import ManufacturerField class Car(models.Model): manufacturer = ManufacturerField() Unfortunately, I'm having a hard time overriding the init method of the child class to get my "Company" model inserted into the mix. Here's what I have so far by way of a modelfield (not working on the widget at all yet): # otherapp/fields.py from otherapp.models import Company class ManufacturerField(models.ForeignKey): def __init__(self, *args, **kwargs): return super(ContentField, self).__init__(Company, **kwargs) When I try to do this, I get: TypeError: Couldn't reconstruct field manufacturer on myapp.Car: __init__() got multiple values for argument 'to' Is there a property I can set on the custom modelfield class to specify that I want this to be a foreignkey to one specific model? If not, any ideas on how I can properly intercept the … -
Django Database: Saving a New Entry Wtihout Saving Its ForeignKeys First
Suppose I have a model structure like this: class Cheese(Model.models): type = models.CharField(max_length='50') class Sauce(Models.models): type = models.CharField(max_length='50') class Pizza(Models.models): cheese = models.ForeignKey(Cheese) sauce = models.ForeignKey(Sauce) class PizzaOrder(Models.model): pizza = models.ForeignKey(Pizza) time = models.DateTimeField(auto_now_add=True) Given this, now I want to create a new entry for PizzaOrder--but I do not want any duplicates of Cheese, Sauce, or Pizza--just PizzaOrder to represent that a pizza was just ordered. This results in an error, which is discussed here. How can I avoid this problem? I do not want a duplicate of object Pizza every-time I get a new PizzaOrder. -
function UNIX_TIMESTAMP does not exist
I am trying to convert my datetime to unix timestamp. I've tried doing several ways and the error is all the same. I am not very sure what I am suppose to do. function unix_timestamp(timestamp with time zone) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts. User.objects.annotate(photo_time=Func(F('date_joined'),function='UNIX_TIMESTAMP')) User.objects.extra(select={'photo_time':"to_unixtime(date_joined)"}) #also tried and UNIX_TIMESTAMP -
What queryset do I use to display the data from a foreign key model in my django template
I'm fairly new to coding and am having trouble with foreign key relationships. I would like to display on my template each instance of the driver and the route they are going. Models.py: class Driver(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) tel = models.CharField(max_length=120, blank=True, null=True) slug = models.SlugField(max_length=120, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.first_name # def get_absolute_url(self): # return reverse("urlname", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.first_name) super(Driver, self).save(*args, **kwargs) class Route(models.Model): leave_from = models.CharField(max_length=120, blank=True, null=True) destination = models.CharField(max_length=120, blank=True, null=True) date = models.DateField(auto_now_add=False, auto_now=False) time = models.TimeField(auto_now_add=False, auto_now=False) drivers = models.ForeignKey(Driver, on_delete=models.CASCADE) def __str__(self): return self.leave_from I'm currenly using .prefetch() but this is only giving me the values from Route model, I'd also like to give the Driver data attached to it as well. Views.py: def drivers(request): qs = Route.objects.all().prefetch_related() context = { "qs": qs, } return render(request, 'drivers.html', context) What is the best queryset to use to give each route as well as the driver unique to that route? Appreciate the help -
django - test environment across apps
Say I have a django project with 2 apps: reusable_app: an independent, reusable app main_app: the main app that uses reusable_app reusable_app sends signals that reusable_app listens to. When I run reusable_app's tests, these signals trigger code in main_app and this causes the test to crash because main_app is not initialized with test data. So, the question is: is there a way to trigger project wide setup for tests? without having to explicitly initialize main_app data in reusable_app, which does not need to know about main_app's existance. Thanks! -
How to migrate Django changes on multiple databases
I have a Django 1.11 project containing three apps, page, book, and fruit. All the models in the page and book apps exist on the default database page_db, whereas all the models in the fruit app exist on a separate fruit_db database, which I specify via a database router, like: class MyRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label in ('page', 'book'): return 'page_db' elif model._meta.app_label == 'fruit': return 'fruit_db' def db_for_write(self, model, **hints): if model._meta.app_label in ('page', 'book'): return 'page_db' elif model._meta.app_label == 'fruit': return 'fruit_db' def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == obj2._meta.app_label: return True def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'fruit_db': allowed = app_label == 'fruit' elif db == 'page_db': allowed = app_label in ('page', 'book') else: allowed = None return allowed Running migrations for the page and book apps works fine. However, when I try to run migrations for the fruit app with: manage.py migrate fruit --database=fruit_db I get the error: 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 = … -
Django oscar paypal
I am using 'django-oscar' for ecommerce website. I integrated 'django-oscar-paypal' for payment system. However, I have a small issue in transmitting correct data to 'paypal-redirect'. The address on checkout page appears correctly and it includes 'address, contact, and instruction'. However, when I click on paypal button to redirect, the address appears correctly but the name slightly changes (it just omits the title) with missing contact and instruction. If I try a different address on the website, the name includes the title but still contact/instruction are missing. After paying and coming back to preview page, the whole address section seems to be stuck with whatever was already inserted in the paypal website and I do not see the contact and instruction. I have set the paypal settings so that the address cannot be amended in the paypal-redirect page. Is there a fix to this? I have attached the screenshots. Thank you in advance! [Checkout][1] [Paypal][2] [Preview][3] [1]: https://i.stack.imgur.com/35x1r.png [2]: https://i.stack.imgur.com/hVNtq.png [3]: https://i.stack.imgur.com/aGqgX.png -
TypeError: int() argument must be a string or a number, not 'User'.
File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/fields.py", line 62, in database_forwards field, File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 221, in add_field self._remake_table(model, create_fields=[field]) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/schema.py", line 103, in _remake_table self.effective_default(field) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 210, in effective_default default = field.get_db_prep_save(default, self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 910, in get_db_prep_save return self.target_field.get_db_prep_save(value, connection=connection) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 728, in get_db_prep_save prepared=False) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 968, in get_db_prep_value value = self.get_prep_value(value) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 976, in get_prep_value return int(value) TypeError: int() argument must be a string or a number, not 'User' from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class TutorProfile(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, … -
django allauth: extended user model form field order
django 1.11.x all auth ? latest installed via pip I've followed instructions HERE for extending the django user model in association with allauth. Yay! it finally seems to be working! When I visit the signup form there are all the form fields I expect... but they are in a wacky order. I have since learned about Form.field_order and Form.order_fields(field_order) but I do not control the allauth base form. How do you apply these ordering tools in this context? -
Codenerix - Disable a dropdown field with foreign key using ng-disabled
Codenerix Has anyone knows how to use correctly ng-readonly in a GenModelForm when coming from a sublist tab (GenList) who calls a GenCreateModal windows? Structure is a master-detail, sublist tab has pk of master table and calls GenCreateModal with this pk argument of master table. GenCreateModal receives pk argument in his asociated form (the mentioned GenModelForm) and can use it. The goal is to disable field with ng-disabled if pk argument of master table is filled. This way when create from another list of detail table without arguments, field can be filled with a value selecting it with the dropdown, and when coming from master table it cannot be modified and it will be assigned to master pk value. I tried to do it that way: First assign 'client' on GenCreateModal with: def get_initial(self): client = self.kwargs.get('pk', None) if client: self.kwargs['client'] = client return self.kwargs Then read it on the GenModelform with: def __init__(self, *args, **kwargs): super(DetailForm, self).__init__(*args, **kwargs) if kwargs.get('initial', None) and kwargs['initial'].get('client', None): self.fields['client'].widget.attrs[u'ng-readonly'] = 'true' But it do not work with dropdown fields. Field can be modified. Cause is that in templatetags_list.py of codenerix we have: def inireadonly(attrs, i): field = ngmodel(i) return addattr(attrs, 'ng-readonly=readonly_{0}'.format(field)) This code … -
Django i can't add admin page model.py list_display = 'sum_amount'
How i am add in the (list_display = ) and show the admin page?When i am try start run server " (admin.E108) The value of 'list_display[2]' refers to 'sum_amount', which is not a callable, an attribute of 'OrderAdmin', or an attribute or method on" my model.py class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Hesapla(models.Model): talepid = models.ForeignKey(Order, on_delete=models.CASCADE) paid = models.BooleanField(default=False) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def _get_total(self): "Returns the total" return self.price * self.quantity property(_get_total) my admin.py from django.contrib import admin from orders.models import Order, Hesapla class HesaplaInline(admin.StackedInline): model = Hesapla extra = 3 class OrderAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['first_name']}), ('city', {'fields': ['last_name'], 'classes':['collapse']}), ] inlines = [HesaplaInline] list_display = ['first_name','last_name','sum_amount'] class Meta: model = Order admin.site.register(Order, OrderAdmin) -
Django multiple-choice field of options in database
I am designing a model, view and template for my news aggregation app. I want the template to offer the user a multiple-choice field form with options from the database. How do I design this in my model? I was reading the Django documentation about ManyToManyField (the one with journalists and articles) but I don't think that is quite the right relationship because in my case, "articles" can exist without a journalist and journalist without an article. I have Users. I have Streams. Streams is a collection of news sites a user can sign up to follow and see aggregated headline snippets, such as from CNN,Twitter, Google News, etc etc. A Stream can exist with no Users. A Stream can have many Users. A User can have no Streams, in fact all user accounts start in my app with no Streams until they choose one. A User can have many Streams. In the template, I want to create a form with the list of all the Stream options in the database (this will likely change as I ad more options in the future). When a User selects a Stream, it will be added to their dashboard view. They can add … -
how to make an if else statement for character length
I'm trying to write a piece of code that will see if the text entry has 50 or more characters and if it does then to just show the 50 plus ellipsis (...) or else if it has less than 50 characters then to just show the whole entry without the ellipsis. My current code is: from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): if text.len() >= 50: """Return a string represerntation of the model""" return self.text[:50] + "..." else: return self.text When I run this while using Python and Django I keep getting an error. How would i go about fixing this -
Django: render inherited (nested) values as a list in forms.ModelForm
I'm trying to display a dropdown list in my form, from my model 'TipoDocumento' (I need to display the column 'nombre_corto' as a list). 1) My model name is "Nana", Nana inherits from my model "Usuario". 2) "Usuario" inherits it's 'documento' field from my model "Documento". 3) "Documento" model inherits it's 'tipo_documento' field from "TipoDocumento". But I cannot render 'tipo_documento', as a list, from my 'Nana' model through my 'NanaForm' form. I get an error, detailed at the end. MODELS: Model 'TipoDocumento' from django.db import models class TipoDocumento(models.Model): nombre_corto = models.CharField(blank=False, null=False, max_length=25) nombre_largo = models.CharField(blank=False, null=False, max_length=100) tipo_patron = models.IntegerField(blank=False, null=False, choices=TIPO_PATRON) tipo_contribuyente = models.IntegerField(blank=False, null=False, choices=TIPO_CONTRIBUYENTE) tipo_longitud = models.IntegerField(blank=False, null=False, choices=TIPO_LONGITUD) def __str__(self): return self.nombre_corto Model 'Documento' class Documento(models.Model): def __str__(self): return self.codigo tipo_documento = models.ForeignKey(TipoDocumento, on_delete=models.SET_NULL, null=True) codigo = models.CharField(max_length=25) Model 'Usuario': class Usuario(models.Model): class Meta: abstract = True nombre = models.CharField(blank=False, null=False, max_length=200) apellido_paterno = models.CharField(blank=False, null=False, max_length=100) apellido_materno = models.CharField(blank=True, null=False, max_length=100) fecha_de_nacimiento = models.DateField(blank=False, null=False) documento = models.OneToOneField(Documento, on_delete=models.CASCADE, blank=False, null=True) telefono_o_celular = models.CharField(max_length=14) esta_activo = models.BooleanField(default=False) genero = models.CharField(blank=False, null=False, choices=GENERO, max_length=1) direccion = models.CharField(blank=False, null=False, max_length=60, default='') latitud_y_longitud = models.CharField(blank=False, null=False, max_length=60, default='') Model 'Nana': class Nana(Usuario): secretaria_registradora = models.ForeignKey(Staff) habilidades = …