Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF nested serializer is not serializing data
I am trying to serialize nested models for an API view. class Dashboard(models.Model): created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(IamUser, on_delete=models.CASCADE, related_name='dashboards') title = models.CharField(max_length=100) type = models.CharField(max_length=100) position = models.IntegerField() config = models.CharField(max_length=5000, blank=True, null=True) class WidgetLayout(models.Model): created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(IamUser, on_delete=models.CASCADE, related_name='widgets') dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE, related_name='widgets') type = models.ForeignKey(Widget, on_delete=models.CASCADE) position = models.IntegerField() width = models.IntegerField() config = models.CharField(max_length=5000, blank=True, null=True) with the following serializers class WidgetLayoutSerializer(serializers.ModelSerializer): class Meta: model = WidgetLayout fields = ['id', 'type', 'position', 'width', 'config'] class DashboardSerializer(serializers.ModelSerializer): class Meta: widgets = WidgetLayoutSerializer(many=True) model = Dashboard fields = ['id', 'title', 'position', 'config', 'type', 'widgets'] The view calls the serilizers like this: dashboards = request.user.dashboards.all() serializer = DashboardSerializer(dashboards, many=True) The expected output would be a list of Widgets in their JSON serialization for each Dashboard, however, I get only a list of Widget-IDs. I discovered that, if i remove the widgets = WidgetLayoutSerializer(many=True), the result is the same, so I suspect, the serializer is not being used or referenced properly. I went through https://www.django-rest-framework.org/api-guide/relations/#example and tried to spot any difference, but could not find it. Adding the prefetch_related for the widgets to the .all() in the view made … -
How to fix cryptography module import error?
I was trying to encrypt one field of a model with some libraries: django-encrypted-model-fields django-mirage-field encrypt-decrypt-fields After that, the project started to giving errors even though I uninstall all of the libraries and remove all the codes. I have no idea why. How can I solve it? Traceback (most recent call last): ... self.encryptor = Cipher(algorithms.AES(self.key),modes.CTR(self.nonce)).encryptor() File "/Library/Python/3.9/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 86, in __init__ backend = _get_backend(backend) File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/__init__.py", line 23, in _get_backend return default_backend() File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/__init__.py", line 14, in default_backend from cryptography.hazmat.backends.openssl.backend import backend File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/openssl/__init__.py", line 6, in <module> from cryptography.hazmat.backends.openssl.backend import backend File "/Library/Python/3.9/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 113, in <module> from cryptography.hazmat.bindings.openssl import binding File "/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 14, in <module> from cryptography.hazmat.bindings._openssl import ffi, lib ImportError: dlopen(/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/_openssl.abi3.so, 0x0002): tried: '/Library/Python/3.9/site-packages/cryptography/hazmat/bindings/_openssl.abi3.so' (mach-o file, but is an incompatible architecture (have (arm64), need (x886_64))) -
Django - migrate command not using latest migrations file
I have 5 migration files created. But when I run ./manage.py migrate it always tries to apply the migrations file "3". Even though the latest one is file 5. How can I fix this issue? I have tried: ./manage.py makemigrations app_name ./manage.py migrate app_name ./manage.py migrate --run-syncdb Also, I checked the dbshell, and there is a table already created for the model which is part of migrations file 5. Any help would be great. -
VS Code - broken auto check of links for Django/Python
this is stupid question, but I used to have in Django/Python files in VS Code automatic check by yellow colour, that model, variable, view, function etc. are correctly somewhere defined and I can use them. But something broke and everything is now white. Does anybody know, where to switch on again this check for Python/Django? HTML and JavaScript files are working fine, but for Python files it was broken. Thanks a lot for any help. -
Get all the rows of a table along with matching rows of another table in django ORM using select_related
I have 2 models Model 1 class Model1(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) type = models.CharField(max_length=255) details = models.TextField(max_length=1000) price = models.FloatField() Model 2 class Model2(models.Model): id = models.IntegerField(primary_key=True) user_id = models.ForeignKey( User, on_delete=models.CASCADE ) plan_selected = models.ForeignKey(Model1) I am trying to check whether a user has selected any plans. The field plan_selected is a foreign key for Model1 - id. I want to get all details of Model1 along with details of Model2 in a single line of the query set using Django. So far I have tried to get is : sub_details = Model1.objects.select_related('Model2').filter(user_id=id) -
How to store tran_id and val_id in database using?
My motive is to implement the payment gateway in my e-Commerce website using sslcommerz-python by clicking the buy now button. The payment gateway is working well. Now I want to store tran_id and val_id in the PurchasedItem model so that the admin can understand which product a user ordered and whether the user payment is done or not. How can I do it? I tried different ways, but these didn't work😥. Give me a relevant solution😊... views.py: def MakePayment(request,pk): mypayment = SSLCSession(sslc_is_sandbox=True, sslc_store_id=store_id, sslc_store_pass=API_key) status_url = request.build_absolute_uri(reverse('PaymentStatus')) mypayment.set_urls(success_url=status_url, fail_url=status_url, cancel_url=status_url, ipn_url=status_url ) #product information orderItem = get_object_or_404(FoodMenu, pk=pk) mypayment.set_product_integration( total_amount=Decimal(order_total), currency='BDT', product_category='Mixed', product_name=orderItem, num_of_item=orderQTY, shipping_method='Courier', product_profile='None' ) #sender info mypayment.set_customer_info( name=request.user.first_name, email=request.user.email, address1=request.user.address, address2=request.user.address, city=request.user.district, postcode=request.user.zipcode, country='Bangladesh', phone = request.user.phone_number ) #billing info mypayment.set_shipping_info( shipping_to=request.user.first_name, address=request.user.address, city=request.user.district, postcode=request.user.zipcode, country='Bangladesh' ) response_data = mypayment.init_payment() if request.method == "POST": PurchasedItem.objects.create( user = request.user, item=orderItem, address=request.POST.get('address'), ) return redirect(response_data['GatewayPageURL']) NOTE: Security purpose I did not mention value of store_id and API_key @csrf_exempt def PaymentStatus(request): if request.method == 'POST' or request.method == 'post': payment_data = request.POST status = payment_data['status'] if status == 'VALID': tran_id = payment_data['tran_id'] val_id = payment_data['val_id'] messages.info(request,"Your payment successfully done.") return HttpResponseRedirect(reverse("PurchasedProduct", kwargs={'tran_id':tran_id, 'val_id':val_id})) return render(request, 'payment_status.html') def PurchasedProduct(request,tran_id,val_id): context = … -
ERROR.. Unhandled exception during build. When running pipeline
trying to run a pipeline, my set up : GitHub Elastic Beanstalk with autoscaling and load balancer S3 Bucket for persistent static-files After running the pipeline it fails to deploy all instances with the same version. So from my logs I've found out that it fails when running the container_commands. option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: project.settings "PYTHONPATH": "/opt/python/current/:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: project.wsgi:application NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:proxy:staticfiles": /html: statichtml /static-files: static-files /media: media-files **container_commands: 10_deploy_hook_permissions: command: | sudo find .platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; sudo find /var/app/staging/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \;** Which it execute this : #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/manage.py collectstatic --noinput python /var/app/current/manage.py migrate NOTE: The app deploys perfectly fine when I run "eb deploy", but when deployment is triggered from pipeline than it goes in to "Degraded" status where the instance is still running but apparently no all the instances are running the same version. Error from health: over all : - Command failed on all instances. - Incorrect application version found on all instances. Expected version "app-221124_115515680871" (deployment 418). instance : - Application deployment failed at 2022-11-24T11:32:55Z with exit status 1 and error: Engine execution has encountered … -
Serializers not working on multiple levels as expected in Django
I have 4 models and 3 serializers. 1 model is a simple through table containing information about which user posted which reaction about which article. models.py class User(AbstractUser): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) username = models.CharField(max_length=250, unique=True) ... class Article(models.Model): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) title = models.CharField(max_length=50) author = models.ForeignKey(User, related_name='authored', on_delete=models.PROTECT) ... class Reaction(models.Model): user_id = models.ForeignKey(User, related_name='reacted', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_details', on_delete=models.CASCADE) sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE) class Sentiment(models.Model): like = models.IntegerField(default=1) dislike = models.IntegerField(default=-1) serializers.py class UserSerializer(serializers.ModelSerializer): authored = ArticleDetailSerializer(many=True, read_only=True) reacted = ReactedSerializer(many=True, read_only=True) class Meta: fields = ( 'id', 'username', 'authored', 'reacted', ) model = User class ArticleDetailSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'title', ) model = Article class ReactedSerializer(serializers.ModelSerializer): article_details = ArticleDetailSerializer(many=True, read_only=True) class Meta: fields = ( 'sentiment', 'article_id', 'article_details', ) model = Reaction Currently, the output for a GET request for a User shows authored correctly. I copied the logic so reacted can be a multi-level object containing sentiment and the relevant article information. I've tried many solutions yet the result for the User field reacted never includes the article_details field. I've ensured the related_name field in in the Reacted model is article_details so what am I missing? I've … -
Django override save method with changing field value
I need some help with overriding save method with changing field value. I have such structure: models.py class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) to_categories = models.ManyToManyField(Category, blank=True, related_name='categories', ) def save(self, *args, **kwargs): super(Product, self).save(*args, **kwargs) So I can`t find a correct sollution for save method. I can select category on the "to_category" and categories on "to_categories" field, but I need if I selected one of the categories on the "to_category" field then save the Product, this selected field must be automatically selected on the "to_categories" field. Thanks for help. -
Correct escaping to use in Django templates to avoid Unterminated string literal errors in VS Code
Consider the following in a Django .html template <button onclick="location.href='{% url 'my-route' pk %}'"> # Warns because of this -------^.......^ VS Code will warn of an unterminated string literal as it doesn't understand that inside {% %} is processed first by the template engine. It works just fine, but the VS Code warnings (complete with red highlighting) are distracting. Any way to fix this either by escaping ' or " or changing some VS Code config? -
Dynamically define model attributes / database fields in Django
I would like to define a Django Model looking like this: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Foo(models.Model): object_id_1 = models.UUIDField() content_type_1 = models.ForeignKey(ContentType) object_id_2 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) object_id_3 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) # etc. d1 = GenericForeignKey("content_type_1", "object_id_1") d2 = GenericForeignKey("content_type_2", "object_id_2") d3 = GenericForeignKey("content_type_3", "object_id_3") # etc. Obviously, the more dimensions (d stands for "dimension") I add, the messier it gets: this isn't very DRY, all the more since I've removed the many fields options in this example. Is there a way to dynamically define these model attributes, for instance in a for loop, without using eval? If not, what would be the cleanest and safest way to resort to eval here? I've found a very similar Stackoverflow question here but it is more specific and it hasn't got any generic answer. -
Change DRF url query filter pattern
The default DRF url pattern for search is "?search=<...>", where you search by a field you add in view's search_fields. How can I change it to "?field_name=<...>" ? How can I change "?field_name__lte=" to "?field_name[lte]=" ? -
how can I display or return a instance of a django model by using another instance(which is primary key)
I have Wallet class. user and Walletname are the instance of this class. when a new user is registered, the Wallet class is created by signal. the thing that ı would like to do is that displyaing or returning the Walletname of the current logged user. thank you I tried filtering but ı got error which is related with id it says %s is expected integer value? However ı have never created a instance named as id -
DRF APITestCase force_authenticate make request.user return tuple instead of User object
I have a custom authentication class following the docs class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) and I used it in my APIView: class profile(APIView): permission_classes = () authentication_classes = (ExampleAuthentication,) def get(self, request, format=None): try: print('user', request.user) serializer = GetUserSerializer(request.user) return JsonResponse({'code': 200,'data': serializer.data}, status=200) except Exception as e: return JsonResponse({'code': 500,'data': "Server error"}, status=500) when I try to call it normally from the API through postman I got the following result from the print and it worked normally: user (<User: User(143)>, True) I written a test as following: class BaseUserAPITest(APITestCase): def setUp(self): # self.factory = APIRequestFactory() self.user = models.User.objects.get_or_create( username='test_user_1', uid='test_user_1', defaults={'agent_type': 1} ) def test_details(self): url = reverse("api.profile") self.client.force_authenticate(user=self.user) response = self.client.get(url) self.assertEqual(response.status_code, 200) I got server error because the print of request.user return a tuple instead of a User object, this is the print from the test log user (<User: User(143)>, True) I tried searching up and seem like there no result or explanation on why this happening My version: django==2.2.8 djangorestframework==3.10.2 -
solr search object and object_list print None
I have implemented solr in django 4+ when i hit the query it return me result but when i run a loop sqs = SearchQuerySet().models(Post).all() sqs.count() # output 3 and run a loop for result in sqs: print(request) output <WSGIRequest: GET '/blogs/search?query=abc'> <WSGIRequest: GET '/blogs/search?query=abc'> <WSGIRequest: GET '/blogs/search?query=abc'> but object or object_list give me None for x in sqs.object_list: print(x) # None output or for x in sqs: print(x.object) # None solr-9.0.0 I want to print fields like x.title and x.publich etc what i am doing wrong please let me know -
Is this login fail? or?
when click login the page no blank to home page just stay in login page the terminal show me "GET /login/?csrfmiddlewaretoken=LK82SQKdzu802NaUuXom8CWRn3S86WWK0XrzEqFCCrUmGGCe06MXoMgFtt0JLDRN&username=tim&password=tim123 HTTP/1.1" 200 3148 and the browser link this http://127.0.0.1:8000/login/?csrfmiddlewaretoken=MWNadf5CSlSmTnCFIlJ5aoJDKHL1ShJJ196HZP01ViEIxg4Zeu7Gqy3rQ7TCxYEM&username=tim&password=tim123 login.html {% extends "main/base.html" %} {% block title %} Login Here {% endblock title %} {% load crispy_forms_tags %} {% block content %} <form class="from-group" method="get"> {% csrf_token %} {{form | crispy}} <button type="submit" class="btn btn-success">Login</button> <p>Don't have an account? Create one <a href="/register">Here</a></p> </form> {% endblock content %} settings.py (i just skip to STARIC it so long STATIC_URL = 'static/' CRISPY_TEMPLATE_PACK = "bootstrap4" (add) LOGIN_REDIRECT_URL = "/" (add) urls.py from django.contrib import admin from django.urls import path, include from register import views as v urlpatterns = [ path('admin/', admin.site.urls), path('register/', v.register, name='register'), path('', include('main.urls')), path('', include('django.contrib.auth.urls')), ] -
Django - problem with adding extra variable to the context that will count matched filters?
I have a function that gives me HTML with filtered products based on several filters that users can use on the website. The filters are the list of checkboxes (multiple choice of course). I managed to pass a product title but I also want to add the number of matched options next to each product title so if the user will select 3 out of 8 checkboxes in Filter 1 and Filter 2 lists then the list of matched product titles and the number of matched filters will be updated. For now the page it looks like this: What I want is this: Where 3 means that this product matches to all 3 options I selected and second product with 1 means that only 1 option matches from Filter 1 and Filter 2. I suppose that I need to add annotate with Count method but how can I do that if my fulter1 and filter2 is a list, not a queryset. views.py def filter_data(request): filter1 = request.GET.getlist('filter1[]') filter2 = request.GET.getlist('filter2[]') product_list = Product.objects.all() if len(filter1) > 0: product_list = product_list.filter(filter1__title__in=filter1).distinct() # how to add matched_products_count in here? if len(filter2) > 0: product_list = product_list.filter(filter2__title__in=filter2).distinct() # how to add matched_products_count in … -
Python-Docx - Jinja2: Populate word document without messing the template
I am trying to populate my word template with info from database. But it keep messing up the template. Any other way to make the result exactly the same as the template? template.docx result.docx Here's my code for views.py def save_devicedemoteapplication(request): samples = DeviceDemoteApplication.objects.all()[0:10] document = DocxTemplate("template.docx") context = { 'content': [], } for sample in samples: count = 0 samp= [count, sample.device.device_name, sample.device.asset_number, sample.device.device_model, sample.device.serial_number, sample.demote_reason, sample.demote_time, sample.device.buy_time, sample.technology_administrator, sample.quality_administrator] context['content'].append(samp) document.render(context) document.save('result.docx') return redirect('/DeviceDemoteApplication/') -
How to get uploaded file in views?
I'm trying to get uploaded data in my views. Firstly, I'm getting the path and after that I have to read the file but Django gives me an error FileNotFoundError: [Errno 2] No such file or directory: '/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx but I have that file. How can I fix that? upload = Upload(file=f) content = ScanDocument(upload.file.path) upload.save() def ScanDocument(file_path): text = docx2txt.process(file_path) return text Note if I use url instead of path then it returns: FileNotFoundError: [Errno 2] No such file or directory: '/media/Meeting%20notes%20notes%20%(1).docx' -
Dynamically change db_table django Meta
Sorry for my English I have a table to manage list of database configurations. Table post in all db have same fields but different name. Eg. table post name is md_post, table post in other db is tdt_post. So, when I access a db configuration I want to remote that database. I did it! But how can I change tb_name in Meta Django Model? These Datatables configurations are non-permanent and may change when I add/update/delete record. I tried it, but it only works one time. Post._meta.db_table = `tdt_post` Post._meta.original_attrs['db_table'] = `tdt_post` When I change the db_table back to 'md_post', it doesn't work. I have looked at the following posts, but it doesn't solve my problem: Django model: change db_table dynamically Change table name for django model in runtime -
I am getting error when to limit foreign keys
Goal: I want to limit(20) the number of Students per Group. I was trying to make validation (based on this question - Limit number of foreign keys), but got a problem - it's working when I am trying to make 21 Student in group in my Django admin panel, but when I'm trying to change login(or other parameters) of Student (the group in this moment has 20 Students), who already in group it turns up an error, because it seems like I already have 20 students and trying to add new one def validate_number_of_students(value): if User.objects.filter(group=value).count() >= 20: raise ValidationError('Already 20 students in group (20)') class User(AbstractUser): role = models.CharField(max_length=max([len(role[0]) for role in ROLES]), choices=ROLES, default=USER, ) group = models.ForeignKey('structure.Group', on_delete=models.SET_NULL, related_name='users', blank=True, null=True, validators=(validate_number_of_students, ) ) I tried to use this method with constraint (limit number of foreign key using Django CheckConstraint) but get an error, maybe I'm doing something wrong? (I have two apps - structure with Group model and users with User model) models.CheckConstraint( name="limit_students_in_group", check=IntegerLessThan( models.Count("group", filter=models.Q(group=models.F("group"))), 20), ) -
Django - problem with saving data in Createview with ModelForm to non-default database
I've got problem with saving data to non-default database. In models.py I've got: grid_fs_storage = GridFSStorage(collection='tab_userinquiries', base_url='mydomain.com/userinquiries/',database='mongo_instance') class DocsUserInquiry(models.Model): query_pk = models.CharField(blank=False, null=False, unique=True, max_length=150, primary_key=True) # auto - calculated query_file_md5 = models.CharField(blank=False, null=True, unique=False, max_length=200) # auto - calculated query_file = models.FileField(upload_to='userinquiries',storage=grid_fs_storage,null=True) # auto from form In views.py: class UploadInquiryFileView(CreateView,LoginRequiredMixin): model=DocsUserInquiry template_name ='new_inquiry.html' success_message = "You've added your new Token successfully" form_class = UploadInquiryFileForm def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): file_name = request.FILES['query_file'].name print(f'file...{file_name}') q_pk = random_id() file_in = self.request.FILES.get('query_file') f_md5 = calculate_md5(file_in) form.instance.query_pk = q_pk form.instance.query_file_md5 = f_md5 form.save() return HttpResponse(self.success_message) The problem is every time when I submit form I've got Exception Type: TypeError Exception Value: database must be an instance of Database I've tried added this to post method: instance = form.save(commit=False) instance.save(using='mongo_instance') but the error is the same. Any ideas how to resolve this issue? NOTE: This issue is related only with modelform or when I use custom list of fields in view. When I'm using CreateView without ModelForm but with fields = 'all' and additionally with the logic passed to form_valid method of the view instead of post everything works fine. Then files are added to my mongo db. -
how to display first_name in database on django
`views.py from allauth.account.views import SignupView from .forms import HODSignUpForm class HodSignUp(SignupView): template_name = 'account/signup.html' form_class = HODSignUpForm redirect_field_name = '' view_name = 'hod_sign_up' def get_context_data(self, **kwargs): ret = super(HodSignUp, self).get_context_data(**kwargs) ret.update(self.kwargs) return ret forms.py from .models import Admin from po.models import User from allauth.account.forms import SignupForm class HODSignUpForm(SignupForm): first_name=forms.CharField(required=False) last_name=forms.CharField(required=False) class Meta: model= Admin fields = ['first_name','last_name'] def save(self,request): user = super(HODSignUpForm, self).save(request) user.is_hod = True user= User(first_name=self.cleaned_data.get('first_name'), last_name=self.cleaned_data.get('last_name')) user.save() return user models.py from po.models import User class Admin(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=30, db_column='first_name') last_name = models.CharField(max_length=30, db_column='last_name') po.models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_active = models.BooleanField(default=True) is_hod= models.BooleanField(default=False) first_name = models.CharField(null=True, max_length=50) last_name=models.CharField(null=True, max_length=50) admin.py from po.models import User class Schooladmin(admin.ModelAdmin): list_display = ("id","is_active","is_hod","first_name","last_name") list_filter = ("is_active","is_hod") add_fieldsets = ( ('Personal Info', { 'fields': ('first_name', 'last_name') }), ) admin.site.register(User,Schooladmin) enter image description here i want this image show name but how does show firstname and lastname on database? -
Can't describe POST request with BaseHandler
sorry for my bad english get request works fine, the data is displayed correctly, but it's not possible to add new data, it shows a server error status 500 Class Test(models.Model): id = models.AutoField(u'id', primary_key=True) name = models.CharField(u'name', max_length=255, null=True) class Meta: db_table = u'test' verbose_name = u'test' verbose_name_plural = u'tests' Class TestHandler(baseHandler): def read(self, request, id=None): return self.model.object.all() enter image description here def create(self, request, id=None): f=Test(request.POST) new=f.save() return new POST http://127.0.0.1:8000/test/ 500 (INTERNAL SERVER ERROR) I tried this, but it doesn't work either: def create(self, request, id=None): new_test = SmartCheckpointVideo( id=request.POST['id'], name=request.POST['name'] ) new_test.save() return new_test and this def create(self, request, id=None): new_test = SmartCheckpointVideo( name=request.POST['name'] ) new_test.save() return new_test I don't understand how to work with BaseHandler, if there is detailed documentation, please share it -
DRF: many=True causes array instead of returning a regular object
I'm using a nested serializer to access the facility address of each facility. The only way the values will actually show is when i add many=true to the "LeadFacilityDetailFacilitySerializer". But the issue is that it will add [] around my address object. Which leads to "undefined" whjen i try to access the items inside my address object: {info.LeadFacilityDetailFacility.AddressInfo.City} serializers.py class LeadAddressSerializer(serializers.ModelSerializer): class Meta: model = FacilityAddress fields = ( "PrimaryAddress", "SecondaryAddress", "City", "RegionOrState", "PostalCode", ) class LeadFacilityDetailFacilitySerializer(serializers.ModelSerializer): AddressInfo = LeadAddressSerializer(source="fa", many=True) class Meta: model = Facility fields = ('mainimage', 'Name', 'AdministratorCell', 'AddressInfo') class LeadFacilityDetailSerializer(serializers.ModelSerializer): LeadFacilityDetailFacility = LeadFacilityDetailFacilitySerializer(source="assigned_facilities") class Meta: model = LeadFacilityAssign fields = ('assigned_facilities', 'datetime', 'id', 'LeadFacilityDetailFacility') models.py class FacilityAddress(models.Model): PrimaryAddress = models.CharField(max_length=150, null=True, blank=True) SecondaryAddress = models.CharField(max_length=150, null=True, blank=True) City = models.CharField(max_length=150, null=True, blank=True) RegionOrState = models.CharField(max_length=50, null=True, blank=True) PostalCode = models.CharField(max_length=30, null=True, blank=True) Geolocation = models.CharField(max_length=30, null=True, blank=True) AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') class Facility(models.Model): Name = models.CharField(max_length=150, null=True, blank=False)