Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to cascade delete on one to one both sides in django?
I have the models set as follows: class CodeConstraint(models.Model): must_not_have = models.TextField() class Question(models.Model): code_constraint = models.OneToOneField(CodeConstraint, on_delete=models.CASCADE, null=True) When i delete CodeConstraint the associated Question will be deleted. I would like the cascade to go the other way as well i.e when i delete Question the associated CodeConstraint should also be deleted. How do i achieve this behavior? I appreciate any help. Thanks! -
Problems in login with django api
Hello I am learning to make api with django I am in the login part but for some reason when I try to login and the token is generated it gives me this error how can I solve it Internal Server Error: /gateway/login Traceback (most recent call last): File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\gateway\views.py", line 51, in post Jwt.objects.create( File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\django\db\models\query.py", line 451, in create obj = self.model(**kwargs) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\django\db\models\base.py", line 485, in init _setattr(self, field.name, rel_obj) File "D:\Users\ferna\Documents\Cursos\youtube\djangoRest\django_api\env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in set raise ValueError( ValueError: Cannot assign "7": "Jwt.user_id" must be a "CustomUser" instance. [04/May/2021 22:00:06] ←[35;1m"POST /gateway/login HTTP/1.1" 500 127750←[0m it's code from model class Jwt(models.Model): user_id = models.ForeignKey(CustomUser, related_name='login_user', on_delete=models.CASCADE) access = models.TextField() refresh = models.TextField() created_at … -
Django - Navigate through forms (backwards/forwards) without creating/deleting objects in the database
I have these two models, Task and PaymentCondition, both depend of my Contract model. These are the details of how things should work: Create object Contract view. Create contract view Next, create objects Task view, with inline_formsets, asociated to Contract. Create Task view Once the Tasks were created, it should go to the create PaymentCondition view. The problem is: what if I hit cancel when I'm on Tasks or PaymentConditions views? Should I erase from the db the object I created a step ago? Is there a way to save the forms untill I create the last object, that is PaymentConditions, save the object Contract and then asociate its child models to it? This is how my forms, templates and views look like: models.py class Contract(models.Model): some_field class Task(models.Model): contract = models.ForeignKey('Contract', on_delete=models.CASCADE) ... class PaymentCondition(models.Model): contract = models.ForeignKey('Contract', on_delete=models.CASCADE) ... forms.py class FormCreateContract(forms.Form): .. def save(self): data = self.cleaned_data contract = Contract(data) contract.save() return contract.id views.py def create_contract(request): form = FormCreateContract if request.method == 'POST': form = FormCreateContract(request.POST) if form.is_valid(): pk = form.save() return redirect(f'{pk}/tasks/create') context = {'form':form} return render(request, 'contracts/create.html', context) def create_task(request, pk): TaskFormSet = inlineformset_factory(Contact, Task,fields=('fields'), can_delete=False, extra=5) contact = Contract.objects.get(id=pk) formset = TaskFormSet(queryset=Task.objects.none(), instance=contract) if … -
Bootstrap table cell based on another cell value
I am using Bootstrap tables from this site Bootstrap Tables and I return data to the table using Django. One of the columns is a date filter and another column includes a “edit” and “delete” button. I would like the buttons to only appear if the date is within a date range. -
Login to test client by patching custom backend in django test
I'm trying to start writing some tests on some views, but my project uses a 3rd party login system, and I have a custom auth backend BarBackend that interfaces with this. The views I'd like to test are protected by LoginRequiredMixin. I figure I will somehow need to patch logging in with the test client to access these and test them. My goal is to create a user, and then log that user in with my patched backend, so that I can do things such as self.client.get('some-url-with-login-required'). How can I do this? My attempt so far has gotten me here: class FooTest(TestCase): def setUp(self): self.user = User.objects.create(username='user', email='test@example.com') @patch('identity.backends.BarBackend.authenticate') def test_can_access_with_groups(self, mock_auth): mock_auth.return_value = self.user self.client.login() Code is failing on self.client.login. Here's the stacktrace just in case (with some of the paths removed/renamed): Traceback (most recent call last): File "/usr/lib/python3.8/unittest/mock.py", line 1342, in patched return func(*newargs, **newkeywargs) File "project_name/apps_dir/nzplatform/tests/test_site_access.py", line 32, in test_can_access_with_groups self.client.login() File ".venv/lib/python3.8/site-packages/django/test/client.py", line 585, in login user = authenticate(**credentials) File ".venv/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 67, in authenticate inspect.getcallargs(backend.authenticate, request, **credentials) File "/usr/lib/python3.8/inspect.py", line 1336, in getcallargs f_name = func.__name__ File "/usr/lib/python3.8/unittest/mock.py", line 637, in __getattr__ raise AttributeError(name) AttributeError: __name__ -
django exception Object of type 'User' is not JSON serializable?
I'm getting the error mentioned in the title of this question. Here i'm wokring with django only. Not using django restframework. The point is i want to query user with a json response from the user model. How can i do that ? class ProfileManager(models.Manager): def toggle_follow(self, request_user,user_id, username_to_toggle,json_follower): profile_ = UserProfile.objects.get(user__username__iexact=request_user.username) is_following = False follower = profile_.follower.filter(username__iexact=username_to_toggle).first() if follower: profile_.follower.remove(follower.id) actor = User.objects.get(pk=user_id) user = User.objects.get(username=username_to_toggle) json_follower = user else: new_follower = User.objects.get(username__iexact=username_to_toggle) profile_.follower.add(new_follower.id) actor = User.objects.get(pk=user_id) user = User.objects.get(username=username_to_toggle) notify.send(actor, recipient=user, verb='follow you') json_follower = new_follower is_following = True return profile_, is_following,json_follower -
Am receiving => NameError: name 'ModelAdmin' is not defined,
Please help me in solving this code, I just want to print the employee details in the template through model and please help me in fixing this... #----***admin.py****------- from django.contrib import admin from dbapp.models import Employee class EmployeeAdmin(admin,ModelAdmin): emp_details=['empNo','empName','empSalary','empAddress'] admin.site.register(Employee, EmployeeAdmin) #___***models.py******______ from django.db import models class Employee(models.Model): empNo = models.IntegerField() empName = models.CharField(max_length=20) empSalary = models.IntegerField() empAddress = models.CharField(max_length=50) def __str__(self): return 'Employee details are shared' + empName #______*****views.py***___ from django.shortcuts import render from dpapp.models import Employee def empDetails(request): emp_data =Employee.objects.all() emp_dict = {'emp_list':emp_data} return render(request, 'dbapp/db.html', context=emp_dict) -
PostgreSQL - create a generated column for a column that already exists
I have the following raw SQL command that I am executing inside a Django migration file. I need to use raw SQL because Django does not support generated columns. ALTER TABLE dockets_document ADD COLUMN search_vector tsvector GENERATED ALWAYS AS ( setweight(to_tsvector('english', coalesce(title, '')), 'A') || setweight(to_tsvector('english', coalesce(f_arr2text(content),'')), 'B') || setweight(jsonb_to_tsvector('english', coalesce(tables), '["all"]'), 'C') ) STORED; My models.py file has the following field: search_vector = SearchVectorField(null=True) This line triggers a migration that generates the column for me, then my custom migration applies the SQL. The custom migration fails because the column was already created (with a corresponding index) so ADD COLUMN returns the error ERROR: column "search_vector" of relation "dockets_document" already exists. I tried using ALTER COLUMN in place but it did not work (ERROR: syntax error at or near "tsvector"). I tried removing the field from the models.py file but then Django doesn't know that the field exists and won't allow me to query against the column. And it doesn't feel right to remove it either. How can I convert the existing null column into a GENERATED column instead? -
How can i update data to a related field before saving Django model form
I am trying to update the user instance of an assigned file when the file is transferred. The transfer POST action goes through successfully without any errors but then the user instance of the file model is not updated with "transfer_to" user instance. This is what I have done so far: models.py class File(models.Model): file_type_choice = ( ('General', 'General'), ('Personal', 'Personal') ) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='files') file_type = models.CharField(max_length=250, choices=file_type_choice) file_name = models.CharField(max_length=250) recipient_name = models.CharField(max_length=250) def __str__(self): return f'{self.file_name}' def get_absolute_url_file_transfer(self): return reverse('file_transfer', args=[self.pk]) class Transfer(models.Model): file = models.ForeignKey('File', on_delete=models.CASCADE, null=True) transfer_from = models.ForeignKey(User, on_delete=models.CASCADE, related_name='transfers_from', null=True) transfer_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='transfers_to', null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.transfer_from} {self.transfer_to}' forms.py class FileTransferForm(forms.ModelForm): class Meta: model = Transfer fields = ['transfer_from', 'transfer_to', ] views.py def file_transfer(request, pk): file = get_object_or_404(File, pk=pk) if request.method == "POST": form = FileTransferForm(data=request.POST) if form.is_valid(): form_edit = form.save(commit=False) form_edit.file = file file.user = form_edit.transfer_to form_edit.save() return redirect('outgoing_file_list') else: form = FileTransferForm() context = { 'form': form, 'file': file, } return render(request, 'file_transfer.html', context) -
How to pass parameters to modify a decorator that takes a function with parameters
I have to create a decorator that has parameters, and uses those parameters to modify a function also with parameters. This is a general question of how to decorate any function with parameters with additional parameters, but for my specific case, I need it for Django RQ, to determine based on an environment variable whether to use an asynchronous queue that is activated through a decorator. There is a function in Django RQ called django_rq.job that I use like this (it requires args and kwargs): @django_rq.job('default', timeout=3600, result_ttl=86400) def upload_missing_documents_s3(batches, projects, uuid_val): pass # A simpler example: @django_rq.job('default', timeout=3600, result_ttl=86400) def sample(content): file = open("temp/sample.txt", "w+") file.write(content) file.close() I need to essentially create a decorator that will take a boolean value and return either the modified function (with a job) or the unmodified function (no job). But I can't seem to figure it out, because there are two sets of parameters. I tried something like this: #My attempt, I don't think it works... def conditional_django_job(function_name, *args, **kwargs): if settings.NO_QUEUE: return function_name else: return django_rq.job("default", None, *args, **kwargs)(function_name) @conditional_django_job('default', timeout=3600, result_ttl=86400) def sample(content): file = open("temp/sample.txt", "w+") file.write(content) file.close() I also tried with an inner function, but I can't seem to … -
How to delay Django queryset execution in a Graphene resolver function?
I am using graphene/graphene-django without relay as an API for a highly nested data model with both foreign key and m2m relationships across tables. I am also using offset limit pagination via slicing since in many places I am returning lists of objects that can potentially be very large. However, I am finding that my queryset is executing too early before I can slice it, thus negating any database benefits I'd get with using pagination. Here's a simplified example of my schema to help illustrate: class BookType(ObjectType): id = String() binding = Field(BindingType) (... Some other attributes) def resolve_binding(parent, info): return parent.binding class BookListType(ObjectType): total_count = Int() results = List(BookType, limit=Int(), offset=Int()) def resolve_total_count(parent, info): return parent.count() def resolve_results(parent, info, offset, limit): return parent[offset : (limit + offset)] class UserListType(DjangoObjectType): books = Field(BookListType, (various filtering arguments)) class Meta: model = UserList def resolve_books(parent, info, **kwargs): return <Some Expensive and Complex Django ORM Query> So say I am fetching a UserList along with all of its books. I build up the query that I need and return it from the resolve_books function, which then gets passed to the BookListType which applies pagination from input arguments. However, it seems like as soon … -
Use variable in template Django template logic
if I have a dictionary {{tokens}} being rendered in my Django template using that outputs: {26: <Token: 0c90dd25e8bc07578725160349fd6fedac776afb>, 28: <Token: 6e3bb042eb4ea05918e26b80a2c6d7fada99cf86>, 29: <Token: ca4dc6ccc893605195002be986a07142d96f3371>, 42: <Token: 2f157eb152b818b5ca53d63344279626a73a4e38>} I can access dictionary key 26 value in my template by using {{tokens.26}} But how can I access these values if I am using a queryset to access it? For example, I want to do something like: {{tokens.machine.id}} where `{{machine.id}} is equal to 26. This doesn't work. I have also tried: {% with machine.id as machineID %} {{ tokens.machineID }} {% endwith %} This outputs nothing. -
Django : Grabbing Template data from views.py
I have a django project. I get user input, then interact with an API that returns a list. I turn that list into a JSON object and pass it to the template. A static javascript file runs to create buttons, from the values in the JSON object. I do this because the list length changes, so there is a dynamic number of buttons based on user input. I want these button clicks to be saved. My methodology so far has been to give unpressed buttons a button id (ex. button.id = 'unpressed';), and pressed buttons a different id(ex. button.id = 'pressed';). The last step, the one I am having trouble with, is finding some way for a button press to trigger a django python function, or some function in the template itself that triggers a django python function, and having the ability to poll the id of all of the buttons to save to a dictionary. I have looked around for an answer, but a lot of them seem dependent on creating the button in the html template to be a form, which I'm not sure I could do in the .js file that generates the buttons. ' Surely, there … -
How to implement Group Permissions in an existing Django project?
For starters, I'm new to Django and am trying to implement Group-based permissions on an existing Django project using Django REST Framework. Looking for some direction on how to get started. I have a list of groups that should be created, as well as the various permissions that need to be associated with those groups. My assumption is that I will need to: Programmatically create the groups Programmatically create custom permissions and assign them to groups Use a decorator to authorize access to models/objects/methods based on groups Again, I'm just not sure where to start with the above steps. Some key questions I have that I haven't been able to find any good documentation/examples on are: What file(s)/directory(s) should this code reside in, according to Django best practices? (e.g. is there a convention on how groups and permissions should be organized in the code?) Should groups and permissions be created as a part of migrations? Hopefully this isn't an entirely stupid question. Any guidance, or even just a link to helpful resources would be greatly appreciated. Thank you! -
Django - Test circular models reference
I have two models Actor and User. Where Actor is a super set of User. The issue is that I have added two relationships into the Actor models to User one aiming to ContentType in which the choice is user and entity_id that aims straight to the User model. Therefore, I am not being able to assign one to another in test since each needs each other to be created. Before entity_id was only a PositiveField() and I could make the test pass. However, since I was asked to add a ForeignKey to entity_id I am having this issue of circular reference. models.py from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models # for testing Actor and ContentType: class Actor(models.Model): """ Actor: the superset for User and Applicant """ choices = models.Q(app_label='coretest', model='user') content_type = models.ForeignKey(ContentType, limit_choices_to=choices, related_name='entity_types', on_delete=models.CASCADE, null=True) entity_id = models.OneToOneField('User', on_delete=models.CASCADE, null=True) content_object = GenericForeignKey('content_type', 'entity_id') company_id = models.IntegerField() created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.content_type) class User(models.Model): actor_id = models.ForeignKey(Actor, on_delete=models.CASCADE) # having issues to relate two models created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.actor_id) test_models.py from django.utils import timezone from django.test import TestCase from coretest.models import … -
How to add an item from a product list in Django?
I would like to send an order. When creating my order, I can add a line to it. This works well. What I am trying to do now is to add a line from an existing product list. How can I modify my views to automatically browse the product list with a filter for the item field (in order to not show the 7000 products...) Many Thanks, Product list models.py class BaseProduct(models.Model): """ Abstract base product model class providing the base fields and methods """ supplier = models.CharField(max_length=300, blank=True, null=True) manufacturer = models.CharField(max_length=300, blank=True, null=True) product_range = models.CharField(max_length=300, blank=True, null=True) part_number = models.CharField(_('Item Code'), max_length=255, blank=True, null=True) description = models.CharField(_('description'), max_length=255, blank=True, null=True) Orders views.py class OrderCreate(CreateView): model = Order template_name = 'accounting/orders/create_order.html' form_class = OrderForm success_url = None def get_context_data(self, **kwargs): data = super(OrderCreate, self).get_context_data(**kwargs) if self.request.POST: data['lines'] = OrderLineFormSet(self.request.POST) else: data['lines'] = OrderLineFormSet() return data def form_valid(self, form): context = self.get_context_data() lines = context['lines'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if lines.is_valid(): lines.instance = self.object lines.save() return super(OrderCreate, self).form_valid(form) def get_success_url(self): return reverse('accounting:detail_order', kwargs={'order_id': self.object.pk}) @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(OrderCreate, self).dispatch(*args, **kwargs) forms.py class OrderLineForm(forms.ModelForm): class Meta: model = OrderLine exclude = () OrderLineFormSet … -
How to select the fields that i want to show in DRF using a foreign key
I'm working on a small project using Django / Rest Framework, i have two models ( CustomUser and Team ) from django.db import models from users.models import CustomUser class Team(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) This is my serializer : from rest_framework import serializers from apps.teams.models import Team class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = '__all__' # how can i show the CustomUser model fields depth = 1 the result is : [ { "id": 3, "user": { "id": 8, "password": "", "last_login": null, "is_superuser": false, "is_staff": false, "is_active": true, "date_joined": "2021-05-04T21:23:46.513567Z", "first_name": "John", "last_name": "Doe", "username": "testingxe", "email": "ab@test.com", "groups": [], "user_permissions": [] } } ] how can i choose the user, fields that i want to show / i can't show all of them because i have the password ... -
ValueError: Field 'id' expected a number but got 'BlablaRequest'
I am using Django. I am trying to introduce a data in this table: migrations.CreateModel( name='Request', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.CharField(max_length=200)), ('PartToaddToBaseUrl', models.CharField(max_length=200)), ('funcToExtractDataFromJsonName', models.CharField(max_length=100)), ('ParamsOrDataDictStructure', models.JSONField()), ('typeRequests', models.CharField(choices=[('GET', 'Get'), ('POST', 'Post')], max_length=5)), ('headers', models.JSONField(blank=True)), ('RApi', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='requests', to='app.restapi')), ], ), The data is: blablaCarRESTApi=RESTApi(name='BlablaCarRESTApi',BaseUrl='https://public-api.blablacar.com',APIKey='apiKey') I obtain this error: ValueError: Field 'id' expected a number but got 'BlablaRequest'. I don`t know why, I have tried to delete migrations and bd and make migrations and migrate(python manage.py makemigrations -> python manage.py migrate) -
I want to use ForeignKey Serializer
I have these Models Below class Campaign(models.Model): title = models.CharField(max_length=120) img = models.ImageField(upload_to='products/') def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=100) data = models.DateField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to="products/") campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING, null=True, blank=True, related_name="products") offer = models.ForeignKey(Offer, on_delete=models.DO_NOTHING, null=True, blank=True) market_price = models.PositiveIntegerField() selling_price = models.PositiveIntegerField() description = models.TextField() def __str__(self): return self.title I want to show campaign_wise products. But i cant find any solution for this. Though i tried reading the docs of DRF Here is my Serializer class CampaignProductsSerializer(serializers.ModelSerializer): products = serializers.PrimaryKeyRelatedField(read_only=True, many=True) class Meta: model = Campaign fields = ['title', 'products'] Whenever i try to run this i get 'Product' object has no attribute 'products' Here is my URL path('campaign_products/<int:id>/', CampaignProducts.as_view()), Here is my View: class CampaignProducts(APIView): def get(self, request, id): campaigns = Campaign.objects.all() query = Product.objects.filter(campaign_id = id) serializer = CampaignProductsSerializer(query, many=True) return Response(serializer.data) -
Django model method to get recursive children in M2M table inheritance
I am using table inheritance in Django and the base ModelA has a ManyToMany recursive field to itself called children. Then I have a ModelB that inherits from ModelA. The issue here is that when I query the children of an instance in ModelB, they are pointed to their equivalents in ModelA. What I would like to accomplish is that an instance of ModelB would return a queryset of children also of ModelB. I can do this using a method _children so it doesn't collide with the field name and have it return the correct model instances. Is there any way that I could instead have modelB.children.all() return the children with the correct model? I know I could use _children() but I would like to call it as an attribute and not a method(). The reason for all of this is that the table inheritance was added later in the game and all the instances will be migrated to these new models soon. Plus, children is broadly used in my project so it would be a hassle to change it all to _children. class ModelA(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) children = models.ManyToManyField( 'self', related_name='parents', symmetrical=False ) def _children(self): return … -
Writing if else statements in Django's Admin.py
I would like to have my Django admin collapse certain information if the user is new and cannot seem to figure out how to write an if else statement within the admin.py. Here's a general example models.py class User(models.Model): name = models.CharField() is_new = models.BooleanField(default=True) class NewUserInfo(models.Model): join_date = models.CharField() ''' admin.py ''' class NewUserInfoInline(admin.StackedInline): model = NewUserInfo # Here is where I'd like the if else statement I believe # Something like this **if user.is_new is False: classes = ['collapse']** class UserAdmin(admin.ModelAdmin): inlines = [NewUserInfoInline] -
Saving instances of model to ManyToMany field thows AttributeError 'Post' object has no attribute 'save_m2m' but when db is checked, has saved
My Django 3.1.7 blog app has a Post model with a tags field, which is a ManyToManyField to the PostTag model. I want my users to be able to select from some popular tags, or add their own in the new_tags field I created in models.py. new_tags does not exist in the Post model. My idea was to grab the string of "new" tags, split it at the spaces, then check if the tag already existed - creating it if it does exist. That bit of code is working, as new tags are being added to the database. My issue comes when I try to attach these new tags to the instance of Post being updated with the form. I have read loads of SO posts, and have arrived at the view code below. This does save the new tags to the Post instance in the database. However, on submitting the form it still throws an AttributeError: 'Post' object has no attribute 'save_m2m' However if I remove the post.save_m2m() line, the instances are created, but are not attached to my Post instance. views.py class EditPostView(LoginRequiredMixin, UpdateView): """ Renders view to edit an existing post """ model = Post template_name = … -
Overwrite Django "Using" method
I want to use PostgreSQL multi schema in Django. I want to overwrite using method to make my query according schema name. I want like this: objs=MyModel.objects.using('schema_name') objs.filter(...) # extra codes -
Django filter model by method result
I'm looking to filter a model (InventoryItem) by a custom defined method (current_location) that is the filtered queryset of another model (InventoryMovement). I've tried reading the Django documentation, but can't make out exactly how they are using model managers to achieve something like this. One example of what I'm trying to achieve would be something like: InventoryItem.objects.filter(current_warehouse='A') Code is: class InventoryAddress: def __init__(self, warehouse, location, sublocation): self.warehouse = warehouse self.location = location self.sublocation = sublocation class InventoryItem(models.Model): inventory_sku = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Inventory SKU") authenticated = models.CharField(max_length=2, choices=yes_no_choices, verbose_name='Authentication Status') # GenericForeignKey for Specific Product content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True) object_id = models.CharField(max_length=50) content_object = GenericForeignKey('content_type', 'object_id') def movements(self): movements = InventoryMovement.objects.filter(inventory_item=self) return sorted(movements, key=lambda x: x.datetime_entered, reverse=True) def completed_movements(self): movements = InventoryMovement.objects.filter(inventory_item=self, datetime_completed__isnull=False) return sorted(movements, key=lambda x: x.datetime_completed, reverse=True) def current_location(self): movements = self.completed_movements() if movements: last_movement = movements[0] loc = InventoryAddress( warehouse=last_movement.warehouse, location=last_movement.location, sublocation=last_movement.sublocation ) else: loc = InventoryAddress( warehouse='EXT', location=None, sublocation=None, ) return loc def current_warehouse(self): return self.current_location().warehouse class InventoryMovement(models.Model): movement_id = models.CharField(max_length=20, unique=True, blank=False, null=False, verbose_name='Movement ID') warehouse = models.CharField(max_length=40, null=False, blank=False, choices=warehouse_location_choices, verbose_name='Warehouse') location = models.CharField(max_length=40, null=False, blank=False, verbose_name='Target Bin') sublocation = models.CharField(max_length=40, null=False, blank=False, verbose_name='Target Position') inventory_item = models.ForeignKey(InventoryItem, null=True, on_delete=models.PROTECT, verbose_name="Inventory … -
Django parse JSON structure into Q filters
I have an input JSON structure that defines a set of logic that should be applied to a queryset. The json structure looks like this: filters = { "and": { "field__ismissing": "some_text", "other_field__gt": 100, }, "or": { "field__ismissing": "some_text", "other_field__gt": 100, } } which should parse into the following filter. (Q(field__ismissing='some_text') & Q(other_field__gt=100)) | (Q(field__ismissing='some_text') & Q(other_field__gt=100)) Is it possible to parse the JSON as such? The end goal would be to do something like Model.objects.filter(**filter_function(a, b, c))