Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Let users create their own database datable with Python Django
So, As the title describe I would like to have an authenticated user be able to create tables in the database (for instance, by filling a text field in a form and clicking a button). Basically, my idea is to create a to-do-list manager where, a user can create its own to-do list, or more, (tables in the database) and add things to it (row inside the table). I can't understand how to attach more tables to a single authenticated user. Because the structure of the table must be fixed, the idea was to create the model of this table in models.py inside my app, and use the Django signal listening to the POST action on the button to create a new object (so a new table) from the class defined on models.py. The "fixed table" should be: class base_table(models.Model): link = models.CharField(max_length=30) def __str__(self): return self.link Now my doubt is how do I link every table to a specific user? Is it possible to check the name of the table, let's say something like user1_1, user1_2 user1_3 or is there a cleaver way I'm missing in Django to do that? -
Django: If objects queryset is empty write zero instead. I solve this with numpy but I want a direct solution in the queryset
I think there should be an easier and more elegant solution but I cannot find it. I have the following in views.py. As you can see I achieve want I want with numpy but I want a direct solution: myarray = np.asarray(MyDatabase.objects.filter( status='user').values_list('name','age').order_by('age')) if myarray.size==0: myarray=np.zeros((1,2)) What I want is to set zeros when the object queryset is empty. I just dislike using the extra lines. I wonder if there is a way to directly ouput zeros when the objects filter is empty. In the documentation it says that django 4.0 comes with default() option in the queryset to do precisely what I'm asking but no example is given. I would appreciate it if you share your solution Thanks -
How to update graphene-django to latest version
I am facing difficulties to update the graphene-django to the latest version. while I am trying pip install "graphene-django>=3", it shows the error given below: ERROR: Could not find a version that satisfies the requirement graphene-django>=3 (from versions: 1.0.dev20160909000001, 1.0.dev20160910000001, 1.0.dev20160917000001, 1.0.dev20160919000001, 1.0.dev20160919000002, 1.0.dev20160919000003, 1.0.dev20160919000004, 1.0.dev20160920000001, 1.0.dev20160922000001, 1.0, 1.1.0, 1.2.0, 1.2.1, 1.3, 2.0.dev2017072501, 2.0.dev2017072601, 2.0.dev2017073101, 2.0.dev2017083101, 2.0.0, 2.1rc0, 2.1rc1, 2.1.0, 2.2.0, 2.3.0, 2.3.2, 2.4.0, 2.5.0, 2.6.0, 2.7.0, 2.7.1, 2.8.0, 2.8.1, 2.8.2, 2.9.0, 2.9.1, 2.10.0, 2.10.1, 2.11.0, 2.11.1, 2.12.0, 2.12.1, 2.13.0, 2.14.0, 2.15.0, 3.0.0b1, 3.0.0b2, 3.0.0b3, 3.0.0b4, 3.0.0b5, 3.0.0b6, 3.0.0b7) ERROR: No matching distribution found for graphene-django>=3 Does anybody have a solution? -
bootstrap JavaScript not working as in when the screen size is decreased the menu bar wont work
so I'm working with Django for the first time and I am following a tutorial, bootstrap is used for the navbar so I added the CSS from bootstrap it worked but the JavaScript from bootstrap is not working, I know that because when the screen size is reduced, a menu bar appears instead of the navbar items but it doesn't work when clicked. How can I fix this? <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CRMain</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> {% include "accounts/navbar.html"%} {% block content %} {% endblock %} <hr> <h5>footer</h5> </body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </html> 2 screenshots of the before and after:- https://i.stack.imgur.com/7I5he.png https://i.stack.imgur.com/JteLC.png -
Encode ImageField in base64 and store it in DB instead of path of the image
settings.py STATIC_URL = '/static/' STATICFILES_DIRS= [str(BASE_DIR.joinpath('static'))] STATIC_ROOT = BASE_DIR.joinpath('staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = str(BASE_DIR.joinpath('media')) config/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('proj.urls')), ] += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Book(models.Model): image = models.ImageField(upload_to='upload/', blank=True, default=None, null=True) views.py class BookCreateView(CreateView): model = Book template_name = "book_new.html" fields = "__all__" book_new.html {% extends 'base.html' %} {% block content %} <h1>New Book</h1> <form action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock content %} proj/urls.py urlpatterns = [ path("", home_view, name="home"), path("book/new/", BookCreateView.as_view(), name="book_new"), ] I have written this code which will upload the image to /media/upload/ and the path of the file will be saved on the database like upload/image_file.png. I don't want to store the file path in the database, I want to read the file, convert it to base64 and store the encoded string in the database. How can I do that? I've searched a lot and tried to figure this out on my own as I usually do, but this one's a little hard for me, here's what I've read so far: Binary image display in Django template Save base64 image in django file field Saving a decoded temporary image to Django Imagefield a … -
django-admin startproject gives SyntaxError
I tried to start a new project with Django 4.0. After installing Django in environment folder (Anaconda/envs/taskman/) I created a new folder somewhere in my E: drive and by using Windows command line created a new folder Django_site/. Then from this folder I typed in command line prompt: django-admin startproject lifetool and got the following: (taskman) E:\Projects\Django_site>django-admin startproject lifetool Traceback (most recent call last): File "E:\Programs\Anaconda\envs\taskman\Scripts\django-admin-script.py", line 5, in <module> from django.core.management import execute_from_command_line File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\core\management\__init__.py", line 16, in <module> from django.core.management.base import ( File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\core\management\base.py", line 13, in <module> from django.core import checks File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\core\checks\__init__.py", line 18, in <module> import django.core.checks.translation # NOQA isort:skip File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\core\checks\translation.py", line 3, in <module> from django.utils.translation.trans_real import language_code_re File "E:\Programs\Anaconda\envs\taskman\lib\site-packages\django\utils\translation\trans_real.py", line 485 while (i := lang_code.rfind('-', 0, i)) > -1: ^ SyntaxError: invalid syntax What is wrong? Do I need to correct invalid syntax in installed Django package? Help me to clarify the issue -
How to pass a query parameter to SerializerMethodField in django rest framework?
I want to filter out some instance based on the query parameter I get in the GET call. class RevisionSerializer(serializers.ModelSerializer): slot_info = serializers.SerializerMethodField(required=False, read_only=True) batch_config = serializers.SerializerMethodField(required=False, read_only=True) class Meta: model = Revision fields = ['id', 'status', 'revision_id', 'instructor', 'number_of_classes', 'start_date', 'slot', 'slot_info', 'tinyurl', 'zoom_link', 'batch_config'] read_only_fields = ['revision_id'] def get_batch_config(self, obj): # filter this on the incoming data from the GET call related_batches = CompensationClass.objects.select_related('style', 'instructor').filter( compensation_class_id=obj.revision_id) batch_config_values = related_batches.values('batch_id', 'age_group', 'level', 'course_version', 'style__name', 'class_number') return batch_config_values This is my serializer and I will be passing one date and based on that date I want to filter my serializermethodfield. How can I achieve this? -
Using AJAX to test for readiness of data through polling
I have a Django application and am attempting to utilize Ajax and Redis to poll for the completion of a long calculation. The difficulty I am having is that my Ajax is "recalling itself" after the timeout period. My intended action is for Ajax to test for the completion of a process (indicated by a Redis channel). The difficulty I am having is that the Ajax is called once upon page load, again upon page click (which is intended), but does not "re-poll" at the regular 3 second intervals to test my retrieval view for my result. Here is the view.py: @login_required() def retrieveAsync(request): if is_ajax(request=request) and request.method == "GET": show_df = request.session['win_deep_show_df'] df = [] msg = ['you have called retrieveAsync'] if show_df == False: ret_val = { 'do_what': 'nothing', 'msg': msg, 'df': df, } # user has not requested the dataframe info yet...do nothing return JsonResponse(ret_val, status=200) elif show_df == True: redisChannel = request.session['win_deep_redis_channel'] data_ready = (REDIS_INSTANCE.get(redisChannel + 'reco_data_ready').decode('utf-8') == 'yes') if data_ready is False: msg = "Loading data..." ret_val = { 'do_what': 'wait', 'msg': msg, 'df': df, } return JsonResponse(ret_val, status=200) elif data_ready is True: ret_dict = pickle.loads(REDIS_INSTANCE.get(redisChannel + 'ret_dict')) msg = "Your data is ready now..." … -
Need to get specific field value from one model to another
model 1 class Users(models.Model): JOINING_ROLES_CHOICES= ( ('sde-intern','SDE Intern'), ('sde-trainee','SDE Trainee'), ('sde_1','SDE I'), ('ui/ux','UI/UX Designer'), ('quality-engineer-trainee','Quality Engineer Trainee'), ('quality-engineer','Quality Engineer'), ('product-manager','Product Manager'), ('technical-manager','Technical Manager'), ('technical-architect','Technical Architect'), ('technical-lead','Technical Lead') ) BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=100,default=None) aadhar=models.CharField(max_length=100,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) joining_role=models.CharField(max_length=250,choices=JOINING_ROLES_CHOICES,null=True) billable_and_non_billable=models.CharField(max_length=250,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') def__str__(self): return self.employee_name model 2 class Consolidated(models.Model): emp_name=models.OneToOneField(Users, on_delete=CASCADE, null=True,related_name="user") proj_name=models.OneToOneField(Project,on_delete=CASCADE, null=True) custom_name=models.OneToOneField(Client,on_delete=CASCADE, null=True) Cons_date=models.OneToOneField(Add_Timelog,on_delete=CASCADE, null=True) bill_no_bill=models.ManyToManyField(Users,related_name="bill") hours_spent = models.OneToOneField(Add_Timelog,on_delete=CASCADE, null=True,related_name="hours") def __str__(self): return str(self.emp_name) I need to get the employee_name and billable_and_non_billable values from the Users model to Consolidated model fields(emp_name and bill_no_bill). I tried using the above code but it is returning the employee name value to the bill_no_bill field also. Kindly help me to get the value from billable_and_non_billable field for bill_no_bill field. -
Replace chars in substring of a string
I'm working on a blog with Django, however my question is Python related not really Django related. To write my blog posts I use Quill which generate the post in HTML. I save this HTML in the database than display the post using the filter |safe. Until now everything worked well until ... I want to display HTML code as examples which is obviously considered as safe because of the filter and is interpreted by the browser. As a workaround I try to create a function able to escape HTML code as soon as they are between the tags but not escape the HTML out of this tag. For example if quill return this: <p> This is the code you need: <pre class="myclass"> <div> The code </div> </pre> </p> I would like to save in database something like this: <p> This is the code you need: <pre class="myclass"> &lt;div&gt; The code &lt;/div&gt; </pre> </p> That way the safe tag will make the HTML code interpreted and display the HTML code inside the tag. My problem is I don't find a way to make a replacement for each character only between the tags and keep everything as it is. Basically I … -
Django api backend filter table
The goal is to get the photos associated with a listing id. I have the bellow structure in django rest framework Model.py class Pictures(models.Model): index = models.BigIntegerField(blank=True, null=True) listing_id = models.ForeignKey( Listings, models.DO_NOTHING, blank=True, null=True) post_title = models.TextField(blank=True, null=True) guid = models.TextField(blank=True, null=True) post_mime_type = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'pictures' Serializer.py class PicturesSerializer(serializers.ModelSerializer): class Meta: model = Pictures fields = ('index', 'listing_id', 'guid') Views.py class PicturesListViewAlt(generics.ListAPIView): serializer_class = PicturesSerializer def get_queryset(self): if self.request is None: return Pictures.objects.none() id_of_listing = self.kwargs['listing_id'] return Pictures.objects.filter(listing_id=id_of_listing) urls.py app_name = 'pics' urlpatterns = [ re_path('^pictures/(?P<listing_id>.+)/$', views.PicturesListViewAlt.as_view()), ] I keep getting the bellow errors. django.db.utils.ProgrammingError: column pictures.listing_id_id does not exist LINE 1: ...ELECT COUNT(*) AS "__count" FROM "pictures" WHERE "pictures"... ^ HINT: Perhaps you meant to reference the column "pictures.listing_id". [03/Feb/2022 11:58:17] "GET /api/pictures/123/ HTTP/1.1" 500 24360 Although I have never initiated a column listing_id_id And ProgrammingError at /api/pictures/123/ column pictures.listing_id_id does not exist LINE 1: ...ELECT COUNT(*) AS "__count" FROM "pictures" WHERE "pictures"... ^ HINT: Perhaps you meant to reference the column "pictures.listing_id". Which when I change my filter to pictures__listing_id I get django.core.exceptions.FieldError: Cannot resolve keyword 'pictures' into field. Choices are: guid, id, index, listing_id, listing_id_id, post_mime_type, post_title [03/Feb/2022 … -
Join two related fields tables of a model using Django's ORM
I have the following models in my Django app where I have common user subscription info as an abstract class that contains a foreign key to my user, and my other free and paid user subscription models that inherit the abstract class and implement the desired behavior: class CommonUserSubscriptionInfo(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="%(class)s") is_active = models.BooleanField(default=True, editable=False) number_of_requests = models.IntegerField(default=0, editable=False) hectares_consumed = models.FloatField(default=0, editable=False) class Meta: abstract = True class FreeUserSubscription(CommonUserSubscriptionInfo): max_free_hectares_allowed = models.FloatField(default=50) max_number_of_requests_allowed = models.FloatField(default=50) class PaidUserSubscription(CommonUserSubscriptionInfo): plan = models.ForeignKey(PaidSubscriptionPackages, on_delete=models.PROTECT, related_name="users_subscriptions") In my user model, in the case where my user has no active subscriptions, how can I join the tables of both related fields to query all the inactive free and paid subscriptions, order them by date and return the newest inactive subscription? something like: class User(AbstractBaseUser, PermissionsMixin): # code def get_last_active_subscription(self): return self.joined_subscriptions?.filter(is_active=False).order_by('-start_subscription_date')[0] I know I can use the related_name to access each table's related rows, and then I can merge both querysets as mentioned in this question, but I was wondering if there's a better or maybe more efficient way to achieve that using Django's ORM -
psycopg2 cant connect to postgres DB psycopg2.OperationalError
my db setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', 'HOST': '127.0.0.1', 'USER': 'postgres', 'PORT': '5432', 'PASSWORD': '1234' } } i try python manage.py migrate but have this error -
function or method for repeated event in python / django
models: from django.db import models class datecrt(models.Model): name=models.CharField(max_length=255) stdate=models.DateField() sttime=models.TimeField() endate=models.DateField() forms: import datetime from xml.dom.minidom import Attr from django import forms from .models import datecrt class dateform(forms.ModelForm): class Meta: model=datecrt fields='__all__' widgets={ 'stdate':forms.DateInput( attrs={'type':'date','class':'form-control'}, format='%D-%m-%yy', ), 'sttime':forms.TimeInput( attrs={'type':'time','class':'form-control'}, format='%H:%M', ), 'endate':forms.DateInput( attrs={'type':'date','class':'form-control'}, format='%D-%m-%yy', ) } def __init__(self,*args,**kwargs): super(dateform,self).__init__(*args,**kwargs) self.fields['stdate'].imput_format=('%D-%m-%yy',) self.fields['sttime'].imput_format=('%H:%M',) self.fields['endate'].imput_format=('%D-%m-%yy',) Views: from unicodedata import name from django.shortcuts import redirect, render from .forms import dateform from .models import datecrt def datecr(request): if request.method=='GET': form=dateform() return render(request, 'date.html', {'form':form}) else: form=dateform(request.POST) if form.is_valid(): form.save() return redirect('/dateview') def dateview(request): context={'dateview':datecrt.objects.all()} return render(request, 'dateview.html',context) When I create this booking on 1st of feb and end date will select as 5th of feb, my challenge is, created booking should display name, date, and time till 5th of feb automatically in dateview template, without me creating same for 2nd of feb, 3rd of feb till 5th of feb manually. -
Modify unique_together contraint on through model
I have a Rate model defined as follow: class Rate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'reviewer': True}) project = models.ForeignKey(Project, on_delete=models.CASCADE) rate = models.IntegerField( default=100, validators=[ MinValueValidator(0), MaxValueValidator(100) ] ) level = models.IntegerField(default=1) objects = RateManager() class Meta: db_table = 'api_project_reviewers' unique_together = ('user', 'project', 'level') It is an intermediate model between my User and my Project model. It's created like this on my project model: reviewers = models.ManyToManyField(User, related_name="review_project", through='Rate') I added the unique_together constraint on the model because I want to be able to have 2 entries as: Entry 1: User 1, Project 1, rate 100, level 1 Entry 2: User 1, Project 1, rate 100, level 2 Basically I want to be able to associate one user to the same project multiple time, changing the level. But when I do it I receive: IntegrityError at /admin/api/user/6/change/ duplicate key value violates unique constraint "api_project_reviewers_project_id_user_id_cd9f7f42_uniq" DETAIL: Key (project_id, user_id)=(1, 6) already exists. which is totally right byt shouldn't raise an error. How can I remove the unique_together constraint on user and project ? Thanks -
Django dynamic form returning only the last data using formset
in this view, I am getting only the last data that a user has filled. Let's suppose a user has entered 3 times Stop name but on the server-side, I am getting only the last which is the 3rd. 1st and 2nd are vanishing This is my template for the form <form method="POST" class="add-new-form" enctype="multipart/form-data"> {{ f_formset.management_form }} {{ ingredient }} <div id="div_testing"> <div class="testing2"> {{ form }} </div> </div> <button type="button" id="add-more-forms" onclick="duplicateForm()"> More Fields </button> This is my add new form function of javascript const xyx = document.getElementById("div_testing"); function duplicateForm() { let forms = xyx.getElementsByClassName("testing2"); let firstForm = forms[0]; let formClone = firstForm.cloneNode(true); xyx.appendChild(formClone); } And this is my Django view def supply_chain(request, id=0): items = SupplyChainStops.objects.all() formset_class = StopsFormSet ingredient_form = SupplyChainIngredientForm(request.POST or None) if request.method == 'POST': form = formset_class(request.POST) if form.is_valid() and ingredient_form.is_valid(): for frm in form: stop_name = frm.cleaned_data.get('stop_name') stop_longitude = frm.cleaned_data['stop_longitude'] stop_latitude = frm.cleaned_data['stop_latitude'] supply_chain_obj = SupplyChainStops(stop_name=stop_name, stop_longitude=stop_longitude, stop_latitude=stop_latitude) supply_chain_obj.save() return redirect('supply-chain') else: form = formset_class() context = { 'form': form, "ingredient": ingredient_form, # "items":items } return render(request, 'ingredients/supply_chain.html', context) This is the image of this HTML, when I will click on the add more button it will add 3 more fields which … -
Creating Custom Django model Function similar to Avg, Sum ,min ,max etc which are imported from django.db.models
I'm trying to create a function similar to the min, max avg, etc offered by django.db.models in Django. I'm stuck and couldn't find any lead and also I don't want to write a function and then perform operation on it, rather I want to perform the operation directly on DB and use a formula to return the value. For example If I want to find the change in a particular field in a given interval. I can do something as below. filtered_obj= modelA.objects.filter(create__range=[start_date,end_date]).values_list('value',flat=True) result= filtered_obj[-1]-filtered_obj[0] But rather then doing this i want to create a function similar to the Avg,min and max. So any help or any guidance or any reference will be a great help -
Is django's .get() faster than .filter()?
Which of the two is faster with big number of objects in a django model???? item1 = Item.objects.get(id=4) item2 = Item.objects.filter(school = request.user.school,id=4) -
Django multipart/form-data pass Dict & File
I want to create a post requests that sends a file along with information in the form of a dictionary. I have the following implementation: # conftest.py import pytest @pytest.fixture def api_client(): from rest_framework.test import APIClient return APIClient() Testing with pytest: # test_dataset.py @pytest.mark.django_db() class TestDatasetEndpoint: def test_dataset_create(self, api_client): data_raw = baker.make(Dataset) serialized_dataset = DatasetSerializer(data_raw).data print(serialized_dataset) file_path = "./Top 250s in IMDB.csv" with open(file_path, "rb") as fp: encoded_data = encode_multipart( BOUNDARY, {"data": serialized_dataset, "file": fp} ) response_post = api_client.post( reverse("datasets-list"), encoded_data, content_type="multipart/form-data; boundary=BOUNDARY", ) assert response_post.status_code == 201 Server side: # views.py class DatasetViewSet(viewsets.ModelViewSet): queryset = Dataset.objects.all() serializer_class = DatasetSerializer def create(self, request, *args, **kwargs) -> Response: data = request.data return Response(request.data["data"], status=status.HTTP_201_CREATED) The response i am getting is a combination of the dict and the file data. How can i handle the data and the file in the server side (views.py)? -
Should django migrations be applied automatically when using docker?
I'm dockerizing a Django app and I saw that some people run the migrations in the docker-compose.yml file but some people don't, what is the best solution? Thanks!! -
malloc_consolidate(): invalid chunk size
This is a strange error I'm having on a server: root@charles:oauthtutorial# /opt/oauthtutorial/venv/bin/python manage.py Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages [...removing more output...] test testserver [sessions] clearsessions malloc_consolidate(): invalid chunk size Aborted If INSTALLED_APPS contains only django.contrib.admin, django.contrib.contenttypes, django.contrib.messages and django.contrib.staticfiles (and my app, which it is a completely empty app created by django-admin), the error doesn't occur. If INSTALLED_APPS contains django.contrib.sessions or django.contrib.auth, then the error occurs. Environment: Debian 11.2 Linux 5.10.0-11-amd64 #1 SMP Debian 5.10.92-1 (2022-01-18) x86_64 GNU/Linux (Debian-packaged) Python 3.9.2 (default, Feb 28 2021, 17:03:44) [GCC 10.2.1 20210110] on linux Django 3.2.12 -
How to save a nested object in a post request correctly?
I am trying to work with a post request were I am first saving a Tag object, which then becomes the tag field of a Tagging object. However, no matter what combinations I have tried, despite the Tag Post method working, when I pass a json object like this: { "user_id": 1, "gameround_id": 2015594866, "resource_id": 2975, "tag": { "name": "TESTTAGGGG2222", "language": "en" }, "score": 0, "origin": "" } I keep getting this message: { "name": [ "This field is required." ], "language": [ "This field is required." ] } However, when I pass a Tag, it works. This is the relevant part from the post method: if tag_serializer.is_valid(raise_exception=True): tag_serializer.save(tag=request.data) if tagging_serializer.is_valid(raise_exception=True): tagging_serializer.save(tagging=request.data, tag=tag_serializer.data) return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED) # else: # return Response({"status": "success", "data": tag_serializer.data},status=status.HTTP_201_CREATED) else: return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST) How do I correctly pass the nested object in the post method so that I don't get this error anymore? -
Django rename field and create new one with the same name returns psycopg2 error: DuplicateTable: relation already exists
I have a Django (foreign key) field which I renamed in one migration (automatic detection). Then I realised I actually need one with that name but a different one. Locally I develop on an SQLite DB and this works fine. When I pushed it to our Postgres DB, this returned an error. Migration one operations = [ migrations.RenameField( model_name='modelname', old_name='oldfieldname', new_name='newfieldname', ),] Migration two operations = [ migrations.AddField( model_name='modelname', name='oldfieldname', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='OldFieldName', to='app.othermodel'), ),] When I run this migration I get the following error Applying app.xxx1_previous... OK Applying delight.xxx2_rename_field... OK Applying delight.xxx3_add_field...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DuplicateTable: relation "app_modelname_oldfieldname_id_8c448c6a" already exists Normally this should have been deleted. I found this issue describing a similar issue in Postgress and now I wonder if this is a bug in Django. Could it be that the cleanup from the rename is not done correctly? -
how to override list permission with django-rules
I installed django-rules to my project to define rules for my actions. The list function hast no permission setting per default so you have to add them to the permission_type_map as written here but without an effect. For the other actions i am able to change the behavior if i set it to is_superuser or something else. from django.db import models import rules from rules.contrib.models import RulesModel from rules.contrib.rest_framework import AutoPermissionViewSetMixin from base.models import BaseModel class Company(RulesModel, BaseModel): name = models.CharField(max_length=100) active = models.BooleanField(default=True) permission_type_map = { **AutoPermissionViewSetMixin.permission_type_map, "list": "all", } class Meta: rules_permissions = { # TODO: rules need to be defined "add": rules.always_allow, "view": rules.always_allow, "delete": rules.always_allow, "change": rules.always_allow, "all": rules.is_superuser } What do i miss here? -
django urls error when I import a non-itinerant object
I can't understand why it gives me an error when importing my views. I don't understand where the mistake is. I deleted some apps from the project and views, will it be for that? views from django.shortcuts import render from django.views.generic import ListView from .views import Schede class SchedeListView(ListView): model = Schede template_name = 'test.html' context_object_name = 'schede' devtest urls from django.urls import path from django.views.generic import TemplateView from .views import views urlpatterns = [ path('', TemplateView.as_view(template_name="dash.html"), name="home"), path('test_schede/', views.SchedeListView.as_view(), name="test_schede"), ] url general from django.contrib import admin from django.urls import path, include #sitemap from django.contrib.sitemaps.views import sitemap from .sitemaps import StaticViewSitemap #pdf from pdf.views import testPdfView sitemaps = {'static': StaticViewSitemap} urlpatterns = [ path('admin/', admin.site.urls), path('test/<id>/', testPdfView, name="test_pdf"), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), path('', include('devtest.urls')) ] error C:\Users\dev\Downloads\laragon\www\scheda>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\dev\Downloads\laragon\bin\python\python-3.6.1\lib\site-packages \django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable