Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test.Client is logged in but passed as AnonymousUser in views
I have a weird problem here... I am trying to test a @login_required views so I wrote this code: from django.test import TestCase from django.test import Client from .models import SiteEcommerce from .models import Client as TestDbClient from .models import MyCustomEmailUser class DataBaseTestCase(TestCase): def __init__(self, *args, **kwargs): super(DataBaseTestCase, self).__init__(*args, **kwargs) self.c = Client() # instantiate the Django test client self.user = MyCustomEmailUser.objects.all()[0] def test_method(self): """ Test of the settings page. """ self.c.login(username=self.user.email, password=self.user.password) print self.user.is_authenticated() response = self.client.get('/main/settings/%s' % self.website.idsite) self.assertEqual(response.status_code, 200) The view called settings_view where I am printing the request.user The problem is that in the test print self.user.is_authenticated() give True BUT the request.user in the view return AnonymousUser -
Django checking for a query string
When someone clicks on my site's logout link, I want them to be redirected to the login page but I want a message to pop up saying that they were successfully logged out. However, I don't want this behaviour to occur when someone normally visits the login page. I decided to pass in a query string so now when someone hits logout they are redirected to users/login/?logout. How can I check for this in my template though? I want to do something like: {% if ______ %} *Message box appears* {% endif %} Thanks! -
Django error: "Expected table or queryset, not str"
Hi am currently building an django app by connecting with SQL server of existing data base through sql_server.pyodbc. Once i build the necessary steps it showing me an error stating "Expected table or queryset, not str". I tried all the steps(including updating django and django_tables2). Still the problem exists. Kindly suggest me an remedy for resolving this issue. Below are the code for all python files. models.py from django.db import models class Tbluser(models.Model): user_xid = models.CharField(db_column='User_XID', max_length=8) # Field name made lowercase. user_name = models.CharField(db_column='User_Name', max_length=100) # Field name made lowercase. # class Meta: # managed = False # db_table = 'tblUser' def __str__(self): return self.user_name class Tblmetric(models.Model): metric_name = models.CharField(db_column='Metric_Name', max_length=100) # Field name made lowercase. # class Meta: # managed = False # db_table = 'tblMetric' def __str__(self): return self.metric_name tables.py import django_tables2 as tables from django_tables2.utils import A from.models import Tbluser, Tblmetric class EmployeeTable(tables.Table): #id = tables.LinkColumn('tblUser', args=[A('pk=pk')]) class Meta: model = Tbluser attrs = {'class': 'table table-bordered table-striped table-hover'} class UserMetrixTable(tables.Table): id = tables.Column(visible=True) # name = tables.LinkColumn('Tblmetric', args=[A('pk')]) class Meta: model = Tblmetric attrs = {'class': 'table table-bordered table-striped table-hover'} forms.py from django import forms from .models import Tbluser, Tblmetric class EmployeeForms(forms.ModelForm): class Meta: model … -
django-push-notifications pem v p8
I am trying to use "django-push-notifications" and I get the error: Internal Server Error: / SSLError at / [SSL] PEM lib (_ssl.c:2584) The instructions say to use a pem certificate but I have a p8. Is this the problem? If so how should I go create a pem file OR is there an alternative django option that uses p8. Many thanks, Alan. -
DetailView template not displaying it's data
within an app I have two models, named Course and Step. Every Step belongs to a Course and each Course has many steps. However, I'm having problem creating a detailview for Steps. For example when i go to the url 'http://127.0.0.1:8000/courses/1' it should display steps for course.objects.get(pk=1). However what i get back is just the page for course, i.e, http://127.0.0.1:8000/courses'. Model from django.db import models # Create your models here. class Course(models.Model): created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length= 255) description = models.TextField() def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length = 255) description = models.TextField() order = models.IntegerField() course = models.ForeignKey(Course) def __str__(self): return self.title Url from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.course_list), url(r'(?P<pk>\d+)/$', views.course_detail) ] View from django.shortcuts import render from django.http import HttpResponse # Create your views here. from .models import Course, Step def course_list(request): courses = Course.objects.all() return render(request, 'courses/course_list.html', {'courses': courses}) def course_detail(request, pk): course = Course.objects.get(pk=pk) return render(request, 'courses/course_detail.html', {'course': course}) course_detail.html {% extends 'layout.html' %} {% block title %}{{course.title}}{% endblock %} {% block content %} <article> <h2>{{ course.title }} %</h2> {{course.description}} <section> {% for step in course.step_set.all %} <h3>{{ step.title }}</h3> {{step.description}} {% endfor %} </section> </article> … -
Django migration 11 million rows, need to break it down
I have a table which I am working on and it contains 11 million rows there abouts... I need to run a migration on this table but since Django trys to store it all in cache I run out of ram or disk space which ever comes first and it comes to abrupt halt. I'm curious to know if anyone has faced this issue and has come up with a solution to essentially "paginate" migrations maybe into blocks of 10-20k rows at a time? Just to give a bit of background I am using Django 1.10 and Postgres 9.4 and I want to keep this automated still if possible (which I still think it can be) Thanks Sam -
Is there a better way to create a Django REST Web Service?
I'm new to Python Django - further to my question. I create a REST Web Service but I'm totaly unhappy with my code, but i can not find ab better solution. Is it really necessary to create new classes for each new URL part? If not, how can I find a better way for this issue? urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^movement/$', views.MovementDirection.as_view()), url(r'^movement/on/$', views.On.as_view()), url(r'^movement/off/$', views.Off.as_view()), url(r'^movement/stop/$', views.Stop.as_view()), url(r'^movement/forward/$', views.Forward.as_view()), url(r'^movement/backwards/$', views.Backward.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) views.py ... #movement/forward class Forward(APIView): def get(self, request): print("FORWARD") # engine control return Response("Forward") #movement/backwards class Backward(APIView): def get(self, request): print("BACKWARD") # engine control return Response("Backward") ... -
Retrieving attributes of currently selected objects in Django
Right now I'm trying to make an e-commerce site. My problem is that calculate the total amount the user has spent on the current purchase, my problem is that I don't know how to use the price from the current Product object, instead I'm just getting None. I know there's probably a simple answer. Here's my models.py: from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django import forms, views from django.db.models import Sum # Create your models here. #LoginInfo is not being used, LoginForms in forms.py is class LoginInfo(models.Model): username = models.CharField('', max_length=10) password = models.CharField('', max_length=15) class ExtendedProfile(models.Model): user = models.OneToOneField(User) amount_spent = models.DecimalField(max_digits=6, decimal_places=2, default=0) #@classmethod tells the class to act on itself instead of an instance of itself @classmethod def total_amount(cls): #returns a dictionary return cls.objects.all().aggregate(total=Sum('amount_spent')) class RevenueInfo(models.Model): #here we access the dictionary user_total = ExtendedProfile().total_amount()['total'] total_amount_spent = models.DecimalField("Total User Revenue", max_digits=6, decimal_places=2, default=user_total) class Product(models.Model): category = models.CharField(max_length=100) name = models.CharField(max_length=100) description = models.TextField() #photo = models.ImageField() price_CAD = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.DecimalField(max_digits=2, decimal_places=0, null=True, editable=True) And my view: def product_page(request): all_products = Product.objects.all() quantity_forms = QuantityForms(request.POST) quantity = request.POST.get('amount') grand_total = RevenueInfo.user_total if quantity > 0: return HttpResponse(Product().price_CAD) return … -
How to intercept and control saving a Django POST form?
When the user is required to fill his profile, he picks a city from the Google Places Autocomplete and posts the form, in the view I extract the city Id from the Google API based on the posted text (I use the same id as pk in my db) and try to extract a city from my db. These are the models: class City(models.Model): #extracted from the Google API city_id = models.CharField(primary_key=True, max_length=150) name = models.CharField(max_length=128, blank=True) country = models.CharField(max_length=128, blank=True) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', primary_key=True) city = models.ForeignKey(City, blank=True, null=True) prof_pic = models.ImageField(blank=True, upload_to='profile_pictures') This is the view: def createprofile(request): if request.method =='POST': user = User.objects.get(username=request.user.username) user_form = UserForm(data=request.POST, instance=user) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.save() profile = profile_form.save(commit=False) profile.user = user #brings back the city search result as text searched_city = request.POST['city'] #brings back city ID from the Google API searched_city_id = population_script.get_city_json(searched_city.replace(" ", ""))['results'][0]['id'] #If it's a valid city if searched_city_id != -1: city = City.objects.get(city_id = searched_city_id) profile.city = city#this is what I want to happen! else: return HttpResponse("There's no such city, please try a different query.") if 'prof_pic' in request.FILES:#now save the profile pic profile.prof_pic = request.FILES['prof_pic'] print("PROF … -
How can I serialize / de-serialize a Django QuerySet without executing the queryset?
I noticed that if I pass a queryset to a Celery task (which, therefore, serializes it): my_awesome_task.apply_async((my_queryset,), queue='whatever') the query is executed, thus pulling all of the objects from the DB for nothing. Is there a way to avoid that and have it just serialize the un-executed QuerySet, itself, leaving the DB pummeling to the Celery task? -
Docker NGINX Proxy not Forwarding Websockets
NGINX proxy is passing HTTP GET requests instead of WebSocket handshakes to my django application. Facts: Rest of the non-websocket proxying to django app is working great. I can get WebSockets to work if I connect to the django application container directly. (Relevant log entries below.) The nginx configuration works localhost on my development machine (no containerizing). (Log example below.) Relevant Logs: Daphne log when connecting through containerized nginx proxy: `xxx.xxx.xxx.xxx:40214 - - [24/May/2017:19:16:03] "GET /flight/all_flight_updates" 404 99` Daphne log when bypassing the containerized proxy and connecting directly to the server: xxx.xxx.xxx.xxx:6566 - - [24/May/2017:19:17:02] "WSCONNECTING /flight/all_flight_updates" - - xxx.xxx.xxx.xxx:6566 - - [24/May/2017:19:17:02] "WSCONNECT /flight/all_flight_updates" - - localhost testing of nginx (non-containerized) configuration works: [2017/05/24 14:24:19] WebSocket HANDSHAKING /flight/all_flight_updates [127.0.0.1:65100] [2017/05/24 14:24:19] WebSocket CONNECT /flight/all_flight_updates [127.0.0.1:65100] Configuration files: My docker-compose.yml: version: '3' services: db: image: postgres redis: image: redis:alpine web: image: nginx ports: - '80:80' volumes: - ./deploy/proxy.template:/etc/nginx/conf.d/proxy.template links: - cdn - app command: /bin/bash -c "envsubst '' < /etc/nginx/conf.d/proxy.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" cdn: image: nginx volumes: - ./cdn_static:/usr/share/nginx/static - ./deploy/cdn.template:/etc/nginx/conf.d/cdn.template command: /bin/bash -c "envsubst '' < /etc/nginx/conf.d/cdn.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" app: build: . image: app ports: - '8000:8000' links: - redis … -
django dictionary data into html table
I have following dictionary output data of python in browser {'pid': 0, 'name': 'System Process'} {'pid': 41, 'name': 'System123'} {'pid': 110, 'name': 'svchost.exe'} {'pid': 280, 'name': 'smss.exe'} {'pid': 336, 'name': 'WSE.exe'} {'pid': 424, 'name': 'csrss.exe'} but want to create a html / bootstrap table in my template such that the output table will look similar to: PID NAME 0 System Idle Process 41 System123 110 svchost.exe 280 smss.exe 336 WSE.exe .. .. .. ... my template code: <body> {% for obj in mydict_key %} <table > {{ obj }} </table> {% endfor %} </body> -
Could not find PyAudio check installation Error
I am trying to go live with my project and I am using PyAudio in it. I know that pyaudio requires port audio and it needs to be installed. All the requirements have been installed and pyaudio also installs successfully but when I try to execute the piece of code which uses pyaudio, I get the following error Could not find PyAudio; check installation In the traceback we can see the following piece of code import pyaudio except ImportError: raise AttributeError("Could not find PyAudio; check installation") The website is being hosted at web faction. -
Django Website Administration Broken
I have recently updated and the Django Website Administration has broken (I must add I do not know if that is the root cause of the problem as I have not used it for some time and have only just noticed it. I get the following error: Internal Server Error: /admin/ TemplateSyntaxError at /admin/ 'future' is not a registered tag library. Must be one of: account account_tags admin_list admin_modify admin_static admin_urls avatar_tags cache crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils dwadfilters humanize i18n l10n log mathfilters socialaccount socialaccount_tags static staticfiles tinymce_tags tz I have had a look round and some are suggesting it is a bug. Some say to downgrade to 1.8 (which is not an option). I will place the traceback at the bottom of this email. Many thanks in advance for any help. Traceback: File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 215. response = response.render() File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/template/response.py" in render 109. self.content = self.rendered_content File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content 86. content = template.render(context, self._request) File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/template/base.py" in render 208. return self._render(context) File "/usr/share/str8RED-virtualenv/local/lib/python2.7/site-packages/django/template/base.py" in … -
Django - 'TypeError: expected string or bytes-like object' when clearing an uploaded image with Cloudinary
I'm using Cloudinary in my Django application to store and serve images that users upload in one view of my site. The images are getting uploaded and shown correctly; however, in my UpdateView when a user checks 'clear' to remove the previous image and then submits the form this error is shown: TypeError: expected string or bytes-like object The error page in the browser also shows these highlighted messages: ...\lib\site-packages\cloudinary\models.py in to_python return self.parse_cloudinary_resource(value) ... ...\lib\site-packages\cloudinary\models.py in parse_cloudinary_resource m = re.match(CLOUDINARY_FIELD_DB_RE, value) ... ...\AppData\Local\Programs\Python\Python36-32\lib\re.py in match return _compile(pattern, flags).match(string) These are what my model, view and form look like: models.py: class Item(models.Model): name = models.CharField(max_length=255) image1 = CloudinaryField('image', blank=True, null=True) views.py class ItemUpdateView(LoginRequiredMixin, UpdateView): model = models.Item form_class = forms.ItemForm forms.py class ItemForm(forms.ModelForm): image1 = CloudinaryFileField( required=False, options = {'crop': 'limit', 'width': 546, 'height': 1000,}) class Meta: model = models.Item fields = ("image1", "name") I think Cloudinary is still expecting something when the field's value is empty. I have looked at the docs and searched the web and I just can't figure out how to fix this. -
Using relational operators for several fields in django model filter
I have a requirement to find a unique record depending on two date fields and a char field as follows. Start Date End Date Item No. (There will be unique item numbers.) Owner ID - This is what should be retrieved from the model. Provided: Data model is implemented such a way, within the Start and End dates Item can only be possessed by one owner. Requirement: When the Item No. and a Date is given, find the owner of the item within that day. Let say given day is D1, Start day S1 and End day E1. I know this should be using filter logic as follows. But how can I refer those fields in my query? (negative scenarios will be discarded) Filter: (d1 >= s1) AND (d1 <= e1) -
List is not JSON serializable
I have two classes Book and Basket. In this scenario, basket has more than one books. I have to serialize them in a proper order. I wrote a serialize query but it doesnt work. When im trying runserver, it returns homepage.views.Book object at 0x7f1afe3a8ef0 is not JSON serializable CLASSES class Book(object): def __init__(self,bookId,bookName,bookPrice,bookAuthor,bookYear,bookStar,bookCatagory): self.bookId=bookId self.bookName=bookName self.bookPrice=bookPrice self.bookAuthor=bookAuthor self.bookYear=bookYear self.bookStar=bookStar self.bookCatagory=bookCatagory class Basket(object): def __init__(self): self.numberOfProduct = None self.validate = None self.paymentValidate = None self.books = list() class UserClass(object): def __init__(self,id,name,surname,address): self.id = id self.name = name self.surname = surname self.address = address self.basket = Basket() def dummy(user): book = Book("1","1973","20TL","George Orwell","1999","4","Drama") book1 = Book("2", "Dönüşüm", "25TL", "Franz Kafka", "2001", "5", "Drama") book2 = Book("3", "Game of Thrones", "50TL", "George Martin", "2007", "5", "Drama") user.basket.books.append(book) user.basket.books.append(book1) user.basket.books.append(book2) @api_view(['GET']) def test(request): query = User.objects.filter(userName="berkin768").first() if (query != None): userId = query.userId name = query.name surname = query.surname address = query.address newUser = UserClass(userId, name, surname, address) dummy(newUser) serializer_class = BasketSerializer( data={'userId': newUser.id, 'name': newUser.name, 'surname': newUser.surname, 'address': newUser.address,'book': newUser.basket.books}) serializer_class.is_valid() return Response(serializer_class.data) SERIALIZER class BookSerializer(serializers.Serializer): bookId = serializers.IntegerField() class BasketSerializer(serializers.Serializer): userId = serializers.IntegerField() name = serializers.CharField(max_length=21) surname = serializers.CharField(max_length=21) address = serializers.CharField(max_length=51) book = BookSerializer(many=True) Thanks -
Associating Views to Models
I have been getting my head around these basics but i am not getting it right. I am trying to associate my view to my user model using team which is a foreign key Model class User(models.Model): first_name = models.CharField(max_length=200,blank=False) last_name = models.CharField(max_length=200, blank=False) class Gps(models.Model): location = models.CharField(max_length=200,blank=False) team= models.ForeignKey(User, on_delete=models.CASCADE) serializers class GpsSerializer(serializers.ModelSerializer): class Meta: model = Gps fields = ('id','location','team') view class Gps_list(generics.ListCreateAPIView): queryset = Gps.objects.all() serializer_class = GpsSerializer team = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault() ) -
Django Serialize Multiple Classes
I need to serialize two classes with each other but one of my classes contains list. That makes so complicated the whole process. I wrote something like this i know that it wont work. Scenario : A user has basket and this basket might store more than one book. Here is the deal. SERIALIZERS class BookSerializer(serializers.Serializer): bookId = serializers.IntegerField() bookQuantity = serializers.IntegerField() class BasketSerializer(serializers.Serializer): userId = serializers.IntegerField() name = serializers.CharField(max_length=21) surname = serializers.CharField(max_length=21) address = serializers.CharField(max_length=51) book = BookSerializer() CLASSES class Book(object): def __init__(self,bookId,bookName,bookPrice,bookAuthor,bookYear,bookStar,bookCatagory): self.bookId=bookId self.bookName=bookName self.bookPrice=bookPrice self.bookAuthor=bookAuthor self.bookYear=bookYear self.bookStar=bookStar self.bookCatagory=bookCatagory class Basket(object): def __init__(self): self.numberOfProduct = None self.validate = None self.paymentValidate = None self.books = list() class UserClass(object): def __init__(self,id,name,surname,address): self.id = id self.name = name self.surname = surname self.address = address self.basket = Basket() VIEW.PY def dummy(user): book = Book("1","1973","20TL","George Orwell","1999","4","Drama") book1 = Book("2", "Dönüşüm", "25TL", "Franz Kafka", "2001", "5", "Drama") book2 = Book("3", "Game of Thrones", "50TL", "George Martin", "2007", "5", "Drama") user.basket.books.append(book) user.basket.books.append(book1) user.basket.books.append(book2) MY FUNC userId = query.userId name = query.name surname = query.surname address = query.address newUser = UserClass(userName,userId,name,surname,address) dummy(newUser) serializer_class = BasketSerializer(data = {'userId': newUser.id, 'name' : newUser.name, 'surname' : newUser.surname, 'address' : newUser.address, 'book' : newUser.basket.books} -
Django HTML Template Cache
I have limited experience with Django but i am having an issue where I update the HTML Template file that serves an important view on our page and some users when they view the page do not get the updated view. Almost as if their device is caching the page. Now this page is not static and is dynamically generated on request. Now the part that I am changing is an embedded java script. My question is is there a way that part of the page can be cached while others are not from within the same template? -
Docker connection refused hanging Django
When I run my container, it just hangs on the next line and if I write curl http://0.0.0.0:8000/ I get Failed to connect to 0.0.0.0 port 8000: Connection refuse This is my dockerfile FROM python:3.6.1 # Set the working directory to /app WORKDIR /app # Copy the current directory contents into the container at /app ADD . /app RUN pip3 install -r requirements.txt CMD ["python3", "dockerizing/manage.py", "runserver", "0.0.0.0:8000"] I also tried doing it through a docker-compose.yml file and again nothing happens, I´ve searched a lot and haven´t found a solution, this is the docker-compose.yml version: "3" services: web: image: app1 deploy: replicas: 5 resources: limits: cpus: "0.1" memory: 50M restart_policy: condition: on-failure ports: - "8000:8000" networks: - webnet networks: webnet: By the way, if I run docker ps I get this: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e9633657f060 app1 "python3 dockerizi..." 5 seconds ago Up 5 seconds friendly_dijkstra -
Django Wagtail elastic search 2.4 ascii folding
Is it possible to set ascii folding on Wagtail elasticsearch 2.4 search backend so that e.g. searching for "Nimes" returns objects with "Nîmes" indexed? I tried adding the following settings: WAGTAILSEARCH_BACKENDS = { 'default': { 'BACKEND': 'app.search.backend', 'URLS': ['http://search:9200'], 'INDEX': 'wagtail', 'TIMEOUT': 5, 'INDEX_SETTINGS': { 'settings': { 'analysis': { 'analyzer': { 'ngram_analyzer': { 'type': 'custom', 'tokenizer': 'lowercase', 'filter': ['asciifolding', 'ngram'] }, 'edgengram_analyzer': { 'type': 'custom', 'tokenizer': 'lowercase', 'filter': ['asciifolding', 'edgengram'] }, "folding": { "tokenizer": "standard", "filter": ["lowercase", "asciifolding"] } } } } } } } But it doesn't work. I'm using Wagtail 1.9 on Django 1.10.7 with Python 3.5.2. -
Setting up MySQL database with Django
I am trying to set up MySQL with Django but don't know the correct way to set up MySQL after installing it and connecting it to my Django project. Any help would be greatly appreciated! -
Merging models, Django 1.11
After upgrading from Django 1.8 to 1.11 I've been looking at a means of merging some records - some models have multiple entries with the same name field, for example. There's an answer here that would appear to have what I would need: https://stackoverflow.com/a/41291137/1195207 I tried it with models like this: class GeneralType(models.Model): #... domains = models.ManyToManyField(Domain, blank=True) #... class Domain(models.Model): name = models.TextField(blank=False) #... ...where Domain has various records with duplicate names. But, it fails at the point indicated: for alias_object in alias_objects: for related_object in alias_object._meta.related_objects: related_name = related_object.get_accessor_name() if related_object.field.many_to_one: #...snip... elif related_object.field.one_to_one: #...snip... elif related_object.field.many_to_many: related_name = related_name or related_object.field.name for obj in getattr(alias_object, related_name).all(): getattr(obj, related_name).remove(alias_object) # <- fails here getattr(obj, related_name).add(primary_object) The problem is apparently that 'GeneralType' object has no attribute 'generaltype_set'. Adding a related_name to GeneralType doesn't fix this - the script fails in the same manner but quoting the name I've now given it. I'm not quite sure what Django is up to here so any suggestions would be welcome. -
How to exclude certain entries from meta ordering in django?
Hi I have the following given: class Copy(CommonLibraryBaseModel): signature = models.CharField(max_length=100, blank=True, verbose_name=u'Signatur') ... class Meta: ordering = ['signature'] What I want to do now is to define a ordering along the signature (this is already done with ordering = ['signature']), but exclude all signatures that start with a certain substring. How would I do that using the Meta class? Thanks