Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Persian text in url djngo
I have some links that include Persian texts, such as: http://sample.com/fields/طب%20نظامی and in the view function i want to access to Persian part, so: request.path_info key = re.findall('/fields/(.+)', url)[0] and i get the error: IndexError at /fields/ list index out of range Actually, the problem is with the index zero because it can not see any thing there! It should be noted that it is a Django project on IIS Server and I have successfully tested it with other servers and the local server. I think it has some thing related to IIS. Moreover i have tried to slugify the url without success. I can encode urls successfully, but i think it is not the actual answer to this question. -
FF92.0 on linux introduces caching issues with django 3.2 inline forms
I've noticed a strange behavior with FF 92.0 (Manjaro Linux, but likely all linux I guess) when using inline forms. Setup: Django inline forms A way to add inlines ajax. I'm using the django forms empty_form Some arbitray # of inline saved on the server for that object (for example, say 3) Load the form, add say 2 inlines using javascript. TOTAL_FORMS now shows value=5 Do NOT submit the form, but F5 for a refresh instead After reload, the inlines shown in the table will mirror that of the server However the TOTAL_FORMS from the management_form will show value=5, instead of the 3 it should. page.js: function insert_inlinedets_form () { let form_idx = $('#id_details-TOTAL_FORMS').val(); console.log("inserting new form " + form_idx); let newrow = $('<tr></tr>').appendTo($('#details_form')); newrow.append($('#empty_form_inlinedets').html().replace(/__prefix__/g, form_idx)); $('#id_details-TOTAL_FORMS').val(parseInt(form_idx)+1); console.log("added row to inlinedets formset"); }; function remove_inlinedets_form () { console.log("remove last form "); let form_idx = $('#id_details-TOTAL_FORMS').val(); if (form_idx>0) { $('#details_form > tr').last().remove(); $('#id_details-TOTAL_FORMS').val(parseInt(form_idx)-1); console.log("removed row from inlinedets"); calc_grand_total(); // existing rows haven't changed but the total might } else { $('#id_details-TOTAL_FORMS').val(); // if no form left, this SHOULD be 0. console.log("No more dets left - nothing done."); } }; html - empty form: <div style="display:none"> <table> <thead></thead> <tbody> <tr id="empty_form_inlinedets"> {% … -
Handle login with JWT auth in reactjs
im trying to handle login with JWT auth and axios in my reactjs app; but everytime i send my data into the backend i get "'data' is not defined no-undef" error... this is my handle submit code in Login.js: class Login extends Component{ constructor(props) { super(props); this.state = {username: "", password: ""}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({[event.target.name]: event.target.value}); } handleSubmit(event) { event.preventDefault(); try { const response = axiosInstance.post('/token/obtain/', { username: this.state.username, password: this.state.password }); axiosInstance.defaults.headers['Authorization'] = "Bearer " + response.data.access; localStorage.setItem('access_token', response.data.access); localStorage.setItem('refresh_token', response.data.refresh); return data; } catch (error) { throw error; } } render() { return (... and this in my axiosInstance file : const axiosInstance = axios.create({ baseURL: 'http://127.0.0.1:8000/', timeout: 5000, headers: { 'Authorization': "Bearer " + localStorage.getItem('access_token'), 'Content-Type': 'application/json', 'accept': 'application/json' } }); how can in handle this error "'data' is not defined no-undef" ???? -
How to build a download counter in django
I am building a freebie website where I allow users to download my source files when they click on the download button. I would like to get the total downloads for each item. Since I am still learning. I need to know what approach I should take to build this. Appreciated it in advance as I have learned soo much from this community. So to summarize I need to have a download counter on each item in admin to know how many times this item has been downloaded. -
JWT authentication in reactjs
im trying to handle login with JWT auth and axios in my reactjs app; but everytime i send my data into the backend i get "'data' is not defined no-undef" error... this is my handle submit code in Login.js: constructor(props) { super(props); this.state = {username: "", password: ""}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({[event.target.name]: event.target.value}); } handleSubmit(event) { event.preventDefault(); try { const response = axiosInstance.post('/token/obtain/', { username: this.state.username, password: this.state.password }); axiosInstance.defaults.headers['Authorization'] = "Bearer " + response.data.access; localStorage.setItem('access_token', response.data.access); localStorage.setItem('refresh_token', response.data.refresh); return data; } catch (error) { throw error; } } how should i handle saving data in localStorage? -
Django Queryset and Union
I have 2 models for global tags and user tags. Both Global_Tag and User_Tag have common field encapsulated in an abstract class. When a user is logged in I show user both user tags and global tags in a list sorted by name. I have defined a queryset of global_tag and user_tag and later doing union on them and order by name. Now my question is if django is actually firing 3 query to database or just 1 query. In pycharm debugger I see it printing data as soon as global_tag queryset is defined and later for user_tag queryset as well. Later for union queryset as well. So my question is django firing 3 queries to db or 2 and doing union and order by in memory OR just firing 1 query to db. I need output of only union query. What the best way to have django only fire last query and not 2 queryset used for preparation of final query. -
How can I login to a service's API using OAuth2 in a Django Web App?
I have a small Django app, that I want to allow users to login to an API with, so then I can perform operations on the data from their account. I know Django has built in libraries to deal with social network authentications, but I wanted to know how to login to services to use the API to interact with the persons account. When a user logs in, it won't be used to log them into my web app as they have a separate account for that it's purely to give me access to the API and their data on the service they log in to. Any help or ideas would be greatly appreciated -
How to CRUD data that's created only by the current user in DRF?
Hi Im currently using DjangoRESTFramework to create an API which I would fetch in ReactJS. My app is a project management system where logged in user could create new clients and projects of each client. Now, I would like my DRF to send the data through the API only those which are created by the current/logged in user. What I have so far is as such: serializers.py: class Client Serializer(serializers.ModelSerializer): class Meta: model = Client fields = '__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' views.py class ClientView(viewsets.ModelViewSet): serializer_class = ClientSerializer queryset = Client.objects.all() permission_classes = [IsAuthenticated] authentication_classes = (TokenAuthentication, ) class ProjectView(viewsets.ModelViewSet): serializer_class = ProjectSerializer queryset = Project.objects.all() permission_classes = [IsAuthenticated] authentication_classes = (TokenAuthentication, ) How can I alter this so that I could only access those data created by the logged in / current user? Thank you so much in advance cheers! -
can't add plus button to django model form
I have to add plus button feature , similar to django admin form , for example when i try to add a new instance and the form has foreign key , in sometimes we dont have the object in the foreign key field , so we have to add a new object for the foreign key field , in django admin its so easy , just added a plus button , and it opens a pop up form , i tried this bellow code to achieve that , but it wont open any pop up form , it just replace the current url in the same window , and when fill the form and hit the save button , it just shows a blank page !? this is what i tried my models.py class MainGroup(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) main_type = models.CharField(max_length=40,unique=True) def __str__(self): return self.main_type class Meta: db_table = 'maingroup' class PartGroups(models.Model): admin = models.ForeignKey(UserAccount,on_delete=models.CASCADE) main_type = models.ForeignKey(MainGroup,on_delete=models.PROTECT,related_name='maintypes') part_group = models.CharField(max_length=30) def __str__(self): return self.part_group and this is my forms.py from django.contrib.admin import site as admin_site,widgets class MainGroupForm(forms.ModelForm): class Meta: model = MainGroup fields = ['main_type'] error_messages = { 'main_type':{ 'required':_('some message'), 'unique':_('some message'), } } widgets = { 'main_type':forms.TextInput(attrs={'class':'form-control','placeholder':_('placeholder')}) … -
Show django form in a designed page
How are you? I m totally new in Django.I designed a page and I wanted to show a django form(edit or create) in a well designed HTML page. but i do not know how. This is my owner method: class OwnerUpdateView(LoginRequiredMixin, UpdateView): """ queryset to the requesting user. """ def get_queryset(self): print('update get_queryset called') """ Limit a User to only modifying their own data. """ qs = super(OwnerUpdateView, self).get_queryset() return qs.filter(user=self.request.user) class OwnerCreateView(LoginRequiredMixin, CreateView): """ Sub-class of the CreateView to automatically pass the Request to the Form and add the owner to the saved object. """ # Saves the form instance, sets the current object for the view, and redirects to get_success_url(). def form_valid(self, form): print('form_valid called') object = form.save(commit=False) object.user = self.request.user object.save() return super(OwnerCreateView, self).form_valid(form) This is my views.py class TaskUpdateView(OwnerUpdateView): model = Task fields = ["title", "text", "endDate"] class TaskCreateView(OwnerCreateView): model = Task fields = ["title","text","status","endDate"] This is my urls.py: app_name='task' urlpatterns = [ path('', views.TaskListView.as_view(), name='all'), path('task/<int:pk>/', views.TaskDetailView.as_view(), name='detail'), path('task/create', views.TaskCreateView.as_view(success_url=reverse_lazy('task:all')), name='task_create'), path('task/update/<int:pk>', views.TaskUpdateView.as_view(success_url=reverse_lazy('task:all')), name='task_update'), path('task/delete/<int:pk>', views.TaskDeleteView.as_view(success_url=reverse_lazy('task:all')), name='task_delete'), path("accounts/login/", views.login, name='login'), path("accounts/logout/", views.logout, name='logout'), ] And this is the models.py: class Task(models.Model): title=models.CharField(max_length=250) text=models.TextField() user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False) status=models.ForeignKey('Status',on_delete=models.SET_NULL,null=True) startDate=models.DateTimeField(auto_now_add=True) endDate=models.DateField(null=True) def __str__(self): return self.title class Status(models.Model): … -
which approach is best to create django react application?
I am coming with a basic question that which approach should I use and why? create Django application and integrate react inside it- so when we run Django it will render react instead of its own templates. create Django project and API's separately and react app separately and let them both talk through API's, on the same server or other. -
How to implement js to django to run 3 functions?
I have found this question which colud work for me, but I don't know js. I want to run 3 function like you see in my views.py, but I'm unable to do that because I use from forms one document that is uploaded to run 3 functions. Can you help me implement this js to my django site. Please provide precise answer. Thanks in advance! This is forms.py class DocumentForm(forms.Form): docfile = forms.FileField(label='Select a file') This is views.py def save_exls(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() return redirect('html_exls') else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form,} return render(request, 'list.html', context) def pandas_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df in dfs.items(): #pandas stuff done.to_excel(writer, sheet_name=name) output.seek(0) response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'list.html', {'form': form}) def html_exls(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) writer = pd.ExcelWriter(output) for name, df … -
Converting dict into different objects
I am building a Blog App and I made a queryset which is showing blog date and likes of every day since blog date, But it is showing in dictionary and i am trying to show both instances differently in table like. Blog Date Likes 20 Sep. 6 Likes 21 Sep. 2 Likes 22 Sep. 4 Likes But it is showing like :- ({20: 6},{21: 2},{22: 4}) views.py from django.db.models.functions import ExtractDay from collections import Counter def page(request): blogpost = get_object_or_404(BlogPost,pk=pk) totals = blogpost.likes_set.filter( blogpost__date=blogpost.date, ).annotate( date=ExtractDay('blogpost__date'), ).values( 'date' ).annotate( n=Count('pk') ).order_by('date').values() results = Counter({d['date']: d['n'] for d in totals}) context = {'results':results} return render(request, 'page.html', context) What have i tried ? :- I have tried lists = [{'id': blog.date, 'name': blog.n} for blog in results ] But it is showing only date like 24 not the likes. than i tried json.dumps(list(results )) than i tried from calendar import monthrange __, ds = monthrange(blogpost.date) finalSecond = [data[i] for i in range(1, ds+1)] But it showed monthrange() missing 1 required positional argument: 'month' I have tried many times but it is still not working. Any help would be much Appreciated. Thank You -
module 'jwt' has no attribute 'ExpiredSignature' GET
module "jwt" has no attribute "ExpiredSignature" I'm getting this error through POSTMAN -
Razorpay window is not loading
I have developed a website using react and django i used razorpay(test-mode) for payment transaction It was working fine but it is not loading payment page when i changed the port 8000 to 7000 it is also not working when i deployed it or used the same code in another project But it is working fine in old project (only when the port is 8000) It is sending success status but the page is not loading: [24/Sep/2021 12:28:51] "POST /razorpay/pay/ HTTP/1.1" 200 243 orders.py @api_view(['POST']) def start_payment(request): # request.data is coming from frontend amount = request.data['amount'] # setup razorpay client this is the client to whome user is paying money that's you client = razorpay.Client(auth=("id", "id")) payment = client.order.create({"amount": int(amount) * 100, "currency": "INR", "payment_capture": "1"}) serializer = "Success" data = { "payment": payment, "order": serializer } return Response(data) -
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use meeting.set() instead. Error with Django m2m fields
i am beginner in Django and i am stucked with the many to many relationship. here i am fetching the google meet data from my google calendar through the calendar API. i have successfully fetched the data but when i save the participants of the meeting.. this error comes. TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use meeting.set() instead. here is the code where problem exists create a partcipant object & save it for email in participants_emails: participant_obj,created = Participant.objects.create( meeting=meeting_obj, email=participants_emails) print(f'participant {participant_obj} was created==== ',created) In the Above code i have access to all emails of participants in the participants_emails and I was to save them in the model. Here below is the models.py from django.db import models from django.contrib.auth.models import User class Meeting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) unique_key = models.CharField(max_length=100, unique=True) subject = models.CharField(max_length=400, null=True, blank=True) start_at = models.DateTimeField( auto_now_add=False, auto_now=False, null=True) end_at = models.DateTimeField( auto_now_add=False, auto_now=False, null=True) feedback_status = models.BooleanField(null=True, default=False) def __str__(self): return self.subject class Participant(models.Model): meeting = models.ManyToManyField(to=Meeting) email = models.EmailField(default=None, blank=True, null=True) def __str__(self): return self.email class Question(models.Model): question_type = [ ('checkbox', 'CheckBox'), ('intvalue', 'Integar Value'), ('text', 'Text'), ('radio', 'Radio Button'), ] question_label = models.TextField(null=True, blank=True) question_type … -
Add login in django by rest API in a template
how are you? I am totally new in Django and I am working on a project that is for task managing. every owner of a task can edit or update but no one else can. I wrote a login function that works correctly but now I want to rewrite it with the rest. I wrote a navbar in which by pressing the login button (in that)you will see the login.html. How can I write login in rest and connect it with my login.html ? Also, I have a question that how can I protect the update and delete method that only the admin and the owner can do them? Thanks in advance My login.html {%extends 'base.html' %} {% block content %} <body> <div id="container"> <div></div> <div class="container"> <h1>Login</h1> <p>Please fill in this form to login.</p> <hr> <form method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> <label for="username"><b>Userame</b></label> <input type="text" placeholder="Enter Username" name="username" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="password" required> <div class="row justify-content-center "> <button type="submit" class="signupbtn btn btn-primary" name="btn">Login</button> </div> </form> {% for message in messages %} <div class="alert alert-danger d-flex align-items-center" role="alert"> <svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:"><use xlink:href="#exclamation-triangle-fill"/></svg> <div> {{ message }} … -
Django: Using multiple select with dynamic Data from SQL
I am in the process of creating a graphical interface for filtering SQL data. There the corresponding table should be selected first. Then it should be possible to select with the drop-down list, which columns of the respective table should be displayed. Does anyone have an approach for me there? Thanks a lot :) Returns the names of the columns of the passed table -
How to count all objects in a queryset related to a specific fields value?
I have a Model Poller that has a field category. I have a filtered queryset of Poller. Now I would like to count the objects for each category like so: Poller 1: Category - Sport Poller 2: Category - Sport Poller 3: Category - Tech Poller 4: Category - Tech Poller 5: Category - Fashion should return a dictionary somewhat to counts = {'Sport' : '2', 'Tech' : '2', 'Fashion' : '1'} # Model class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) poller_category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) # View / query qs = Poller.objects.filter( created_by__username=username).order_by( '-poller_category') Not sure but the ordering itself might be obsolet probably. -
How to get backend data in invoice pdf in django
In invoice.html file where i am rendering data from backend but i don't know how to get data in pdf how to pass the context this is my view can anyone tell me about that? -
How to set query to Autofill Data using Django
My Models: '''class Client(models.Model): name = models.CharField(max_length=40) contact = models.CharField(max_length=11) address = models.CharField(max_length=50) def __str__(self): return self.name class Area(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Route(models.Model): area = models.ForeignKey(Area, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return "%s %s %s" % (self.area, ",", self.name) class Driver(models.Model): name = models.CharField(max_length=30) phone = models.CharField(max_length=11) salary = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) active = models.BooleanField(default=False) client = models.ForeignKey(Client, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) def __str__(self): return "%s" % (self.name) class Attendance(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) name = models.ForeignKey(Driver, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) date = models.DateField() week_one = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_one_loan = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_one_extra = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_two = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_two_loan = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00) week_two_extra = models.DecimalField(decimal_places=2, max_digits=10000, default=0.00)''' I have 5 class 1- client and its just name 2- area also only name 3- route its part from area to make it easy to filter and all name 4- driver name , salary , route from class , client from class 5- attendance here i add it every month (date/ client/driver) all definitely so i have to filter I want when I add data in Attendance class once I select Driver … -
is this correct using of foreign key ? i get error by migrate
class CustomerDetail(models.Model): name = models.CharField(max_length=100,default='') phone_no = models.CharField(max_length=10,unique=True,default='') dob = models.DateField(default='') def __str__(self): return self.name class orderview(models.Model): reference = models.CharField(max_length=100,default='') customer = models.CharField(max_length=100,default='') overalltotal = models.ForeignKey(CustomerDetail, on_delete=models.SET_NULL,null=True,blank=True) def __str__(self): return self.reference class orderdetails(models.Model): product = models.CharField(max_length=100,default='') quantity = models.IntegerField() unit_price = models.IntegerField() total= models.CharField(max_length=30) orderid = models.ForeignKey(orderview,on_delete=models.SET_NULL) def get_total(self): result = self.quantity * self.unit_price return result def save(self, *args, **kwargs): self.total = self.get_total() super(orderdetails, self).save(*args, **kwargs) -
Django "manage.py startapp" functionality through a view
I am trying to create a django app dynamically with respect to user inputs and would want to do it in a view (after a POST request). Is it possible to run python manage.py startapp myNewDynamicApp through Django's view rather than through CLI? I could use shell scripts and call them through os.system() but I wanted to check for options in the current space rather than that. -
Dynamic Dual List Box with django
I'm try to realize a dual Dynamic Dual List Box with django. I try to adapt this jquery plugin: https://www.jqueryscript.net/form/Dual-List-Box-Multi-Selection.html but it doesn't work: button it seems doesn't be cliccable. This my code: forms.py from django import forms from station.models import Station station_all=Station.objects.all() class VdlForm(forms.Form): vdl_name = forms.CharField(label='nome virtual data logger', max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'})) stations = forms.ModelMultipleChoiceField(queryset=station_all) selected_stations = forms.ModelMultipleChoiceField(queryset=Station.objects.none()) views.py from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from .forms import VdlForm def new_vdl(request): template_name = 'vdl.html' heading_message = 'Add a new vdl' if request.method == 'POST': form = VdlForm(request.POST or None) if form.is_valid(): vdl_name = form.cleaned_data.get("vdl_name") stations = form.cleaned_data.get("stations") return HttpResponseRedirect('new_vdl') else: form = VdlForm() return render(request, template_name, {'form': form, 'heading': heading_message, }) vdl.html {% extends 'base.html' %} {% block content %} <form method="post" novalidate> {% csrf_token %} <div class="jp-multiselect"> <div class="from-panel"> {{ form.vdl_name }} <br> {{ form.stations }} </div> <div class="move-panel"> <button type="button" class="btn-move-all-right btn-primary"></button> <button type="button" class="btn-move-selected-right"></button> <button type="button" class="btn-move-all-left"></button> <button type="button" class="btn-move-selected-left"></button> </div> <div class="to-panel"> {{ form.selected_stations }} </div> <div class="control-panel"> <button type="button" class="btn-delete"></button> <button type="button" class="btn-up"></button> <button type="button" class="btn-down"></button> </div> </div> <button type="submit">Submit</button> </form> <script> $(".jp-multiselect").jQueryMultiSelection(); </script> {% endblock %} in my base.html I import the js file mentioned in … -
How to debug and fix the error in the Django
One of the most important problems we face in Django is how to fix the error. There is an error below that I do not know how to troubleshoot and fix the error. What is the best approach and tools for error detection? E:\Bourse\BourseWebApp\BourseDjangoAPI>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' Traceback (most recent call last): File "E:\Bourse\BourseWebApp\BourseDjangoAPI\manage.py", line 22, in <module> main() File "E:\Bourse\BourseWebApp\BourseDjangoAPI\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Maryam\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File …