Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to declare abstract class and methods for model implementation?
I wonder if there is a way in Django to create an abstract class where I can declare a method that should be implemented in a model. Normally, in Python, we declare abstract class like this: import abc class MyABC(metaclass=abc.ABCMeta): @abc.abstractmethod def do_something(self, value): raise NotImplementedError And then implement it like this: class MyClass(MyABC): def do_something(self, value): pass What I did with django is: import abc from django.db import models class MyClass(metaclass=abc.ABCMeta): @abc.abstractmethod def __str__(self): raise NotImplementedError class MyClass2(models.Model, MyClass): def __str__(self): pass But this gives me error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I don't understand what I did wrong here. MyClass2 should inherit from MyClass and from models.Model. What I did wrong? Why this is wrong? What is the better way of declaring methods that should be implemented in models? -
Clear the variable x after use in sklearn.linear_model
I developed the django application which use a sklearn.linear_model model to predict the output based on input using form when i submit i get the expected output and then when i revisit the page i get this error how i can clear the x. ValueError at /output/ X has 18 features per sample; expecting 6 Request Method: POST Request URL: http://127.0.0.1:8000/output/ Django Version: 3.0.4 Exception Type: ValueError Exception Value: X has 18 features per sample; expecting 6 Exception Location: C:\Users\Saicharan Pogul\Desktop\Sihva\Project\final\lib\site-packages\sklearn\linear_model\_base.py in decision_function, line 273 Python Executable: C:\Users\Saicharan Pogul\Desktop\Sihva\Project\final\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Saicharan Pogul\\Desktop\\Sihva\\Project\\final\\avasyu', 'C:\\Users\\Saicharan ' 'Pogul\\Desktop\\Sihva\\Project\\final\\Scripts\\python37.zip', 'c:\\users\\saicharan pogul\\anaconda3\\DLLs', 'c:\\users\\saicharan pogul\\anaconda3\\lib', 'c:\\users\\saicharan pogul\\anaconda3', 'C:\\Users\\Saicharan Pogul\\Desktop\\Sihva\\Project\\final', 'C:\\Users\\Saicharan ' 'Pogul\\Desktop\\Sihva\\Project\\final\\lib\\site-packages'] Server time: Fri, 13 Mar 2020 08:38:03 +0000 I tried this to clear all the variable then to i get the error def approvereject(request): files = os.path.join(settings.MODELS, 'classifierfinal.pkl') with open(files, 'rb') as file: classifier = pickle.load(file) # classifier = joblib.load(file) converted_data = input_con(data) print(data) output = classifier.predict([converted_data]) print(output) dis_out = output_con(output) print(dis_out) dis_output = dis_out del converted_data del output del dis_out return render(request, 'output.html', {'output': dis_output}) def clear_data(request): data.clear() return render(request, "landing.html") -
Django crispy forms tabholder can't change css
In my form i would like to change the style of the tabs, if i add a css_class to TabHolder it won't render it, it just keeps the default class. Here is the init of the modelform. def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_method = 'POST' self.helper.layout = Layout( TabHolder( Tab(_('Company'), 'name', css_class='nav-item active'), Tab('Address', 'country', css_class='nav-item'), Tab('Info', 'email', 'phone', 'website', css_class='nav-item'), css_class='nav nav-tabs nav-tabs-highlight nav-justified mb-0' ), ButtonHolder( Submit('submit', "Submit form", css_class='btn btn-primary') ), ) As you can see in TabHolder there is css_class='nav nav-tabs nav-tabs-highlight nav-justified mb-0' but it keeps showing just css_class='nav nav-tabs' -
Html is not recognizing block, endblock arguments. Danjo query
*I am having trouble in my index.html file. {% extends 'base.html' %} works. But everything b/w {% block content %}{% endblock content %} doesn't execute. Here are my files. views.py:-* **from django.shortcuts import render def index(request): return render(request, 'main/index.html')** base.html:- **<!doctype html> {%load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <title>To Do App</title> </head> <body> <div> <nav class=" navbar fixed-top navbar-dark bg-dark"> <a class="navbar-brand" href="/">To Do App</a> </nav> <div class="container"> ***{% block content %} {% endblock content %}*** </div> </div> </body> </html>** index.html:- **{% extends 'base.html'%} {% block content %} <div class="row"> <div class="col"> <h2>Add Item</h2> </div> </div> {% endblock content %}** All it shows is a navbar of dark color saying To Do App I also tried adding advanced things like form but it didn't work so then i added this heading saying Add Item. And guess what it doesn't work -
How to change the Django-allauth default url patterns?
while using the django-allauth as the registeration system, the following codes work well: urls.py urlpatterns = [ path('accounts/', include('allauth.urls')), path('admin/', admin.site.urls), ... ] so, under this settings: when the user wants to signin, then go to 'example.com/accounts/login' when the user wants to signup, then go to 'example.com/accounts/singup' ... but now I want to change the urls to something like: when the user wants to signin, then go to 'example.com/staff/login' when the user wants to signup, then go to 'example.com/staff/singup' ... I just want to change 'accounts' in the urls to 'staff'. I've just tried to revise the urls.py to: urlpatterns = [ path('staff/', include('allauth.urls')), path('admin/', admin.site.urls), ] most of the registration funcitons worked well, except the email comfirmtion. I reveived the confirmation email and clicked on the comfirmation button, but then the redirect url will always be 'example.com/accounts/login', which raise a 404 error. I want to know how to fix this problem, I will: fix it, if this can be done in a few steps use the default settings, if this is complicated or will bring some risks. Versions: Python: 3.8.1 Django: 3.0.4 Django-allauth:0.41.0 I am a freshman on coding (and English), thank you very very much. -
Query for GET request in django
My model: class ABC(models.Model): user_id = models.IntegerField(null=True) itemId = models.IntegerField(null=True) calorie_count = models.IntegerField() I'm trying to get data from database in following manner: Url: /api/?user_id=<user_id> Method: GET, Output: - Response Code: 200 - { "user_id": 1, "calorie_info": [{ "itemId": 10, "calorie_count": 100 }, { "itemId": 11, "calorie_count": 100 }] } and also I want to get the user id with the maximum calorie intake till date API. What will be the query for these 2 API ? -
Django filter by datetime month__gte is not working
I'm using Django 2.2 I have a created field of DateTime type. I'm using following command to filter the records which are greater than specific date q.filter(created__year__gte=2020, created__month__gte=3, created__day__gte=1) In my database there are records for March (3) month and more but not for February (2). When above command is executed, it gives me queryset list of data greater than March 1. But when I use the following command q.filter(created__year__gte=2020, created__month__gte=2, created__day__gte=28) Where month is February (2), it is not giving any data and the queryset is blank. -
ForeignKey and One To Many
i having trouble with a form and a view i have 3 tables: Product Order OrderItem. in the view: i have create Order, and save it to the DB and then i wanted to use the neworder ID and store it in the OrderItem Form. but for somereason when i save the From nothing happen in the DB. see my views,py, in short: i am trying to link Order to OrderItem. Model.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def date_createdview(self): return self.date_created.strftime('%B %d %Y') class Product(models.Model): CATEGORY = ( ('General', 'General'), ('SmartHome', 'SmartHome'), ('Software', 'Software'), ('Mobile', 'Mobile'), ) name = models.CharField(verbose_name='שם', max_length=200, null=True) price = models.FloatField(verbose_name='מחיר', null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY, verbose_name='קטגוריה') description = models.CharField(max_length=200, null=True, verbose_name='מלל חופשי') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Order(models.Model): STATUS = ( ('New', 'New'), ('Work in progress', 'Work in progress'), ('completed', 'completed'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def date_createdview(self): return self.date_created.strftime('%d/%m/%Y') class OrderItem(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) order = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) quantity = models.IntegerField(null=True) def __str__(self): return self.product.name Views.py def createOrder(request, pk): customer = … -
Can selected option tag can carry multiple values using django?
I have this selection in my html <select id="days" name="days" onchange="periods(this)" required> <option>-----</option> {% for perfume in s %} <option value="{{perfume.id}}" value="{{perfume.adddate}}" data-days="{{perfume.adddate}}">{{perfume.product}} - {{perfume.adddate}} Days </option> {% endfor %} </select> -
"Missing staticfiles manifest entry" but no apparent spelling mistakes and path correctly included in .json file
I am running into a classic ValueError: Missing staticfiles manifest entry for 'habitap/img/settings.png' when deploying my app on heroku but can't find where the error could be: 1) I can't see any apparent spelling mistakes between the template where I call the file and the path: How I call the file: <img src="{% static 'habitap/img/settings.png' %}"> and the path to the actual folder is: static/habitap/img/settings.png 2) the path seem to be correctly referenced in the file staticfiles.json: "habitap/img/settings.png": "habitap/img/settings.0900b5e534c2.png", The error could be coming from the use of ` instead of " maybe but all my other static files are being served correctly and I don't think I am doing anything different. I am conscious I am giving very little clue but i am a taker for any tips you may provide at this stage. Thank you ! -
Chart.js not displaying Django Rest API data
I have REST API with django rest framework like this : [ { "id": 2, "timestamp": "2020-03-04T11:46:10+07:00", "vibration": 3, "moisture": 70, "gps_latitude": "-7.760776", "gps_longitude": "110.376113", "gyro_x": 6.58, "gyro_y": 85.0, "gyro_z": -3.9, "accelero_x": 6.58, "accelero_y": 85.0, "accelero_z": -3.9, "displacement": 10, "node_id": 1 }, { "id": 3, "timestamp": "2020-03-05T11:46:10+07:00", "vibration": 4, "moisture": 40, "gps_latitude": "-5.760776", "gps_longitude": "115.376113", "gyro_x": 5.58, "gyro_y": 55.0, "gyro_z": -5.9, "accelero_x": 5.58, "accelero_y": 55.0, "accelero_z": -5.9, "displacement": 50, "node_id": 1 }, { "id": 4, "timestamp": "2020-03-12T11:46:10+07:00", "vibration": 8, "moisture": 90, "gps_latitude": "-5.769776", "gps_longitude": "125.376113", "gyro_x": 7.58, "gyro_y": 65.0, "gyro_z": -9.9, "accelero_x": 4.58, "accelero_y": 45.0, "accelero_z": -4.9, "displacement": 40, "node_id": 2 }] And this is the code for making rest API : models.py from app directory from django.db import models from django.contrib.auth.models import User class Data(models.Model): node_id = models.ForeignKey("Node", on_delete=models.CASCADE) timestamp = models.DateTimeField() vibration = models.IntegerField() moisture = models.IntegerField() gps_latitude = models.CharField(max_length=250) gps_longitude = models.CharField(max_length=250) gyro_x = models.FloatField() gyro_y = models.FloatField() gyro_z = models.FloatField() accelero_x = models.FloatField() accelero_y = models.FloatField() accelero_z = models.FloatField() displacement = models.IntegerField() def __str__(self): return self.node_id class Node(models.Model): node_id = models.IntegerField() This is serializers.py from app directory : serializers.py from .models import Data,Node from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField() … -
Populating drop-down list in Django
Given that I have 2 models: Department Course My django project directories are structured as such: \timetable_generator \detailscourse \templates \detailscourse \partials add_course.html admin.py models.py views.py \detailsdepartment \templates \detailsdepartment \partials add_department.html admin.py forms.py models.py views.py models.py-detailsdepartment looks like this: from django.db import models # Create your models here. class Department(models.Model): department_id = models.CharField(primary_key=True, max_length=20) department_name = models.CharField(max_length=100) def __str__(self): return self.department_name forms.py-detailsdepartment looks like this: from django import forms from .models import Department class DepartmentForm(forms.ModelForm): class Meta(): model = Department fields = '__all__' views.py-detailsdepartment looks like this: from django.shortcuts import render, redirect from django.contrib import messages from .models import Department from .forms import DepartmentForm # Create your views here. def adddepartment(request): form_class = DepartmentForm form = form_class(request.POST or None) if request.method == 'POST': if form.is_valid(): cleaned_info = form.cleaned_data form.save(commit=True) messages.success(request, 'The department is added successfully.') return redirect('/detailsdepartment/adddepartment') else: messages.error(request, 'Department ID already exists.') return redirect('/detailsdepartment/adddepartment') else: return render(request,'detailsdepartment/add_department.html', {'form':form}) admin.py-detailsdepartment looks like this: from django.contrib import admin from .models import Department # Register your models here. class DepartmentAdmin(admin.ModelAdmin): list_display = ['department_id', 'department_name'] admin.site.register(Department, DepartmentAdmin) And the web page of the Department section looks like this add_course.html-detailscourse looks like this: . . . <div class="row mb-5"> <div class="col-lg-12"> <form class="p-4 p-md-5 border … -
Django schedule new events for an object
I am working on a Django app. The purpose of the app is to be able to select a device and then select days of the week and time. After the user clicks save a new scheduled event should be created for that device which sends a request to the Url(already stored in database) of the device for the selected days and time. I don’t know how to achieve this. It would be great if some can help me. -
Can we embed param in URL in Django app from url.py?
I want to embed param in URL by default like I have end point abc.com/abc with call type GET I call from postman like this abc.com/abc?isActive=1 now I want Django to embed key=1 in URL Like This abc.com/abc?isActive=1&key=1 in url.py file I now it looks no sense in it but I need this for some purpose -
Query optimisation for FK association on inherited model from the base model
I have users who create (or receive) transactions. The transaction hierarchy I have is a multi-table inheritance, with Transaction as the base model containing the common fields between all transaction types, such as User (FK), amount, etc. I have several transaction types, which extend the Transaction model with type specific data. For the sake of this example, a simplified structure illustrating my problem can be found below. from model_utils.managers import InheritanceManager class User(models.Model): pass class Transaction(models.Model): DEPOSIT = 'deposit' WITHDRAWAL = 'withdrawal' TRANSFER = 'transfer' TYPES = ( (DEPOSIT, DEPOSIT), (WITHDRAWAL, WITHDRAWAL), (TRANSFER, TRANSFER), ) type = models.CharField(max_length=24, choices=TYPES) user = models.ForeignKey(User) amount = models.PositiveIntegerField() objects = InheritanceManager() class Meta: indexes = [ models.Index(fields=['user']), models.Index(fields=['type']) ] class Withdrawal(Transaction): TYPE = Transaction.WITHDRAWAL bank_account = models.ForeignKey(BankAccount) class Deposit(Transaction): TYPE = Transaction.DEPOSIT card = models.ForeignKey(Card) class Transfer(Transaction): TYPE = Transaction.Transfer recipient = models.ForeignKey(User) class Meta: indexes = [ models.Index(fields=['recipient']) ] I then set each transaction's type in the inherited model's .save() method. This is all fine and well. The problem comes in when I would like to fetch the a user's transactions. Specifically, I require the sub-model instances (deposits, transfers and withdrawals), rather than the base model (transactions). I also require transactions that … -
Return custom JSON response from ListAPIView Django 3.0 Rest Framework
I have created an API using DRF That is able to list and view particular records based on the URL pattern specified. For example: for the request: curl -v http://127.0.0.1:8000/get_details/120001/ I am able to get a response: [ { "subject": "Data Structures", "course": "CSE" }, { "subject": "Thermodynamics", "course": "Chemistry" }, { "subject": "Organic Chemistry", "course": "Chemistry" }, { "subject": "Optics", "course": "Physics" } ] Where '120001' is the user_id the database is searched against. But the I want the response in the following format: {'Chemistry': ['Thermodynamics', 'Organic Chemistry'], 'CSE': ['Data Structures'], 'Physics': ['Optics']} (content wise, I am not considering indentation and other factors) While I am able to write code for the logic of how to create and populate this dictionary, I am unable to figure out how to return this as response and from where. I am using generics.ListAPIView as the view class. Here is my model (models.py): class Subject(models.Model): user_id = models.CharField(null = False, max_length=10) subject = models.CharField(max_length=50) course = models.CharField(max_length=50) def __str__(self): return self.subject Serializer (serializers.py): class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = ['subject', 'course'] and, views.py (for the first output in default format): class SubjectView(generics.ListAPIView): serializer_class = SubjectSerializer def get_queryset(self): username = self.kwargs['user_id'] … -
make get request with post method
i'm trying to make CRUD Api with post method and want to set custom response. i have this type of api for every request and i want to minimize the code and common_list_data,custom_response and decorator are custom defined @api_view(['POST']) @login_required_message def sumInsuredEntityListing(request): data = decode_data(request.data.copy()) q_fields = ['field_name','is_balance','is_thresold','status'] try: response_data = common_list_data(request,data, q_fields, SumInsuredEntitySerializer, SumInsuredEntity) return CustomeResponse(request=request, comment=SIEAV_LIST, message=SIEAV_LIST, data=json.dumps(queryset, cls=UUIDEncoder), status=status.HTTP_200_OK) except Exception as e: return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), comment=COULD_NOT_SHOW_CUSTOM_FIELD, message=SOMETHING_WENT_WRONG, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) so i want to create like this with custom response and with post method class SumInsuredViewSet(viewsets.ViewSet): def list(self,request): queryset=SumInsuredEntity.objects.all() serializer = SumInsuredEntitySerializer(queryset, many=True) return Response(serializer.data) i cant add apiview to class based function so how can i make get with post method -
Populating dropdown in Django using Ajax
I have several dropdowns in my form, which I am looking to populate using Ajax from backend. Given below are the relevant code segments: HTML: <div class="row"> <div class="col-xs-6"> <div class="col-xs-6"> <label name="start_date" class="control-label" style="width:35%">Start date</label> <input type="date" style="color:black;width:100px" ></input> </div> </div> <div class="col-xs-6"> <label name="end_date" class="control-label" style="width:35%">End Date(Default: Current Date)</label> <input style="color:black;width:100px" type="date"></input> </div> </div> <div class="row"> <div class="col-xs-6"> <label name="fruit" class="control-label" style="width:35%; padding-left:15px">Select a Fruit</label> <select style="width:150px;height:30px"> {% for option in options.fruit %} <option value="{{ option }}">{{ option }}</option> {% endfor %} </select> </div> <div class="col-xs-6"> <label name="vendor" class="control-label" style="width:35%">Select a vendor</label> <select style="width:150px;height:30px"> {% for option in options.vendor %} {{ option }} <option value="{{ option }}">{{ option }}</option> {% endfor %} </select> </div> </div> {% block script %} <script> document.onload = function(){ $.ajax({ url : window.location.href, type:'GET', cache:false, data:{type:'formdata'}, success:function(res){ if(typeof res.options == 'undefined'){ self.options = res.options; } if(typeof res.options.start_date == 'undefined'){ self.form.start_date = res.options.start_date; } if(typeof res.options.end_date == 'undefined'){ self.form.end_date = res.options.end_date; } if(typeof res.options.fruit == 'undefined'){ window.fruit = res.options.fruit; } if(typeof res.options.vendor == 'undefined'){ window.vendor = res.options.vendor; } }, error : function(err){ self.message = "Error getting data for the form"; } }); } </script> {% endblock %} Both the drop downs are independent of each … -
The most DB efficient way of retrieving one field of a random ManyToManyField relationship in the template
I have these 2 models: class Tag(models.Model): name = models.CharField(max_length=255, null=True, blank=True) ... class Video(models.Model): tags = models.ManyToManyField('home.Tag', blank=True, related_name='tags') thumbnail_link = models.CharField(max_length=255, null=True, blank=True) ... In a Video listview I want to get 15 random tags, so I use this code: class VideoListView(generic.ListView): model = Video context_object_name = 'video_list' template_name = 'pages/home.html' paginate_by = 12 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) tags = Tag.objects.all().order_by('?')[0:15] context['tags'] = tags return context So far so good, I can iterate over the 15 tags in my template. {% for entry in tags %} {{ entry.name }} {% endfor %} But what I want to do now is get 1 random thumbnail_link of an associated video of a particular tag in my for loop. What works is this: {% for entry in tags %} {% for image in entry.tags.all %} {% if forloop.first %} {{ image.thumbnail_link }} {% endif %} {% endfor %} {% endfor %} But I feel this is very unefficient for the database because you generate an extra for loop in a loop, and you retrieve too much unneccessary data. Also it is too much template logic, I would rather move that to the view. What is the most db efficient … -
Django - Match objects by properties
I have three models: Skill(model): skill = CharField() class Person(Model): skills = ManyToManyField(Skill) class Job(Model): skills = ManyToManyField(Skill) I want to match all jobs with a certain skillset, to candidates with an identical or also similar skillset. How is this usually done? From what I can see, Django does not provide any onboard means. -
Access user Apple ICloud drive using rest api or python
Is it possible too access user's Icloud drive using access token obtained after user authentication using python or rest api, similar to what we have for google drive, google cloud or dropbox ? -
django3.0 utf-8 encoded static files can't load. 'ascii' codec can't encode characters
enter image description here enter image description here/8tP9V.png -
Django query with values() where class contains one to many foreign key
If a class has a one to many relationship, and is queried with other attributes from the class that are just fields (TextFields for example), is it possible to complete this in a values() query, and will it result in a list of nested dictionaries? For example (where you would want to get the value for 'a_field' for all related 'another_class' objects): class some_class(models.Model): some_text = models.TextField(blank=True, null=True) class another_class(models.Model): a_field = models.TextField(blank=True, null=True) many = models.ForeignKey(some_class, models.SET_NULL, db_column='some_class_id', related_name='another_class_things', blank=True, null=True) query_set = ['some_text', 'another_class_things__a_field'] dict_list = some_class.objects.values(*query_set).filter(id='1234').first() where you would normally access all the related values with: obj = some_class() sub_obj_list = obj.another_class_things.all() -
Is it a good practice Django send request to itself
I have a django rest API that serves endpoints. I coded a complex system of permissions from the views, hence the importance of going through the views for my CRUD operations. For a particular need, I must allow an external application to be able to also use a single endpoint to serve all the others. As if this global endpoint were a postal service: we will send information in an envelope: the endpoint to serve, the method, the data ... To avoid writing the same code in several places, I thought from the view of the global endpoint, call the view of one of the endpoints to be served. However, once I get the request in the view, I have to modify it by changing the data, the paths ... to pass it to the other view. But I have to change too much information in the request. So I wonder: can I make an outgoing request to my second endpoint can I use a component as a test Client or Mock do I have to modify the information of the request before calling the second view? What are the best practices? -
I WANT TO GET ALL SESSIONS CRETED BY A USER
MY MODEL I WANT TO GET ALL SESSIONS CRETED BY A USER DO SUGGEST ME WHERE AM I DOING WRONG. class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE) game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) Sports_category=models.CharField(max_length=10,choices=SPORT) SESSIONS=( ('General','General'), ('Business','Business'), ) Session_category=models.CharField(max_length=15,choices=SESSIONS) TYPE=( ('Paid','Paid'), ('Free','Free'), ) Session_type=models.CharField(max_length=10,choices=TYPE) Created=models.DateField(null=True,blank=True) Session_Date=models.DateField(null=True,blank=True) Location=models.ForeignKey(MyUser,related_name='street',on_delete=models.CASCADE) Player=models.CharField(max_length=100,blank=False) Start_time=models.TimeField(auto_now=False, auto_now_add=False) End_time=models.TimeField(auto_now=False, auto_now_add=False) Duration=models.CharField(max_length=30,blank=False) status=( ('1','Active'), ('2','UnActive'), ) Status=models.CharField(max_length=20,choices=status) Equipment=models.TextField() Duration=models.CharField(max_length=20,blank=False) Level=models.ForeignKey(IntrestedIn,blank=True,on_delete=models.CASCADE) GENDER=( ('Male','Male'), ('Female','Female'), ('Male and Female','Male and Female'), ('Other','Other'), ) Gender=models.CharField(max_length=20,choices=GENDER ,blank=True) Fee=models.CharField(max_length=50,blank=True,default='0') def __str__(self): return str(self.Host) class Gamification(models.Model): User_Name=models.ForeignKey(MyUser,on_delete=models.CASCADE) Total=models.IntegerField() def __str__(self): return str(self.User_Name) MY VIEWSET I WANT TO GET ALL SESSIONS CRETED BY A USER DO SUGGEST ME WHERE AM I DOING WRONG. class GamificationViewSet(viewsets.ViewSet): def create(self,request): try: User_Name=request.data.get('User_Name') Total=request.data.get('Total') new=Gamification() new.User_Name=MyUser.objects.get(user_name=User_Name) new.Total new.save() return Response({'Data':'Entered'}) except Exception as error: return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) def list(self,request): …