Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am creating a ecommerce website and i want to display size variant of perticular product
my models.py class SizeVariant(models.Model): size_name=models.CharField(max_length=50) price=models.IntegerField(default=0) def __str__(self): return self.size_name class Product(models.Model): product_name=models.CharField(max_length=50) slug=models.SlugField(unique=True, null=True,blank=True) category=models.ForeignKey(Category, on_delete=models.CASCADE, default=1) price=models.IntegerField() desc=models.TextField() image=models.ImageField(upload_to='products') color_variant=models.ManyToManyField(ColorVariant, blank=True) size_variant=models.ManyToManyField(SizeVariant, blank=True) def save(self,*args,**kwargs): self.slug=slugify(self.product_name) super(Product,self).save(*args,kwargs) my html template <div class="product__details__option__size"> <span>Size:</span> {% for size in product.size_variant.all %} <label for="{{size.size_name}}">{{size.size_name}} <input type="radio" > </label> {% endfor %} </div> i have tried using for loop to show all the size variant of particular product but its not working i think there is problem in for loop. because its not taking size variant from database -
TimeoutError while trying to connect SMTP server
I'm trying to make a website that has a message form so that when somebody submits the form it will be present in the django admin panel, but I will get it in e-mail form as well. Here is the port configuration from settings.py: EMAIL_HOST = 'smtp.live.com' EMAIL_HOST_USER = 'mymail@hotmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TSL = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' My model has the fields name, phone, email and message. The function from views.py: def contact(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): form.save() name = request.POST.get('name') phone = request.POST.get('phone') email = request.POST.get('email') message = request.POST.get('message') subject = "WeCreate - Contact Form" content = f"Name: {name}\nPhone: {phone}\nEmail: {email}\nMessage: {message}" from_mail = 'wecreate.designs.srl@hotmail.com' recipient_list = ['wecreate.designs.srl@gmail.com'] send_mail(subject, content, from_mail, recipient_list, fail_silently=False) return redirect('/contact') else: form = MessageForm() return render(request, '../templates/lpadj/form.html', {'form': form}) And the error log: TimeoutError at /contact/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond If I ping the hostname all the packages return. I have triend different ports, changing the EMAIL_USE_TSL/SSL, changing the host to 'smtp.office365.com' and the firwall lets through the … -
I want to generate a token after I verified the user phone number in Django how can I do that
I write an application which send otp from api server and it actually works but after the user verify the phone number I want to generate a token for the user and after that every time the user want to send the request he should post the token to the headers. first I try tokenauth in rest framework but it needs user to be authenticated and it wants username and password which I can't post this to django server. how can I do that with posting phone number and otp this is all of my code """ Django settings for backend project. Generated by 'django-admin startproject' using Django 3.2.14. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # 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: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ "2858-151-240-216-221.ngrok-free.app", "localhost" ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'home', 'requests', 'users', 'api', 'otp_api' ] MIDDLEWARE = … -
Django: query to iterate through a column values and search match in another table
I have this 2 tables in my DB : I would like a query to iterate through "company_members-id" and if there is a match in the "table_contacts" id column, return the line as a result I need to use the result in my HTML template to populate a selectbox with something like this : HTML template : <select id="members_in_companies"> {% for option in rendered_result %} <option value="{{ option.id}} "> {{ option.first_name}} + " " + {{ option.last_name}} </option> {% endfor %} </select> For example : iterate through the "Nike" company would populate the selectbox with 2 and 4 as selectbox value and " Ellon Musk" and "Willy Wonka". -
Already registered models django
I want to automate registering models in admin.py here is the code: from django.contrib import admin from django.apps import apps models = apps.get_models() for model in models: try: admin.site.register(model) except admin.sites.AlreadyRegistered: pass Even though i added exception it raises this error raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model Group is already registered in app 'auth'. -
Django filtered and pagination issue
I have a form that filter a queryset, filtering are ok, but if I use pagination links, I loose the filtering value. How can I paginate my filter result ? template table.html {% if is_paginated %} <div class="row"> <div class="col-lg-12"> {% if page_obj.has_other_pages %} <nav> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="{{request.path}}?page=1"> First </a> </li> <li class="page-item"> <a class="page-link" href="{{request.path}}?page={{ page_obj.previous_page_number }}"> Previous </a> </li> {% endif %} {% for page_number in page_obj.paginator.page_range %} {% if page_number <= page_obj.number|add:3 and page_number >= page_obj.number|add:-3 %} {% if page_obj.number == page_number %} <li class="page-item active"> <a class="page-link" href="{{request.path}}?page={{ page_number }}"> {{ page_number }} </a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{{request.path}}?page={{ page_number }}"> {{ page_number }} </a> </li> {% endif %} {% endif %} {% endfor %} views.py: class CmsView(ListView): queryset = Cmsexport.objects.all().values() model = Cmsexport template_name = 'table.html' context_object_name = 'table' paginate_by = 10 def get_queryset(self): queryset = super(CmsView, self).get_queryset() field = self.request.GET.get('field') lookup = self.request.GET.get('lookup') value = self.request.GET.get('value') reset = self.request.GET.get('btn-reset') if (field and lookup and value) is not None: field = self.request.GET.getlist('field') lookup = self.request.GET.getlist('lookup') value = self.request.GET.getlist('value') query = dict() for (f,l,v) in zip(field,lookup,value): q = f.lower().replace(" ", "_") + '__' … -
Implement Recurring Classes/Events
I have to implement upcoming classes functionality. Upcoming classes can be repeated weekly or monthly. User will only create it once and repeat logic should be handled from back end. There should be no data duplication. Listing api should return the first 10 upcoming classes where date >= today date. Add live or upcoming Class Upcoming Class listing The last tried solution is: calculate the next 100 dates based on weekly or monthly interval and store it in a list named repeated_dates. write a scheduler which will get the last repeated date and if it less than today date then calculate the next 100 dates and update the list. filter out upcoming classes based on repeated_dates list. The issue is: If I filter out from list, I only get the class object. I don't know which date is matched. If there is only two classes, then it should return 1st 10 classes from these two based on dates >= today date. But in this solution, it will only return 2. Here is the model: REPEAT_CHOICES = ( ('no_repeat', 'Does not repeat'), ('repeat_weekly', 'Repeat Weekly'), ('repeat_monthly', 'Repeat Monthly'), ) def image_path(instance, filename): if filename: extension = filename.split('.')[-1] else: extension = "png" … -
Invalid password format or unknown hashing algorithm. Raw passwords are not stored. Django
I have a signup code views.py: def signup(req): if req.method == 'POST': form = SignupForm(req.POST) if form.is_valid(): form.save() return redirect('/') form = SignupForm() return render(req,'signup.html',{'form':form}) forms.py class SignupForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password','first_name','last_name'] now whenever I try to login with this code the submission is successful but when I go to the admin panel and click on the user, on the password section it says Password: Invalid password format or unknown hashing algorithm. Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using http://localhost/admin/auth/user/3/password/. -
How do I make a serializer for many to many relationships in django if one model is a proxy model?
I have a project with multiple types of users: admins, drivers and commuters. I made proxy models for the drivers class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=200) email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=15, unique=True) password = models.CharField(max_length=50) class Role(models.TextChoices): ADMIN = "ADMIN", 'Admin' COMMUTER = "COMMUTER", "Commuter" DRIVER = "DRIVER", 'Driver' base_role= Role.ADMIN role = models.CharField(max_length=50, choices=Role.choices) def save(self, *args, **kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) def __str__(self): return self.name I want to create a Vehicle model with a many to many relationship with only the drivers and also make serializers to allow me to link instances of drivers to vehicles and also list out all drivers and the vehicles they use. How do I go about this? -
error_css_class doesnt apply to django form
I have a form with one variable 'var1': class MyForm(forms.Form): error_css_class='error' var1=forms.IntegerField(label='var1',widget=forms.NumberInput(attrs={'id':'id_var1', 'name':'var1')) def clean_var1(self): var1=self.cleaned_data.get("var1") if var1 == 2: raise forms.ValidationError('cant be 2!') return var1 and styled the error message: <style> .errorlist { list-style-type: none; padding: 0; margin: 0; } .errorlist li { /* Style each error message */ color: red; } .error { /* the label of the field */ color:red; } .error input{ /* the text field */ border: 2px solid red; } </style> When i render the form using {{form.as_p}} everything works correctly, but when i render it manualy like this <form method="post"> {% csrf_token %} <div> <P>{{ form.var1.label_tag }} {{ form.var1 }} {{ form.var1.errors }}</P> </div> <button type="submit", name="calculate">Submit</button> </form> the class "error" isnt applied to the fields. I want to add stuff bewteen the field so using {{form.as_p}} isnt an option. thanks for the help -
Django annotate by first object from m2o or m2m field
I have 3 models: class Ban: name: models.CharField() person: models.ForeignKey(to="apps.Person") class Employee: name: models.Charfield() person: models.ForeignKey(to="apps.Person") class Person: name: models.Charfield() # here a have access to Ban and Employee as self.ban_set, self.employee_set I can get all Employee objects from Ban object as: ban_object.person.employee_set I need annotate Ban queryset by Employee first object from Ban "person.employee_set" field. I try do this by: employees = Employee.objects.filter(person_id=OuterRef("person_id")) qs = Ban.objects.annotate( employee=Subquery(employees[:1]) ) But I get error: "Cannot resolve expression type, unknown output_field" If I set output_field as models.ForeignKey() for Subquery or annotate, nothing working too -
Django concurrency bug handling
I have an API written in Django that provides user with the list of files that they have. There is also a delete API that can delete a File that the user has. However, there is a bug where a GET request after a deletion still shows the previously deleted object. The GET API uses a filter query on the Files object. While the DELETE API will delete a given file id from the list, by getting and calling .delete(). After googling around, it seems like I need to wrap the database queries into a transaction.atomic block and perform select_for_update() in both of the APIs. Will this solve the issue? By right, if the GET Request is done after receiving the DELETE response it should not ever have this concurrency bug right ? It is only if we sent the requests concurrently. But, select_for_update is locking the database row right? So, will the GET API be able to still read the currently being deleted row? Is this the correct way of handling, or do I need to somehow change the isolation level of the database. Currently the DB is Postgresql which defaults to "Repeatable Read". After reading around, this is … -
Django PostgreSQL - Indexes on JsonField vs. custom fields
I am working on a booking system on Django with the following context: Users can create Items for others to book They can further specify the 'available time' per weekday (mon-sun), i.e. opening_time & closing_time. We can also expect that: A. most users adopt the same 'default' values across 7 weekdays (i.e. override when necessary), and B. most users adopt the same default values, say 8am-10pm. A search on Items by its availability, e.g. "Monday 3-4pm", will be expected and of considerably high traffic, so query performance is a must. I have a few options in mind but cannot decide which is better: Option A: Default values + JsonField + index from django.db import models from django.contrib.postgres.fields import JSONField class Item(models.Model): opening_time = models.TimeField() closing_time = models.TimeField() override = JsonField() class Meta: indexes = [ models.Index(models.F("override__sun_open"), name="override__sun_open"), models.Index(models.F("override__sun_close"), name="override__sun_close"), ... ] The Json will 'override' if necessary - might look something like {'sun_open': 07:00, 'sun_close': 23:00}. The filter() will be more complicated but can save on storage (given most users will use the defaults). Option B: JsonField + index class Item(models.Model): available = JsonField() class Meta: indexes = [ models.Index(models.F("available__sun_open"), name="available__sun_open"), models.Index(models.F("available__sun_close"), name="available__sun_close"), ... ] The query will be easy … -
Django not able display the pdf file from Amazon S3, but able to upload to the amazon S3
i am trying to display my pdf list that had upload to the amazon S3, and i had make sure the connection between django and amazon S3 is correct, cause i am able to upload pdf file to S3 by using admin interface. Currently i am trying to display the list of file that had upload to S3 in a table. I had try to display the pdf file list from S3 and nothing show, but the print statement is able to show when i select the Link of "View PDF List", but no data is displaying at the table that should be display. Now the table is just empty and notthing will be display on the table. i had try looking out, did not find something i think it will help me. demo of the table. (https://i.stack.imgur.com/UVAbi.png) following is my code. views.py views.py def upload_pdf(request): if request.method == 'POST': form = PDFDocumentForm(request.POST, request.FILES) if form.is_valid(): pdf_doc = form.save(commit=False) # Upload the PDF file to S3 s3 = boto3.client('s3') pdf_file = request.FILES['pdf_file'] s3.upload_fileobj(pdf_file, settings.AWS_STORAGE_BUCKET_NAME, f'pdfs/{pdf_file.name}') # Set the S3 URL for the PDF file pdf_doc.pdf_file.name = f'pdfs/{pdf_file.name}' pdf_doc.save() return redirect('pdf_list') else: form = PDFDocumentForm() return render(request, 'customPage/uploadPage.html', {'form': form}) def … -
Django On Delete IntegrityError
I get an integrity Error on deleting a Company. See this code below class Company(models.Model): name = models.CharField(max_length=500, null=True, db_index=True) code = models.CharField(max_length=50, null=True, db_index=True) fmp_code = models.CharField(max_length=50, null=True) stock_exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) exchange = models.CharField(max_length=50, null=True) class CalculationYearlyGrowth(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) date = models.DateField() current = models.BooleanField(default=False, db_index=True) historical_data = models.ForeignKey(CalculatedHistoricalFundamental, on_delete=models.CASCADE) This is the error I got django.db.utils.IntegrityError: update or delete on table "company_company" violates foreign key constraint "company_calculationy_company_id_c31e6552_fk_company_c" on table "company_calculationyearlygrowth" DETAIL: Key (id)=(308248) is still referenced from table "company_calculationyearlygrowth". So every time I want to delete a company and wherever it has foreign relations, I first have to delete CalculationYearlyGrowth of that company manually and I can't delete the Company. I have seen some other questions related to this but None have worked for me and the error itself is confusing since I have a Cascade delete so I don't expect the error to come. Thanks -
Django many-to-many fields and ModelForms
I am now working on a system that is calculating the CO2 emissions of a building. The thresholds are calculated taking into consideration the building type and the area of it. One building can have more building types and each building type has its area which in the end compose the gross area of the building (total area). What I am trying to do is when the user adds a building for calculation they will add the building information and for each building type the area of the it, the total area of the building is not important for now, but I am thinking on calculating it from the sum of the areas of the building types. Here is the models.py file: class BuildingType(models.Model): type = models.CharField(max_length=255, blank=True, null=True) co2_factor = models.DecimalField(max_digits=15, decimal_places=7, blank=True, null=True) class Building(models.Model): bbl = models.CharField(max_length=10, blank=True, null=True, unique=True) area = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) electricity = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) natural_gas = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) building_type = models.ManyToManyField(BuildingType, through='BuildingTypeSize', blank=True, null=True) class BuildingTypeSize(models.Model): building = models.ForeignKey(Building, on_delete=models.CASCADE) building_type = models.ForeignKey(BuildingType, on_delete=models.CASCADE) area = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) I am fairly new to Python and Django, i tried following some tutorials and also the documentation. … -
Django: How to convert "1 day, 1:00:09" in "HH:MM:SS" format
I have time in seconds. To convert it into the "HH:MM: SS" format used hour = forDuration.strftime('%H:%M:%S', forDuration.gmtime(seconds)) but I got this value: 1 day, 1:00:09. Are there any other options to get an hour in this format "HH:MM: SS" -
Expense Sharing api using DRF
I am creating an API which user can add expense in group. Imagine that we have 3 user in a group. User 1 add two expense with amount 90 and 210, and user 3 add an expense with amount 30. So basically when i see the group as User 1 i only should see Who do I owe and who owes me. it means i should see ( User2 owes you 100 and User3 owes you 90 ). first problem is i dont know how to calculate the 90 because user 3 had expense with amount 30 it means user3 owes user 1 100 but with the expense he paid, it will reduce his part from his balance. my main problem is in calculate settlements between 2 users amoung group. class GroupRetrieveView(generics.RetrieveAPIView): queryset = Group.objects.all() serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] def calculate_balance(self, pk): try: group = Group.objects.get(pk = pk) except group.DoesNotExists: return Response({'Error':'Group not found !'}, status=status.HTTP_404_NOT_FOUND) expenses = Expense.objects.filter(group = group) summary = defaultdict(Decimal) for expense in expenses: payer = expense.paid_by.username participants = expense.group.members.all() amount = Decimal(expense.amount) len_participants = participants.count() if len_participants > 0: # payment = amount - share share = amount / len_participants for participant in … -
ArrayField is empty even after serializer.save() (Django and Postgres)
I'm trying to save an existing Python list to an ArrayField in Postgres, but when saved it ends up empty. When I print data['questions'] and data['sources'], they both print a populated list (ex. [question1, question2, question3]), but when I print serializer.data, it shows as: 'sources': [] and 'questions': [] data['conversation']['bot'] works correctly. Hence, the problem might be in the model setup, but I'm unable to figure out what's wrong. I have run py manage.py runserver to migrate changes already but the lists are still empty. Here's the excerpt from views.py: def histories(request): if(request.method == 'POST'): data = JSONParser().parse(request) serializer = HistorySerializer(data=data) if(serializer.is_valid()): result = some_python_dictionary data['conversation']['bot'] = result['answer'] data['sources'] = result['sources'] data['questions'] = result['questions'] serializer.save() return JsonResponse(serializer.data, status=201) models.py from django.db import models import json from django.contrib.postgres.fields import ArrayField # Create your models here. class History(models.Model): conversation = models.JSONField() sources = ArrayField(models.CharField(max_length=256), default=list) questions = ArrayField(models.CharField(max_length=256),size=3, default=list) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return json.dumps(self.conversation) class Meta: verbose_name_plural = "Histories" serializers.py from rest_framework import routers, serializers, viewsets from .models import History class HistorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = History fields = ['conversation', 'sources', 'questions', 'created_at'] -
Google Places API returns diferent street number which was given in auto complete
Something wierd starts to happens with Google Places API. I am working on a Python Django app but Google Places API is returning diferent street number in it queries. I search a street name and number "Rua Augusta, 300": But after selecting it the response cames with other number options instead of the choosen one. Does anyone knows what could be happening? It does happens with other addresses even where I live in. :-) Thank you very much! -
pipenv install ERROR: Couldn't install package: {}
I am trying to run a pipenv install command on my ubuntu 22.04 wsl and keep getting this error. I have looked up online and didn't find anything useful. Does anyone knows how to solve it? First, I run pip3 install pipenv succesfully. After running pipenv install I get the following: Installing dependencies from Pipfile.lock (ccbde9)... [pipenv.exceptions.InstallError]: Collecting mysqlclient==2.2.0 (from -r /tmp/pipenv-nctfx03x-requirements/pipenv-zco7ngoc-hashed-reqs.txt (line 1)) [pipenv.exceptions.InstallError]: Using cached mysqlclient-2.2.0.tar.gz (89 kB) [pipenv.exceptions.InstallError]: Installing build dependencies: started [pipenv.exceptions.InstallError]: Installing build dependencies: finished with status 'done' [pipenv.exceptions.InstallError]: Getting requirements to build wheel: started [pipenv.exceptions.InstallError]: Getting requirements to build wheel: finished with status 'error' [pipenv.exceptions.InstallError]: error: subprocess-exited-with-error [pipenv.exceptions.InstallError]: [pipenv.exceptions.InstallError]: × Getting requirements to build wheel did not run successfully. [pipenv.exceptions.InstallError]: │ exit code: 1 [pipenv.exceptions.InstallError]: ╰─> [24 lines of output] [pipenv.exceptions.InstallError]: /bin/sh: 1: pkg-config: not found [pipenv.exceptions.InstallError]: /bin/sh: 1: pkg-config: not found [pipenv.exceptions.InstallError]: Trying pkg-config --exists mysqlclient [pipenv.exceptions.InstallError]: Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. [pipenv.exceptions.InstallError]: Trying pkg-config --exists mariadb [pipenv.exceptions.InstallError]: Command 'pkg-config --exists mariadb' returned non-zero exit status 127. [pipenv.exceptions.InstallError]: Traceback (most recent call last): [pipenv.exceptions.InstallError]: File "/home/naluh/.local/share/virtualenvs/Otimizador_de_Calendario-e6nrz_ZD/lib/python3.10/site-packages/pipenv/patched/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> [pipenv.exceptions.InstallError]: main() [pipenv.exceptions.InstallError]: File "/home/naluh/.local/share/virtualenvs/Otimizador_de_Calendario-e6nrz_ZD/lib/python3.10/site-packages/pipenv/patched/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main [pipenv.exceptions.InstallError]: json_out['return_val'] = hook(**hook_input['kwargs']) [pipenv.exceptions.InstallError]: File "/home/naluh/.local/share/virtualenvs/Otimizador_de_Calendario-e6nrz_ZD/lib/python3.10/site-packages/pipenv/patched/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in … -
Row size too large error in django after changing charfields to textfields
I have change my database from postgresql to mysql and i got this error : django.db.utils.OperationalError: (1118, 'Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs') Before that i had to change all charfields to textfields because of another error ! And now I have this error! i am using RichTextField from ckeditor , do you think this may be the problem? -
django-filter compose filtered url
I'm using django-filter and I would like to link to the view with a pre-set filter. At this time, I'm doing like this: <a href='{{ url "order_list" }}/?year=2023'> or urlnext = ( reverse('order_list') + "?year=2023" ) return HttpResponseRedirect(urlnext) I would like to know if exists a more elegant approach. Thanks -
Create an exe file from a Django project with pyinstaller
I have a problem with generating an .exe file from a Django project using PyInstaller. My goal is to start the Django development server and open the web browser to the homepage by running the file. For this purpose, I have created a file (start.py) that is supposed to start the server: import os import time import webbrowser from django.core.management import execute_from_command_line os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings") def run_server(): execute_from_command_line(["manage.py", "runserver"]) if __name__ == "__main__": run_server() I create the exe file using PyInstaller: pyinstaller start.py --onefile When I run the exe file (./dist/start), I get the following error: Traceback (most recent call last): File "start.py", line 19, in <module> run_server() File "start.py", line 16, in run_server execute_from_command_line(["manage.py", "runserver"]) File "django/core/management/__init__.py", line 442, in execute_from_command_line File "django/core/management/__init__.py", line 436, in execute File "django/core/management/base.py", line 412, in run_from_argv File "django/core/management/commands/runserver.py", line 74, in execute File "django/core/management/base.py", line 458, in execute File "django/core/management/commands/runserver.py", line 111, in handle File "django/core/management/commands/runserver.py", line 118, in run File "django/utils/autoreload.py", line 673, in run_with_reloader File "PyInstaller/hooks/rthooks/pyi_rth_django.py", line 24, in _restart_with_reloader File "django/utils/autoreload.py", line 272, in restart_with_reloader File "django/utils/autoreload.py", line 229, in get_child_arguments IndexError: list index out of range When I run the start.py file, the server can be started without any … -
Integrating my Django REST API based extension into OpenedX container
I made a django extension according to these details:"Stand up an instance of Open edX using either the Dockerized Tutor release or our https://gallery.ecr.aws/ibleducation/ibl-edx-ce (architected using Tutor). Develop an extension that exposes a REST API endpoint and saves a greeting from the user (secure this endpoint with OAuth2 in the same way that Open edX secures its other API endpoints). This endpoint should do the following things with the user-submitted greeting: Log it (it should be visible in the platform’s LMS logs). Save it in the database (the greeting should be visible from the Django Admin). If the greeting is “hello”, then the view of this API endpoint should call the original greeting endpoint again with “goodbye” as the parameter. This is to make sure that you can write an Open edX view that can make an OAuth2-secured API call with a client ID, a client secret and an access token. Of course, if your code calls this endpoint with “hello” again then it’ll be recursive and things will crash." And now the steps where OpenedX is involed are left only please someone guide me through it. I created a docker container using the image link provided above now I …