Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Authentication not working
I was following a tutorial to create a Django authentication module in my app so I succeeded in creating user and login but unfortunately, some errors occurred in my project when I'm implementing the authentication, I have attached the code and error below, pls see if anyone can help. error: django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner django_1 | response = get_response(request) django_1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response django_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) django_1 | File "/usr/local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view django_1 | return view_func(*args, **kwargs) django_1 | File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view django_1 | return self.dispatch(request, *args, **kwargs) django_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 492, in dispatch django_1 | request = self.initialize_request(request, *args, **kwargs) django_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 394, in initialize_request django_1 | authenticators=self.get_authenticators(), django_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 272, in get_authenticators django_1 | return [auth() for auth in self.authentication_classes] django_1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 272, in <listcomp> django_1 | return [auth() for auth in self.authentication_classes] django_1 | TypeError: 'str' object is not callable authentication -> jwt.py class JWTAuthentication(BaseAuthentication): def authenticate(self, request): auth_header = get_authorization_header(request) auth_data = auth_header.decode('utf-8') auth_token = auth_data.split(" ") if len(auth_token) != 2: … -
how to get time since from datetime field
In Django templates, I can do time since on my model to get how long a post was made Model class Post(models.Model): author = models.ForeignKey(User, on_delete=CASCADE) trade = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) {{post.date_posted|timesince}} The above would return me something like 1 day, 8 hours ago My question is how would I do it on my model itself? So that the date_posted field returns it in the humanized format itself. I tried adding the following to my model but it doesn't work def FORMAT(self): return timesince(self.date_posted) -
Version control for Custom Postgres Function in Django
I have a custom postgres function in my Django app. Keeping it up to date with migrations works, but is very hard to code review / move changes from the DB to the migration, because each migration is an entire new block of SQL, like so: def update_func(apps, schema_editor): schema_editor.execute( """ CREATE OR REPLACE FUNCTION public.function() .... ect Does anyone have a similar situation and know a better way to version control the function? -
import error 'force_text' from 'django.utils.encoding'
I'm implementing a graphql solution using python, graphene and django and I'm getting the following import error: Result: Failure Exception: ImportError: cannot import name 'force_text' from 'django.utils.encoding' "/home/site/wwwroot/.python_packages/lib/site-packages/graphene_django/utils/utils.py", line 6, in <module> from django.utils.encoding import force_text I'm not sure about the versions and whether I need to import an additional module. My requirements.txt is like: graphene>=2.1,<3 graphene-django>=2.1,<3 graphql-core>=2.1,<3 graphql-relay==2.0.1 django-filter>=2 Has someone had a similar problem and can look at the versions that I use? Thanks -
I am getting a 'TypeError at /' message in the port when running my django code
this is my models.py This is my views.py This is the error page -
Change default value base on changed primary key field
my models: class Student(models.Model): code_stu = models.PositiveIntegerField() age_stu = models.PositiveIntegerField(default=20) class Cal_age(models.Model): code = models.ForeignKey(Student,on_delete=models.SET_NULL) age = models.PositiveIntegerField() When I am changing code field in admin panel,i want age field will change by related value in age_stu -
Transforming SQL Query to Django Expression
Assuming I have the following Django models and the according SQL-Tables with some data: UserAnswer: | id | answer | partquestion_id | |----|--------|-----------------| | 1 | 667 | 1 | PartQuestion: | id | question_id | |----|-------------| | 1 | 1 | Solution: | id | content | question_id | |----|---------|-------------| |1 | 667 | 1 | |2 | 85 | 2 | I want to get all User answers where the answer is equal to the solution of the according question. I've came up with this SQL-Query but can't really think of how to implement this into a Djano query: select * from (useranswer join partquestion on useranswer.partquestion_id = partquestion.id) join solution on partquestion.question_id = solution.question_id where answer=content; This will output the following: | id | answer | partquestion_id | id | question_id | id | content | question_id | |----|--------|-----------------|----|-------------|----|---------|-------------| | 1 | 667 | 1 | 1 | 1 | 1 | 667 | question_id I just can't get my head around this concept in Django. Maybe using F-Expressions and some stuff. Thanks for any advice. -
Autoincrement field dependent for number of specific value appearances in django
I'm looking for a good example or advice to solve my problem in Django & python. I've simple model like Customer class Customer(models.Model): customer_name = models.CharField(max_length=500) CUSTOMER_CHOICES = [ ('pc', 'Private Customer'), ('bc', 'Business Customer'), ] customer_type = models.CharField(max_length=2, choices=CUSTOMER_CHOICES) For all customers, I want to build (and show on page) a specific "Customer Number" based on customer type and a decimal number. I think I might store this value in the Customer table (somethink like this): |id|customer_name|customer_type|customer_number| |1 |Private 1 |pc |1 | |2 |Private 2 |pc |2 | |3 |Business 1 |bc |1 | |4 |Private 3 |pc |3 | |5 |Business 2 |bc |2 | Of course, when I'll modify the customer name or other value (except customer type and customer number) I don't want to update this number. It is possible to avoid the number gaps or duplicate numbers? I think the bellow code will not work (this is just an example as first thought), because I don't know how the code will work when I'll have two different sessions and when I press the save button at the same time. def save(): if customer_number is None: last_number = Customer.objects.all().filter(customer_type=passed_type).last() #bellow in the pseudocode new_invoice_number = … -
I am getting error while installing web3 module in my django project
ERROR: Command errored out with exit status 1: command: 'C:\Users\saran\OneDrive\Desktop\interview\crypto\core\meta\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\saran\\AppData\\Local\\Temp\\pip-install-j3khl3b4\\cytoolz_486c7a4bef2c4764b3179a18383f6bd7\\setup.py'"'"'; __file__='"'"'C:\\Users\\saran\\AppData\\Local\\Temp\\pip-install-j3khl3b4\\cytoolz_486c7a4bef2c4764b3179a18383f6bd7\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\saran\AppData\Local\Temp\pip-record-s5xwa9zp\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\saran\OneDrive\Desktop\interview\crypto\core\meta\include\site\python3.10\cytoolz' cwd: C:\Users\saran\AppData\Local\Temp\pip-install-j3khl3b4\cytoolz_486c7a4bef2c4764b3179a18383f6bd7\ Complete output (49 lines): ALERT: Cython not installed. Building without Cython. running install running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\cytoolz copying cytoolz\compatibility.py -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\_signatures.py -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\_version.py -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\__init__.py -> build\lib.win-amd64-3.10\cytoolz creating build\lib.win-amd64-3.10\cytoolz\curried copying cytoolz\curried\exceptions.py -> build\lib.win-amd64-3.10\cytoolz\curried copying cytoolz\curried\operator.py -> build\lib.win-amd64-3.10\cytoolz\curried copying cytoolz\curried\__init__.py -> build\lib.win-amd64-3.10\cytoolz\curried copying cytoolz\dicttoolz.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\functoolz.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\itertoolz.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\recipes.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\utils.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\cpython.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\dicttoolz.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\functoolz.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\itertoolz.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\recipes.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\utils.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\__init__.pxd -> build\lib.win-amd64-3.10\cytoolz creating build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\dev_skip_test.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_compatibility.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_curried.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_curried_toolzlike.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_dev_skip_test.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_dicttoolz.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_docstrings.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_doctests.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_embedded_sigs.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_functoolz.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_inspect_args.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_itertoolz.py -> build\lib.win-amd64-3.10\cytoolz\tests copying … -
How to convert the image received with django request FILES into pdf
I saw many answers, but it was hard to find the answer I wanted. I don't want to find files locally and save them locally. I want to receive the image with request FILES and convert it directly into pdf. I'd appreciate it if you could give me an answer. Finally, I want to upload it to s3. def create(self): file = self.request.FILES.get('file', None) # image -> pdf # local save() No. ... Is there something wrong with the settings? # settings.py STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Get the name or labe from django IntegerChoices providing a valid value
I have django 3.2 and an IntegerChoices class class Type(models.IntegerChoices): GENERAL = 2, _("general address") DELIVERY = 4, _("delivery address") BILLING = 6, _("billing address") I can get the Value name and label easily by doing Type.GENERAL , Type.GENERAL.name and Type.GENERAL.label. But how can I get these values if I only have the value, e.g. I want to get the Name DELIVERY from the value 4. Type[4].name ist not working as the list values does not correspond to the int values of the enum. Thanks Matt -
how do I increase number of order detail without refreshing
I am beginner in Django, I create checkout page and when user on change input range number enter image description here it s send to server but it work for first one I think because I set same id for all input and I can t change it because it s in for tag how can I fix it? Django part class Ajax_Handler(View): def get(self,request): if request.is_ajax(): count=request.GET['count'] return JsonResponse({'count':count},status=200) ajax part $(document).ready(function(){ var crf=$('input[name=csrfmiddlewaretoken]').val(); $("#icount").change(function(){ $.ajax({ url:'/adding', type:'get', data:{ count:$('#icount').val(), }, success:function(respond){ $('#icount').val(respond.count) } }); }); }); html part <tbody> {% for order in order.orderdetail_set.all %} <tr> <td class="product-image"> {% thumbnail order.product.image "100x100" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} </td> <td class="product-name"><a href="products/{{order.product.id}}">{{order.product.title}}</a></td> <td class="product-price">{{order.product.price|intcomma:False}}تومان</td> <td class="product-quantity"> <label>تعداد</label> <input type="hidden" name="order_id{{order.id}}" value="{{order.id}}"> <input name='count' id='icount' min="1" max="100" value="{{order.count}}" type="number"> </td> <td class="product-total">{{order.totalprice|intcomma:False}}</td> <td class="product-remove"><a href="delete/{{order.id}}"><i class="fa fa-trash-o"></i></a></td> </tr> {% endfor %} </tbody> -
For the two errors of updateview, Django
I will write down the code first and explain it below. views.py class comment_update(UpdateView): model = Comment fields = '__all__' # success_url = reverse_lazy('board') def get(self, request, pk): com = Comment.objects.filter(id=pk) return render(self.request, 'comment_edit.html',{ 'com' : com }) def get_success_url(self): return reverse('board_detail', kwargs={'pk':self.object.board.pk}) urls.py path('board/comment/<int:pk>/update/', views.comment_update.as_view(), name="comment_update") template <form action="{% url 'comment_update' i.id %}"> If i don't use fields in the situation as the code above, A Error occurs. When fields are used, an error of B occur. In the case of B, why does the success_url and get_sufficiency_url not work? A ImproperlyConfigured at /board/comment/4/update/ Using ModelFormMixin (base class of comment_update) without the 'fields' attribute is prohibited. B TemplateDoesNotExist at /board/comment/4/update/ board/comment_form.html -
How to use different key name in MongoDB while working with Django?
I am working on developing a micro service using Django, where I use MongoDB as backend. Folks who wrote the main code used java hence the data already present in the MongoDB collections follows camelcase pattern for e.g. firstName is the key name. Now while working with python I like to name my variables and functions using snake casing like first_name and get_first_name(). What I want is that inside the code I want to refer first name as first_name but while saving first name in DB or returning JSON response of user data I want to return it as firstName? Is there any way to achieve this behaviour? Please help me? -
Django Admin raise 500 error in production Heroku
I know this question was raised multiple times, but wasn't able to solve the problem. Here is my problem: my Django-React app is deployed on Heroku and works great (very simple app). I would like know to access the /admin part of my app, but I get a 500 Internal Server Error. The error appears locally and in Heroku. The DEBUG is False, and unfortunately I can't get the logs to work, neither in Heroku nor locally :( Here is my settings.py: from pathlib import Path import django_heroku import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['vmbf.herokuapp.com', '127.0.0.1', 'localhost'] ADMINS = [('username', 'emailaddress')] MANAGERS = ADMINSEMAIL_HOST = 'host' SEND_BROKEN_LINK_EMAILS=True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'emailaddress' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'students', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', … -
django - q object filtering getlist
I want to make an intersection by bringing intelligence,strength, and charm from the stat variable to the getlist, but it only comes out as a combination. What could be the reason? I'm waiting for your help. class ProductListView(View): def get(self,request): category = request.GET.get('category', None) sub_category = request.GET.get('sub_category', None) stat = request.GET.getlist('stat', None) q=Q() if category: q &=Q(sub_category__category__name=category) if sub_category: q &=Q(sub_category__name=sub_category) if stat: q &=Q(coursestat__stat__name__in=stat) products = Course.objects.filter(q).distinct() results=[{ "course_id" : product.id, "thumbnail" : product.thumbnail_image_url, "user_name" : product.user.name, "sub_category" : product.sub_category.name, "course_name" : product.name, "price" : product.price, "payment_period" : product.payment_period, "course_like" : product.like_set.count() } for product in products] return JsonResponse({"results" : results}) The query parameters created by Postman are as follows. enter image description here -
How to get id from created object in Django
I have models: Group and Members. Group have many members, but when group is creating, currentUser is automaticlly member. I'm doing everything in single request and I have problem with getting id createdGroup. My models: class Group(models.Model): groupName = models.CharField(max_length=100) description = models.CharField(max_length=255) inviteKey = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) class Members(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) groupId = models.ForeignKey(Group, on_delete=models.CASCADE) Form: class GroupForm(forms.ModelForm): groupName = forms.CharField(label='Name', max_length=100) description = forms.CharField(label='Description', max_length=255) inviteKey: forms.CharField(label='Invite Key') class Meta: model = Group fields = ['groupName', 'description'] View: def createGroup(request): if request.method == "POST": form = GroupForm(request.POST) if form.is_valid(): form.save() currentUser = request.user print('group id', request.POST.get('id', '')) #after group creation i would add current member addMember(currentUser, True, True) # should be currentUser, createdGroup, True messages.success(request, f'Group created') return redirect('/') else: form = GroupForm() return render(request, 'group/createGroup.html',{'form': form}) How i can reach newly created group's id? I've tried something like this: group = request.POST.get('id', '') When i console.log request.POST i'm getting only (name, description) -
Django or Flask for building API?
Well, I have a desktop app developed with Python, And this app will communicate with the database for getting some data that are used (i.e login system, Activation of the software ..etc). Now I've come up with which framework should I use Django or Flask? I really get confused about which one is better for my project. Now, let's talk about the API that I want to build( not a website and it doesn't have any views or front-end), They are very small, all I need is a web application that tells the desktop app whether the user request's data which will contain the user's account is registered on the database or not, The other one is for checking if the product key that user entered from the desktop app is valid or not in every run-time. let's keep in mind in the future if we want to develop a feature or change something. I saw some people recommend Django for being have a lot of functionality, in the other hand Flask doesn't and needs extra work. others say that Flask support API whereas Django does not. Flask vs Django look at the table And some people think that Django … -
Data Migration breaking in production when using bulk_update
My application is deployed on Digital Ocean's App Platform for Django. The database is PostgreSQL. The following data migration has run correctly in my local environment. In production it starts but never ends running, so the deploy is automatically cancelled. This data migration affects more or less 40.000 lines in the database. from django.db import migrations def link_answers_to_default_segment(apps, schema_editor): """Create a default segment for each company""" Company = apps.get_model('brand_score', 'Company') Segment = apps.get_model('brand_score', 'Segment') Answer = apps.get_model('brand_score', 'Answer') for company in Company.objects.all(): default_segment = Segment.objects.create(company=company, name='default') answers = Answer.objects.filter(participant__company=company) for answer in answers: answer.segment = default_segment Answer.objects.bulk_update(answers, ['segment']) class Migration(migrations.Migration): dependencies = [ ('brand_score', '0025_auto_20211209_1412'), ] operations = [ migrations.RunPython(link_answers_to_default_segment, reverse_code=migrations.RunPython.noop), ] -
Using Django-reversion in combination with Neo4j
In a project we are using django-reversion for version control. Is there a way to get this to work with neo4j or get the same functionality in another way. -
Amazon-pay-sdk-python CreateButtonSignature
I'm integrating amazon-pay-SDK-python for the web. I have done reading all documentation of amazon-pay, but I didn't get any idea about how to give or create a button signature in Frontend/backend code. Here is my code of frontend to create a button of amazon-pay One-time-checkout. If anyone implemented this, give your valuable answer.. <body> <div id="AmazonPayButton"></div> <script src="https://static-na.payments-amazon.com/checkout.js"></script> <script type="text/javascript" charset="utf-8"> amazon.Pay.renderButton('#AmazonPayButton', { // set checkout environment merchantId: 'merchant_id', publicKeyId: 'SANDBOX-xxxxxxxxxx', ledgerCurrency: 'USD', // customize the buyer experience checkoutLanguage: 'en_US', productType: 'PayAndShip', placement: 'Cart', buttonColor: 'Gold', // configure Create Checkout Session request createCheckoutSessionConfig: { payloadJSON: 'payload', // string generated in step 2 signature: 'xxxx' // signature generated in step 3 } }); </script> </body> -
code H10 while Deploying Django code to Heroku
2021-12-16T14:04:17.499957+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phoneinf0.herokuapp.com request_id=4b00137c-bb8e-426d-b427-fff468ac7491 fwd="94.249.24.198" dyno= connect= service= status=503 bytes= protocol=https -
how to display data of that date of week. which data is exist on that day by using python django
I want to return a week data of date, if data is exist on that date from threading. If there is data of that date, it should appear in the data list, and if there is no data of that date then a blank list should appear. currently I have data in database only of 2 days but same data returning on all 7 days. class TotalExceedance(Thread): def __init__(self,site): Thread.__init__(self) self.site = site def run(self): currentDate = datetime.datetime.now().date() weekAgo = currentDate - datetime.timedelta(days=7) site_label = self.site.json()[0]["label"] week_exc_data = [] for i in range(1,8): total_exceedance = ExceedanceModel.objects.filter(site=site_label,dateTime__date__range=[weekAgo, currentDate]).all().values() day = weekAgo + datetime.timedelta(days=i) print(day) week_exce = total_exceedance,day week_exc_data.insert(0, len(week_exce)) print("week exc data :", week_exc_data) #thread start th2 = TotalExceedance(sites) th2.start() th2.join() getting this output : 2021-12-10 2021-12-11 2021-12-12 2021-12-13 2021-12-14 2021-12-15 2021-12-16 week exc data : [2, 2, 2, 2, 2, 2, 2] I am expecting output like this : 2021-12-10 week exc data : [] 2021-12-11 week exc data : [] 2021-12-12 week exc data :[{'dateTime': '2021-12-12T08:55:00Z', 'site': 'ABCP', 'station': 'ABCP_1', 'parameter': 'COD', 'values': 5000.0}] 2021-12-13 week exc data : [] 2021-12-14 week exc data : [] 2021-12-15 week exc data : [{'dateTime': '2021-12-15T08:55:00Z', 'site': 'ABCP', 'station': 'ABCP_1', 'parameter': 'COD', … -
Delete all documents in a MongoDB collection via Django backend and Angular frontend
I have managed to write code to add a customer to my MongoDB collection from my Angular service method to my Django http function, as follows: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json' }), withCredentials: false } @Injectable() export class MongoService { myApiBaseUrl = "http://localhost:8000/mydjangobaselink/"; constructor(private httpClient: HttpClient) { } addCustomer(customerFormInfo: Customer): Observable<Customer> { return this.httpClient.post<Customer>(`${this.myApiBaseUrl}`, JSON.stringify(customerData), httpOptions); } deleteCustomer(): Observable<Customer> { return this.httpClient.delete<Customer>(`${this.myApiBaseUrl}`); } } @csrf_exempt @api_view(['GET', 'POST', 'DELETE']) def handle_customer(request): if request.method == 'POST': try: customer_data = JSONParser().parse(request) customer_serializer = CustomerModelSerializer(data=customer_data) if customer_serializer.is_valid(): customer_serializer.save() # Write customer data to MongoDB. collection_name.insert_one(customer_serializer.data) response = { 'message': "Successfully uploaded a customer with id = %d" % customer_serializer.data.get('id'), 'customers': [customer_serializer.data], 'error': "" } return JsonResponse(response, status=status.HTTP_201_CREATED) else: error = { 'message': "Can not upload successfully!", 'customers': "[]", 'error': customer_serializer.errors } return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST) except: exceptionError = { 'message': "Can not upload successfully!", 'customers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) elif request.method == 'DELETE': try: CustomerModel.objects.all().delete() # Delete customer data from MongoDB. collection_name.deleteMany({}) return HttpResponse(status=status.HTTP_204_NO_CONTENT) except: exceptionError = { 'message': "Can not delete successfully!", 'customers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) The POST method works fine and I can see the added … -
AttributeError: 'RelatedManager' object has no attribute '' reverse connection
I'm trying to implement reverse connection , but i get this error : 'admin':i.mobileinv_imei.invoice.seller.username, AttributeError: 'RelatedManager' object has no attribute 'invoice' this is my models.py class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) status= models.BooleanField(default=True) class ImeiInvoice(models.Model): item = models.ForeignKey(Imei,on_delete=models.PROTECT,related_name='mobileinv_imei') invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') price = models.DecimalField(max_digits=20,decimal_places=3) class CustomerInvoice(models.Model): seller = models.ForeignKey(User,on_delete=models.PROTECT) customer = models.CharField(max_length=50) mobiles = models.ManyToManyField(Imei,through='ImeiInvoice') im trying to return seller name from Imei model, here is my views.py def imei_sold_lists(request): imeis = Imei.objects.filter(status=False) lists = [] for i in imeis: imei = { 'admin':i.mobileinv_imei.invoice.seller.username, 'customer':i.mobileinv_imei.invoice.customer, 'imei':i.imei, 'price':i.mobileinv_imei.price } lists.append(imei) return JsonResponse({'data':lists}) is there something i've missed please? or should i change something please? Thank you for helping ..