Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get method in DetailView changes data transmition to templates
I want to add a get method to my DetailView but it's not working. Once I add the get method, I loose the connection to the data on the template. #I tried to change {{ object.field_name }} to #{{ post.field_name }} #{{ object_list.field_name }} # in app views I write : class PostDetailView(DetailView): model = Post # in templates I write: <a>{{ object.author }}</a> # data is send to templates and it works fine # But then I want to add a get/post to the view: class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' def get(self, request, *args, **kwargs): form = HomeForm() return render(request, self.template_name, {'form':form}) # Once I add the get method , data is not rendering on my template. If someone could help me to figure out why data is not rendering in templates once I add the get method to my DetailView, it would be great. I've spent the afternoon/night searching but now my brain is fried...help, pls . tx tx ! -
A model with 4 fields, two of them give error:"add a non-nullable field....". my question is why other two fields dont give error
here is the full error: You are trying to add a non-nullable field 'summary' to product without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py My first question is why not all fields give me the error even tough they are identical fields? Second question how can I fix this without typing this: TextField(default="any string") //models.py from django.db import models class Product(models.Model): title=models.TextField() description=models.TextField() price=models.TextField() summary=models.TextField() //admin.py from django.contrib import admin from .models import Product admin.site.register(Product) //command python manage.py makemigrations my admin page has "Product" tab. When I create a product in admin window, i have only two fields. description and price. -
Django FormSet - [The data corresponding to the ManagementForm does not exist or has been modified]
I'm currently working with the nestedformset_factory bookstore for Django, because I have the following situation, I have a Restaurante model and a TipoCarta model (which would be how the possible sections of the menu), each restaurant, adds one or many Letters to its menu, which selects from the records available in the table TipoCarta. In addition, each letter can have from one to many products. (I attach the model of the domain of said situation) Domain model The problem that I have, is that I must show the user a form where I can register a restaurant and in it, I can add their respective letters and each letter, I can add their respective products, with their prices, but when I have to save in my database registered data, Django shows me the following error: Error But when I inspect the page and the data that was sent in the POST, everything seems normal: POST class RestauranteCreateView(LoginRequiredMixin, CreateView): model = Restaurante template_name = 'calculadora/restaurante.html' form_class = RestauranteForm success_url = reverse_lazy('calculadora:restaurantes') def get(self, request, *args, **kwargs): super(RestauranteCreateView, self).get(self, request, *args, **kwargs) context = self.get_context_data(**kwargs) context['carta_formset'] = nestedformset_factory( Restaurante, Carta, form=CartaForm, min_num=1, max_num=5, extra=0, can_delete=False, nested_formset=inlineformset_factory( parent_model=Carta, model=Producto, form=ProductoForm, min_num=1, max_num=20, extra=1, … -
Django RestFramework - parent-child model serializer with DB views?
I am trying to implement a serializer that returns a parent record with its children embedded in the response json object. My model for the parent and child are both based on database views: class ProductContributorView(models.Model): # its a model of a view id = models.IntegerField(primary_key=True) product_id = models.ForeignKey('ProductTitleView', on_delete=models.DO_NOTHING, related_name='contributors') sequenceNumber = models.IntegerField() name = models.CharField(max_length=180) role = models.CharField(max_length=8, null=True) description = models.CharField(max_length=1408) class Meta: managed = False ordering = ['sequenceNumber',] class ProductTitleView(models.Model): id = models.IntegerField(primary_key=True) isbn = models.CharField(max_length=80) titleText = models.CharField(max_length=300) class Meta: managed = False ordering = ['titleText', 'isbn',] Here are the serializers: class ProductContributorViewSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ProductContributorView fields = ('id', 'product_id', 'sequenceNumber', 'name', 'role', 'description') def create(self, validated_data): contributor = ProductContributorView.objects.create( id=validated_data['id'], product_id=validated_data['product_id'], sequenceNumber=validated_data['sequenceNumber'], name=validated_data['name'], role=validated_data['role'], description=validated_data['description']) return contributor class ProductTitleViewSerializer(serializers.HyperlinkedModelSerializer): contributors = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = ProductTitleView fields = ('id', 'isbn', 'titleText', 'contributors') Here are the views: class ProductTitleViewList(generics.ListAPIView): queryset = ProductTitleView.objects.all() serializer_class = ProductTitleViewSerializer class ProductContributorViewList(generics.ListAPIView): queryset = ProductContributorView.objects.all() serializer_class = ProductContributorViewSerializer The basic idea is to have the contributors - author, illustrator, etc - returned with the book title based on the FK in the ProductContributorView view matching the id in the ProductTitleView. When I run this, however, I … -
Crispy Formset generating one form tag per form
I have a formset that works fine when I go in the page, but if it renders after a post (and has errors), it will re-create the html with one <form> tag inside the main <form> tag. Here is my form: class ReservaForm(forms.ModelForm): saida = forms.ModelChoiceField(queryset=Saida.objects.filter(status=True,day__gte=date.today()),widget = forms.HiddenInput()) Here is my view (pertinent part only): ReservaFormSet = formset_factory(ReservaForm, extra=1,max_num=8) formset = ReservaFormSet() if request.POST: formset = ReservaFormSet(request.POST, request.FILES) if formset.is_valid(): #do_magic context['formset']=formset return render(request,'saidasMultiplas.html',context) Here is my template: <form method="POST" id="reservaFormset" class="d-none" action="/xpto/"> {% csrf_token %} {{ formset.management_form|crispy }} <div class="accordion" id="accordionExample"> {% for xForm in formset %} <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Xpto </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne"> <div class="card-body"> {% crispy xForm %} </div> </div> </div> {% endfor %} <button type="submit" class="btn btn-success">Avançar</button> </div></form> -
How to add categories in a dropdown menu by retrieving the options from database in django?
I want to add categories in drop-down menu by fetching the text from the database. When i call the object from views.py file in templates, categories are not displayed in my drop-down. I have tried generic views as well but my problem is still there. I have also searched for my answer on stackoverflow but most of them in this regard are unanswered or if answered didn't resolve my issue. template.html <div class="input-group-btn search-panel"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <span id="search_concept">Category</span> <span class="caret"></span> </button> <select class="dropdown-menu" name="dropdown"> {% for category in category_list %} <option value="{{ category.name }}">{{ category.name }}</option> {% endfor %} </select> </div> models.py class Category(models.Model): name = models.CharField(max_length=128, unique=True) def __str__(self): return self.name views.py def CategoryView(request): category_list = Category.objects.all() context = {'category_list': category_list} return render(request,'search/search_form.html', context) Please if anyone could help? -
Django ORM get latest item for each group
I am using Django 2.2.1 with MariaDB 10.3.15. I have this models: class Hose(models.Model): description = models.CharField(blank=True, max_length=250) number = models.IntegerField(unique=True) class HoseHistory(models.Model): class Meta: unique_together = (("date", "hose", "hose_event"),) date = models.DateTimeField() description = models.CharField(blank=True, max_length=250) hose = models.ForeignKey(Hose, on_delete=models.CASCADE) hose_event = models.ForeignKey(HoseEvent, on_delete=models.CASCADE) Now I want to get a list of all entries of the Hose Table with, if there is one, the latest HoseHistory row. The resultset should look like that: | Hose.description | Hose.number | HoseHistory.date | HoseHistory.description | =============================================================================== | Example A | 1 | 2019-01-09 | Event A | | Example B | 2 | NULL | NULL | So in detail Django should create a SQL Query which selects the Tabele Hose, LEFT JOINs the table HoseHistory, then group by Hose.number and then all MAX on HoseHistory.date. I tried for example: Hose.objects.values("number").annotate(max_date=Max("hosehistory__date")).order_by("hosehistory__date") But the problem is that with this strategy I only have the column max_date and number, if I add more columns those will be added to the GROUP BY Statement and this query will not work. -
Do orderings in models improve performance in querysets?
Sorry, I’m... let’s say not the best conceptually with DBs plus Django... Anyhow, I’m pretty sure ordering does the opposite of the aforementioned. But simply to check: in class Meta, the ordering only assists when Django queries in which it’ll order the queryset when returning via view, correct? Example: models.py class Test(models.Model): id = models.BigAutoField(primary_key=True) secondAttr = models.OneToOneField(Wall, on_delete=models.CASCADE) # There are 10 more columns for other stuff class Meta: ordering = [‘-secondAttr’, ‘id’] SecondAttr is the pk of a BigAutoField in a different table, ofc; secondAttr could go all the way up to 193,017,273. I’m planning on id being a surrogate pk. The query is looking for any objects with secondAttr being 80; let’s say there are 100 objects with secondAttr = 80. These objects are scattered EVERYWHERE throughout table Test (e.g. row 1, row 101,927,018, row 930,029,019, etc.), if I delete the ordering in Meta that is(, right?). So, will ordering assist in query performance? Or does ordering have NOTHING to do with query performance? Suggestions for what I SHOULD do? Or should I simply not worry? Unfortunately, indices wouldn’t really help in this scenario, now would it? -
Render related objects into Template
I'm trying to render a One to Many field into my Template, but i'm not able to render the Subtask part into my Template. Pure overview of my model: Each TaskID has multiple subtasks that I want to save to my database. And when I query the TaskID I want to list the related Subtasks using a for loop into my template. class Task(models.Model): TaskID = models.CharField(max_length=128) class Subtask(models.Model): SubtaskID = models.CharField(max_length=128, default="Awaiting Query") SubtaskNode = models.CharField(max_length=24, default="Awaiting Query") SubtaskStatus = models.CharField(max_length=15, default="Awaiting Query") Task = models.ForeignKey(Task, on_delete=models.CASCADE) Views: query_intro = Task.objects.filter(TaskID="123") return render(request, 'faq.html', {"query":query_intro} ) Template: {% for p in query %} {{ p.TaskID }} {% for id in p.Subtask_set.all %} {{ id.SubtaskID }} {% endfor %} {% endfor %} TaskID is succesfully rendered into the template but i'm not able to render any of the Subtask part. -
The error was: relation "djkombu_queue" already exists
When I pull the data and tried python manage.py syncdb python manage.py migrate It shows The error was: relation "djkombu_queue" already exists -
Optimizing model design based on multiple relationships
I am trying to create a league leaderboard which I am trying to decide on an optimal structure to avoid problems down the line. Currently I have three models representing the data I wish to collect. Season, Challenge, Attempt. class Season(models.Model): season = models.CharField(max_length=4) start_date = models.DateTimeField() end_date = models.DateTimeField() class Challenge(models.Model): season = models.ForeignKey(Season, on_delete=models.CASCADE) name = models.CharField(max_length=255) start_date = models.DateTimeField() end_date = models.DateTimeField() class Attempt(models.Model): challenger = models.ForeignKey(User, on_delete=models.CASCADE) challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) points = models.IntegerField(default=0) Now, I'm assuming the following statements are true in what I wish to get out of this. A season runs for one year A challenge runs for one month A season can have many challenges A challenge can have many attempts A challenge cannot belong to more than one season An attempt cannot belong to more than one challenge. The difficulty I feel is going to present when I try and display the data. I would like to return a leaderboard for the current season, which calculates the best attempt for a user for each challenge and returns a query set with the user and their total points for the whole season. Example data Season(season='2019', start_date=..., # some date object end_date=..., # … -
Django Form doesn't add new object to ManyToManyField but switch between other
I'm trying to update object by adding new user to permission, and if i'm updating it doesn't add user but set other users which have this permission are unselected. views.py elif(request.POST['custom'] == 'assign'): guest = Departments.objects.get(id=request.POST['id']) print(request.POST) form = AddDepartment() form2 = AssignDepartment(data=request.POST, instance=guest) if form2.is_valid(): department = Departments.objects.get(department = form2.cleaned_data['department']) print(form2.cleaned_data['user']) print(form2.cleaned_data['user'][0].id) department.user.add(Person.objects.get(id=form2.cleaned_data['user'][0].id)) form2.save() models.py department = models.CharField(max_length=60, verbose_name='Oddziały', unique=True) user = models.ManyToManyField('Person', blank=True, verbose_name='Pracownik') -
How can I efficiently save data from geopandas to django (converting from shapely to geodjango)?
I am manipulating GIS data w/ geopandas and storing it in various Django models. geopandas uses shapely under-the-hood while Django does not. Here is some code: import geopandas as gpd from django.contrib.gis.db import models class MyModel(models.Model): geometry = models.PolygonField() name = models.CharField(max_length=255, null=False, unique=True) some_property = models.IntegerField() gdf = gpd.read_file("some_data.geojson") # ...do some stuff w/ gdf... for data in gdf.to_dict("records"): name = data.pop("name") MyModel.objects.create_or_update( name=name, defaults=data, ) The above will fail w/ errors like: TypeError: Cannot set MyModel SpatialProxy (POLYGON) with value of type: <class 'shapely.geometry.polygon.Polygon'> Unless I add some icky code like: from django.contrib.gis.geos import fromstr, Polygon data["geometry"] = Polygon(fromstr(str(data["geometry"]))) Is there any way to avoid this and directly map from shapely to Django? -
Django, Value Error: invalid literal for int() with base 10: '' when trying remove an object from manytomany
I'm working on a mockup e-commerce site using Django and wagtail CMS. I'm running into problems removing items to my cart app. I'm using a POST method which updates the cart based on a product id. It works as a toggle, if object in cart: remove else: add. It works fine on the product page but when I try to remove on the cart page I get ValueError at /cart/update/ invalid literal for int() with base 10: '' It seems as if the product id isn't getting passed? This is the HTML for the button which triggers the POST method <form method='POST' action='{% url "cart:update" %}' class="form"> {% csrf_token %} <input type="hidden" name="product_id" value="{{ self.id }}" /> {% if incart %} <button type="submit" class="btn btn-danger btn-md my-0 p btn-sm" type="submit"> Remove </button> {% else %} <button type="submit" class="btn btn-primary btn-md my-0 p" type="submit">Add to cart <i class="fa fa-shopping-cart"></i> </button> {% endif %} </form> This is my cart view def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: product_obj = Product.objects.get(id=product_id) cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) else: cart_obj.products.add(product_obj) return redirect("cart:home") -
Celery TaskFormatter adds extra garbage characters around log message
So I have set up logging from Celery tasks in a Django project. When I set up celery I do the following: app.config_from_object('django.conf:settings', ) app.conf.update({'CELERYD_HIJACK_ROOT_LOGGER': False}) @after_setup_task_logger.connect def setup_task_logger(logger, *args, **kwargs): for handler in logger.handlers: logger.debug("Setting formatter for handler: {}".format(handler)) handler.setFormatter( TaskFormatter( "%(asctime)s.%(msecs)03d %(levelname)-8s %(name)-10s [%(filename)s].[%(funcName)s]: %(message)s")) So when I do @app.task(time_limit=36000, name="sync") def syn(request, user, current_url_is): logger.debug("sync task STARTED") I get the following: [1;34m2019-05-24 15:21:06,535.535 DEBUG dashboards.tasks [tasks.py].[sync]: sync task STARTED[0m Clearly the first 7 and the last 3 characters should not be there. Is there a bug with the TaskFormatter? Python version: 3.6.7 Celery version: 3.1.18 -
How do I change how Wagtail serves media over it's API?
I'm currently trying to create a web application that uses Django + Wagtail for its backend content, and React for the frontend. As of now, upon pageload, I request all of the 'articles' from Wagtail via an http GET request. I then display this data in my frontend components. This has worked well, except for one issue that I have, which is that media within the article body is represented as an <embed /> tag with a local source. What I'd like instead is an <img /> tag with the src pointing to the url that the image is stored in. How can I go about changing this on the backend? I can't seem to find any kind of documentation regarding this issue. Here's what my get request response currently looks like: { "id": 9, ... "title": "Child page", "date": null, "body": "<p>Here is a test image:</p><embed alt=\"testimg\" embedtype=\"image\" format=\"fullwidth\" id=\"5\"/><p></p>", "author": "Isaac" } Here's what I'd like it to look like: { "id": 9, ... "title": "Child page", "date": null, "body": "<p>Here is a test image:</p><img src="image-location-url"/><p></p>", "author": "Isaac" } How should I go about this? Is this controllable with Wagtail settings configurations? Or should I be changing my … -
Display Field Based Errors in Django Template
I'm using the code found on the following page: https://docs.djangoproject.com/en/2.2/ref/forms/validation/ In particular, the following: from django import forms class ContactForm(forms.Form): # Everything as before. ... def clean(self): cleaned_data = super().clean() cc_myself = cleaned_data.get("cc_myself") subject = cleaned_data.get("subject") if cc_myself and subject and "help" not in subject: msg = "Must put 'help' in subject when cc'ing yourself." self.add_error('cc_myself', msg) self.add_error('subject', msg) But I can't access the errors in the template using the field as follows: {{ form.cc_myself.errors }} Has anyone experienced this issue? Any help would be greatly appreciated. Thanks. -
How to add multiple values under 1 column in database
I need to create a model that allows me to store multiple values under the same column. I'm not sure if this is possible or i'm thinking of the right way to do it. Any feedback is greatly appreciated. TaskID = models.CharField(max_length=128) SubtaskID = models.CharField(max_length=128) SubtaskNode = models.CharField(max_length=24) SubtaskStatus = models.CharField(max_length=10) In my project you can create a task which outputs a Task ID for later querying. And in a task there's n amount of subtasks created also. So i'm wondering how I could store the multiple values of the subtasks on my TaskID? Example of structure of how they could look: TaskID = c07de590-678f-45a2-b6ac-1110c201037b SubtaskID1 = 87da261e-530d-40e8-8a8b-b61507c6eba2 SubtaskNode1 = Node1 SubtaskStatus1 = Waiting SubtaskID2 = 140bb0a4-2cdb-46f0-b62d-9187592ae1e9 SubtaskNode2 = Node2 SubtaskStatus2 = Waiting SubtaskID3 = 43e64d3a-a088-4aae-8a57-64e1c4dfba08 SubtaskNode3 = Node3 SubtaskStatus3 = Finished SubtaskID4 = 324083fb-b9e9-471f-8946-21ed426fc646 SubtaskNode4 = Node4 SubtaskStatus4 = Failed The purpose of all of this to later create a for loop in my template to list all SubtaskID's under the TaskID value. -
didn't return an HttpResponse object. It returned None instead
The view accounts.views.register didn't return an HttpResponse object. It returned None instead. views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/accounts') else: form = RegistrationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) urls.py: path('register/', views.register, name='register'), This occurs once ive filled all fields and pressed register. -
super() argument 1 must be type, not PostCreateView - an error occures
I am creating a blog app in Django 2.2.1 version.( python 3.7) When a logged in user create a new post it gives me below error TypeError at /post/new/ super() argument 1 must be type, not PostCreateView it says error is in line 66 of my view.py file, which I mention below class PostCreateView(LoginRequiredMixin,CreateView): model = Post fields = ['title', 'content','phonenumber','state','Catagory','district','price', 'userimage', 'userimage2', 'userimage3'] def form_valid(self, form): form.instance.author = self.request.user return super(self, form).form_valid(form) #line 66 url pattern as below path('post/new/', PostCreateView.as_view(), name='post-create'), -
how to fix not displaying form widget in html
i'm new in django. I need to create the form widget as an input to push the data from input to script. The problem is that my form does not display and I have no idea where is the mistake. My goal is to get data from input so it will be found in database api and saved in my db. Appreciate for advice. views.py def data(request): url = 'http://www.omdbapi.com/?t={}&apikey=My key is here' if request.method == 'POST': form = MovieForm(request.POST) form.save() form = MovieForm() movies = Movie.objects.all() #// fetch all objects movies_data = [] #//// array for movies and their details for movie in movies: r = requests.get(url.format(movie)).json() #// gets details from api movies_main = { 'title': movie.title, 'director': r['Director'], 'rate': r['imdbRating'], } movies_data.append(movies_main) context = {'movies_data':movies_data} return render(request, 'movies/movies.html', context) forms.py from django.forms import ModelForm, TextInput from .models import Movie class MovieForm(ModelForm): class Meta: model = Movie fields = ['title'] widgets = {'title' : TextInput(attrs={'class' : 'id', 'placeholder' : 'put your id' })} models.py from django.db import models # Create your models here. class Movie(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.title class Meta: verbose_name_plural = 'movies' template {% load static %} <html> <head> <link rel="stylesheet" href="{%static 'movies/style.css' %}"> … -
Django gather instance from selectable inputs of multiple models and post to another model
I didn't even know how to write what I want to achieve on the title. I have 3 models, lets say: Country City: foreign key yo country Person: foreign key yo city Each of them has it's own attributes and those foreign keys I've shown. What I want to do is, write a form that has 2 selectable fields, one for country and another for city. An providing those two values, It get's the instance of Person so that the rest of the fields get rendered and the user populates them in order to save it on the database. I've seen that in order to display cities according to the country provided I need to write some javascript, but they show how to do it if the model that holds the foreign keys is just one. In my case there are three, one references the other. Is this achievable? If so could someone guide me towards the solution? Thanks! -
Serializing Foreign Key Field
I have the following models: class Question(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) text = models.CharField(max_length=255,default='',blank=False) number = models.IntegerField() def __str__(self): return self.text class Test(models.Model): PRIVACY_TYPES = ( ('PR', 'Private'), ('PU', 'Public'), ) user = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=255,default='',blank=False) datecreated = models.DateTimeField(auto_now=True) privacy = models.CharField(choices=PRIVACY_TYPES, default='PR',max_length=15) testtime = models.IntegerField(default=30) class User(AbstractBaseUser, models.Model): username = models.CharField(max_length=20,default='',blank=True) password = models.CharField(max_length=80,default='',blank=True) email = models.CharField(max_length=255,default='',blank=True) I am trying to serialize the test object to also include the username and id from the User model. Here is the serializer I am trying: class TestSerializer(serializers.ModelSerializer): question_set = QuestionSerializer(many=True) user = UserSerializer(source='user') class Meta: model = Test fields = ('id', 'name', 'privacy', 'testtime', 'user', 'question_set') related_object = 'question' The user serializer looks like: class UserSerializer(serializers.Serializer): class Meta: model = User fields = ('id', 'username') The question set serializes fine this way, but with the relationship the other way round, if that is the right way to describe it, for user then I get an empty object with this code. I have tried user_username and user.username in the fields, but that doesn't work. I have searched online and looked at the Django-Rest-Framework documents, but can only find examples where the relationship is as the question to test. -
How to build forms for related models
I am trying to build a training video/quiz app and im not sure exactly how to build the forms. I have built out the quiz, questions, and answers models. The quiz is dependent on which chapter the user is in. models.py class Quiz(models.Model): quiz_name = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True) chapter = models.ForeignKey(Chapter, on_delete=None, null=True) def __str__(self): return self.quiz_name class Question(models.Model): question = models.CharField(max_length=255) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions') creator = models.ForeignKey(User, on_delete=None) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question class Answer(models.Model): answer = models.CharField(max_length=255) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') is_correct = models.BooleanField(default=False) def __str__(self): return self.answer How do I create a form in my forms.py that will give me the quiz specific to the chapter they are in and that will return the answer options to the question as radio buttons? -
How to register postgres to send CIDR data in a proper format
I am trying to recreate something on an old Django 1.8.19 system. Figuring out how this used to work is crucial to what I have to do to recreate it in the supported levels of Django. I have a Django model with a netfields.CidrAddressField field which I believe is stored as a CIDR field in Postgress. But whenever I receive a QuerySet from postgres, I receive a ProgrammingError exception. I'm assuming that Postgres cannot marshal the data into a format that Python can understand. Thanks I believe this is due to a required psycopg2.extras.register that is not installed. But I believe I've tried all of them. The definitions are: from django.db import models import netfields import ipaddress class MyCIDR(models.Model): net_cidr = netfields.CidrAddressField() The code is: new_cidr = ipaddress.IPv4Network(u'1.2.3.4/24') MyCIDR.objects.extra(where=['net_cidr = %s'], params=[new_cidr]) The error message is: ProgrammingError: can't adapt type 'IPv4Network' I expected to receive a list of MyCIDRs [ MyCIDR(u'1.2.3.4/24')]