Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
KeyError: 'user_id' when using PUT request
Recently started working with Django REST framework. I have a user table and another table that stores some relevant data for each user. I've set up POST/GET/DELETE methods fine, but I can't get the method for perform_update working - I keep getting a KeyError at /api/sdgdata/1 'user_id' error in Postman when I attempt a put request for a user. Plz see code below: Models: class TestDataTwo(models.Model): user = models.ForeignKey("auth.User", related_name="testdatatwo", on_delete=models.CASCADE) test_name = models.CharField(max_length=1024, null=True, default="N/A") Serializers: class TestDataTwoSerializer(serializers.ModelSerializer): class Meta: model = TestDataTwo fields = ( "id", "test_name", ) def update(self, instance, validated_data): # get user id from validated data: user_id = validated_data.pop('user_id') # get user: user = User.objects.get(id=user_id) # set user on instance: instance.user = user instance.save() # continue with update method: super().update(instance, validated_data) Views: class TestDataTwoViewSet(ModelViewSet): queryset = TestDataTwo.objects.all().order_by('id') serializer_class = TestDataTwoSerializer paginator = None # CREATE NEW TESTDATATWO ROW FOR USER def perform_create(self, serializer): serializer.save(user=self.request.user) # GET ALL ENTRIES OF TESTDATATWO FOR SPECIFIC USER, EXCEPT IF SUPERUSER, THEN RETURN ALL def get_queryset(self): # if self.request.user.is_superuser: # return self.queryset # else: return self.queryset.filter(user=self.request.user) def perform_update(self, serializer): instance = self.get_object() serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_200_OK) # DELETE TESTDATATWO ID def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return … -
How to generate multiple .pdf docs at once
I am currently trying to print financials for an app that I am using , I would like these to print with the push of a button. However, the system that I am using now (tempFile) can only print one at a time with the following code: import tempfile def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) complexName = pkForm.Complex if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"x_AlltrbYTD":x_AlltrbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero , 'printDesc':printDesc , 'printAcc':printAcc} html_string=render_to_string('main/reports/trialBalanceYear.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalanceMonthly' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"xtrbMonth":xtrbMonth , 'xCreditTotalM':xCreditTotalM , 'xDebitTotalM':xDebitTotalM , 'complexName':complexName , 'printZeroM':printZeroM} html_string=render_to_string('main/reports/trialBalanceMonthly.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) This code only executes the first file instead of both of the files. Does anyone have any other way to print more than 1 pdf document or any changes that I can make to my … -
django form : Data is duplicated instead of updating when i edit in the UI
When I tried to edit the existing data in the Django form it just creating the duplicate entry along with new one. How could I able to get rid of the duplicate entries in the forrm and I have attached the code here. pls someone help me out.Thanks in advance views.py def homeview(request,id=0): userb = Userbase.objects.all() if request.method == 'GET': # new if id==0: form = Userform() # form_mode = 'new' else: # edit user = Userbase.objects.get(pk=id) form = Userform(instance = user) # form_mode = 'update' # post data both adding and updating else: if id==0: # if id==0: form = Userform(request.POST) else:# save from edit user = Userbase.objects.get(pk=id) form = Userform(request.POST, instance=user) if form.is_valid(): form.save() else: messages.error(request, form.errors) return redirect('app:home') return render(request, 'home.html', {'form':form, 'userb':userb}) forms.py class Userform(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder': 'Username'}) self.fields['email'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder': 'E-mail', 'name': 'email', 'id': 'id_email'}) self.fields['timezone'].widget.attrs.update( {'class': 'form-control mb-3', 'name': 'timezone', 'id': 'id_timezone', 'placeholder':'timezone'}) self.fields['my_date'].widget.attrs.update( {'class': 'form-control mb-3', 'placeholder':'Select Timeformat','name': 'my_date', 'id': 'id_my_date'}) class Meta: model =Userbase fields = '__all__'''' urls.py urlpatterns = [ path('', homeview, name='home'), path('<int:id>/', homeview, name='home') ] -
NoReverseMatch Django Project
I want to create the products through the customer's profile, so that the customer's name is attached to the form when creating the product that is related to it. But when I try to enter the user profiles from the dashboard it throws this error urls.py urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/<str:pk>', views.createOrder, name='create_order'), path('update_order/<str:pk>', views.updateOrder, name='update_order'), path('delete_order/<str:pk>', views.deleteOrder, name='delete_order'), path('create_customer/', views.createCustomer, name='create_customer'), ] views.py Here I focus on the "create Order" function passing the customer's primary key and using "initial" to append the customer's name to the form def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request, pk): customer = Customer.objects.get(id=pk) form_value = OrderForm(initial={'customer':customer}) if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = … -
Background Task Django Heroku
I have a problem after deploying my web app at HEROKU, the request lasts 30 second. my app consists to treat excel files and returns new excel files with modifications. The process take more than 30 seconds. I see this tuto https://devcenter.heroku.com/articles/python-rq , but I don't know how to deploy the background task. Ty -
how to reset password by using html template in django djoser
I created classed based view rest api. where I used django djoser. My activation template and all links are worked. but now I am working on reset password where I used template for rest password. but giving 405 error. I was getting reset password link. also my html page is working but when I changed my password and hit on submit its giving me 405 error views.py class ResetPasswordView(View): def get (self, request, uid, token): return render(request, 'password_reset_email.html') # display activation page when user click on link which recieved fron gmail def post (self, request,uid,token): print('In Password Reset Post') new_password=request.post.get("new_password") print("new_password :",new_password) re_new_password=request.post.get("re_new_password") print("re_new_password : ",re_new_password) payload = json.dump({'uid': uid, 'token': token, 'new_password': new_password, 're_new_password': re_new_password}) protocol = 'https://' if request.is_secure() else 'http://' # will evaluate to True if the connection is secure (HTTPS: HTTP over TLS) or False if non-secure (standard HTTP). web_url = protocol + request.get_host() + '/' password_reset_url = "users/reset_password_confirm/" # url used for activate user password_post_url = web_url + AUTHENTICATION_BASE_ROUTE + password_reset_url # for activate user print('url : ', password_post_url) response = request.post(password_post_url,data=payload) return HttpResponse(response.text) urls.py re_path(r'^password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', ResetPasswordView.as_view()), password_reset_email.html <form action="" method="post"> {% csrf_token %} {{ form.as_p}} <div class="container"> <h1>Register</h1> <p>Please fill this form to create … -
Formset does not create an object in the db
I have this "Recipient" model: # Models.py class Recipient(models.Model): Account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) First_name = models.CharField(max_length=100) Last_name = models.CharField(max_length=100) Email = models.EmailField(_('email address'), unique=True) Permitted = models.BooleanField(default=False) def __str__(self): return self.Email And this form, # Forms.py class AddRecipientForm(forms.ModelForm): First_name = forms.CharField(required=True, label = 'First_name', widget = forms.TextInput()) Last_name = forms.CharField(required=True, label = 'Last_name', widget = forms.TextInput()) Email = forms.EmailField(required=True,label = 'Email_address', validators=[validators.EmailValidator()], widget=forms.TextInput()) Permitted = forms.BooleanField(required=False, widget=forms.CheckboxInput()) class Meta(): model = Recipient fields = ('First_name', 'Last_name', 'Email', 'Permitted') I tried to create a Generic FormView where users can add multiple recipient instances using formsets like the code below # Views.py class AddRecipients(LoginRequiredMixin, FormView): context_object_name = 'AddRecipient' template_name = 'Awareness/CyberAwarenessRecipients.html' form_class = AddRecipientForm success_url = reverse_lazy('Awareness:AwarenessHome') Recipient_FormSet = formset_factory(AddRecipientForm, min_num = 1, max_num=100) formset = Recipient_FormSet() def form_valid(self, form): for recipient in self.formset: if recipient.is_valid(): recipient.save() return super().form_valid(form) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['formset'] = self.formset return context But when I check the django admin page, the FormView doesn't commit the recipients to the DB neither redirects me to the success_url after submitting. -
How can i add my company logo in django-oscar homepage?
I am trying out django-oscar for the first time and just for practice I want to add a custom logo in homepage...which template should I modify in order to achieve that -
How to associate a column in a table with a specific user
I am building a social website for delivering objects. I'm trying to assign a location to a user. If the user adds location the location is added to the user only and saved in DB so that the next time he comes to add a product he can select the location he has already added. The problem that I can not assign a location to a specific user is added to DB and appears to all users. class Profile(models.Model): user = models.OneToOneField(User, related_name="pro", on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True, upload_to='img/profile/') phone = models.CharField("Phone Number", max_length=10 , blank=True) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('home') class Location(models.Model): city = models.CharField(max_length=50, choices=cy.city, blank=True) street = models.CharField(max_length=100, blank=True) home_number = models.CharField(max_length=100, blank=True) def __str__(self): return self.city +" "+self.city+" "+ self.street+" "+ self.home_number class Add_Item(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, default=None, null=True) title = models.CharField(max_length=255) categories = models.CharField(max_length=255 , choices= all_categories) description = RichTextField(blank=True,null=True) condition = models.CharField(max_length=100, choices=cond) header_image = models.ImageField(null=True, blank=True, upload_to='img/') more_imges = models.ImageField(null=True, blank=True, upload_to='img/') Pub_date = models.DateField(auto_now_add=True) location = models.ForeignKey(Location, related_name="loc" , on_delete=models.CASCADE ,blank=True, null=True) def get_absolute_url(self): return reverse('home') def __str__(self): return self.title +" "+self.condition View: class AddLocationView(CreateView): model = Location form_class = AddLocationForm template_name ='add_location.html' success_url = reverse_lazy("add-item") def form_valid(self, form): … -
Change value of dropdown in django forms
im trying to update my dropdown (which is in my django forms ) with the id that gets passed. For example views.py form = UploadRoomForm(initial={'companies': company_id}) forms.py companies = forms.ModelChoiceField(queryset=Company.objects.all().order_by('id')) but for some reason. it doesnt pick it up. what am i overlooking here ? when i output the form i get <option value="1" selected>Number 1</option> but in the loaded page i get <option value="" selected>---------</option> -
How to add tensorflow serving in my django postgres container?
Here is my Django container, docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data web: build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db My tensorflow serving run as follows docker run -p 8501:8501 --name tfserving_classifier --mount type=bind,source=C:\Users\Model\,target=/models/img_classifier -e MODEL_NAME=Model -t tensorflow/serving How can I add the above command for tensorflow serving into the same docker-compose of Django and postgres? -
Simple jwt not returning refresh token
I am using simple jwt with django rest. However i dont think the config JWT_AUTH is working. Because i have set the rotate refresh tokens to true but the token-api-refresh url only returns access token while it should also return the refresh. In the settings.py i have INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'shop', 'rest_framework_simplejwt', 'corsheaders', 'django_cleanup' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } JWT_AUTH = { 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=10), 'ROTATE_REFRESH_TOKENS': True, } -
Python's sqlite3 library sometimes returns naive datetimes and sometimes aware datetimes for the same column
I have a TIMESTAMP column in my SQLite database storing a datetime with a timezone, e.g. 2021-09-29 18:46:02.098000+00:00. When I fetch this row inside my Django app, the column is returned as an aware datetime object. However, when I fetch this row in a script that doesn't use Django, in the exact same code path, the column is returned as a naive object. Note that in both cases I am using the built-in sqlite3 library, not Django's ORM. Why are the return types inconsistent? -
unable to execute 'gcc': Permission denied error: command 'gcc' failed with exit status 1 on cPanel
Getting the following Error unable to execute 'gcc': Permission denied error: command 'gcc' failed with exit status 1 while installing mysqlclinet on cPanel pip install mysqlclient -
While running django machine learning model i am facing ModuleNotFoundError: No module named 'sklearn_pandas' confict
*Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, *kwargs) File "C:\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 57, in load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Python39\lib\importlib_init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 850, in exec_module File "", line 228, in _center code hereall_with_frames_removed File "C:\Python39\lib\site-packages\joblib\numpy_pickle.py", line 585, in load obj = _unpickle(fobj, filename, mmap_mode) File "C:\Python39\lib\site-packages\joblib\numpy_pickle.py", line 504, in _unpickle obj = unpickler.load() File "C:\Python39\lib\pickle.py", line 1212, in load dispatchkey[0] File "C:\Python39\lib\pickle.py", line 1528, in load_global … -
Getting template not found error in django
I have tried everything thing and path is correct in view.py but getting template doesn't found error in django My views.py def starting_page(request): return render(request,"tractor/index.html") def posts(request): return render(request,"tractor/all-post.html") I have also added ss of error and my directory. enter image description here enter image description here -
How to Convert Q Object of Django Queryset into SQL?
Suppose we have a Q expression like this: Q(price__lt=160) | Q(publishing_date__year__gte=2016) The SQL expression for this expression would be: price < 160 OR YEAR(publishing_date) >= 2016 I want a package which converts these Q objects of Django into the SQL equivalent. Like: q_obj = Q(price__lt=160) | Q(publishing_date__year__gte=2016) sql_expression = q_obj_to_sql(q_obj) # Please, recommend if there exists such a thing Note: Although Django provides a way to convert Querysets into SQL, but, I need to convert Q objects, and not the Querysets. -
How to disable a input field according to another select field value in bootstrap/crispy?
I'm trying to deactivate existing_name fields based on values that selected on action field I'm using crispy and rendering option for action field from models.py action = models.CharField(max_length=30, choices=[('add', 'Add'), ('delete', 'Delete'), ('modify', 'Modify'), ('rename', 'Rename')]) I had check all same question on Stackoverfllow and all suggested to deactivate it by script with changes happen action fields {% extends "KPI_App/base.html" %} {% load crispy_forms_tags %} {% block content %} <form action="" method="post" autocomplete="off" > {% csrf_token %} <div class="row"> <div class="col-md-4 id='1'">{{form.action|as_crispy_field}}</div> </div> <div class="row"> <div class="row id='existing_name' " >{{form.existing_name|as_crispy_field}}</div> <div class="row"> <div class="col-md-8"> <button type="submit" class="btn btn-success btn-block btn-lg"><i class="fas fa-database"></i> Submit</button> </div> <div class="col-md-4"> <a href="{% url 'KPI_list' %}" class="btn btn-secondary btn-block btn-lg"> <i class="fas fa-stream"></i> Back to List </a> </div> </div> </form> {% endblock content %} <script> $(document).ready(function(){ $("select[name='action']").on('change',function(){ if($(this).val()=='1'){ $("input[name='existing_name']").prop("disabled",false); }else{ $("input[name='existing_name']").prop("disabled",true); } }); }); </script> I can't assign id for these class and use it it script -
How can i make my Django API work for multiple users at the same time?
I created a Django API,lets say that take two numbers as input and returns the sum as output. I wanted my API to work even if i get multiple users request on the API. Can i solve this issue using ThreadPooling? if not can you suggest any other methods to handle multiple user request at the same time. Any kind of help will be really appreciated. Thanks in Advance -
Best practices to configure a modulable web application
I've been having trouble finding the best way to configure a javascript application (with django on the server side). For now, I created an application which is highly configurable using JSON files. For instance, I have some JSON files that defines the composition of pages. I can quickly create a page with a title, a paragraph, a form and a button to send the form by inserting elements in a JSON. So, this part is useful if I want to recreate quickly a new application based on what I already did. For now, when the user load the application, it sends an ajax that retrieve JSON configuration files and send them back where javascript properly creates pages. The thing is, I want to deploy the application using django, and I don't know if this is a good practice concerning security. Indeed django thows an error when I try to load a JSON file locally: In order to allow non-dict objects to be serialized set the safe parameter to False. I'm sure there is a way to remedy that issue but, looking up the internet, I found that django prefers loading data from a database. The thing is, I don't want … -
pyodbc.InterfaceError in pythonanywhere while deploying
I am getting this error while deploying my django website on python anywhere. Please help fixing this issue. -
Screenshot is not taking while screen sharing is on
I am doing a website using Django where i am trying to implement screenshot and screen sharing feature using javascript. I am trying to take screenshot using html2canvas which is a javascript library. In the same webpage, there is a feature of screen sharing besides screenshot. When i click on Take Screenshot, a screenshot of div of video screen is taken. But the video screen is not captured in the screenshot image. <html> <head runat="server"> <title>Demo</title> <style> #video { border: 1px solid #999; width: 50%; max-width: 860px; } .error { color: red; } #photo { width: 51%; border: 4px solid green; padding: 4px; } .warn { color: orange; } .info { color: darkgreen; } </style> <!-- Include from the CDN --> </head> <body> <h1>recording</h1> <form id="form1" runat="server"> <div> <p> This example shows you the contents of the selected part of your display. Click the Start Capture button to begin. </p> <p> <input type="button" id="start" value="Start Capture" />&nbsp; <input type="button" id="stop" value="Stop Capture" /> </p> <p> <a></a> </p> <div id="photo"> <video id="video" autoplay="autoplay"></video> <hr> <a onclick="takeshot()"> Take Screenshot </a> </div> <br /> <h1>Screenshot:</h1> <div id="output"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> const videoElem = document.getElementById("video"); const startElem = document.getElementById("start"); const stopElem = document.getElementById("stop"); // … -
Django filter data in table based on value from another table?
views.py : def dcuinterval(request): var7 = dcu.objects.all() MU_count = Meter_Mapping_Table.objects.filter(DCU_id=dcu.id).count() d = { 'MU_count': MU_count, 'var7': var7, } return render(request, 'dcu_interval.html', d) Models.py: class dcu(models.Model): id = models.AutoField(unique=True, editable=False, primary_key=True) Asset = models.CharField(max_length=128) IMEI_Number = models.CharField(max_length=128) def __str__(self): return self.Asset class Meter_Mapping_Table(models.Model): mid = models.AutoField(unique=True, editable=False, primary_key=True) Meter_id = models.CharField( max_length=128, help_text='(ID of the Meter table)') MU_id = models.CharField(max_length=150) DCU_id = models.CharField(max_length=150, null=True, blank=False) def __str__(self): return self.Meter_id how to filter the data based on the another table filed ? i need to filter the DCU_id based on the DCU tables id field DCU_id =1; DCU.id=1; ANSWER: MU_count=1 like this i need to filter and show that count -
Displaying Django DB values on index.html original path
I have a DB hat hs some values in it. I want to display these values on my index.html. i want to display them on the standard html path path('', views.index, name = "index"), I currently displaying them at path('this_is_the_path/', my_db_class.as_view()), The problem is that i am pulling the values from a class. and i can't figure out how to set the class to the original index.html path. Models.py from django.db import models class Database(models.Model): text = models.TextField() Views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Database # Create your views here. def index(request): return render(request,"index.html",{}) class my_db_class(ListView): model = Database template_name = 'index.html' URLS.PY from django.urls import path from . import views from .views import my_db_class urlpatterns = [ path('', views.index, name = "index"), path('this_is_the_path/', my_db_class.as_view()), ] HTML.PY <ul> {% for post in object_list %} <li> {{ post.text }}</li> {% endfor %} </ul> So my problem is that the above code will only show my DB values at the this_is_the_path path, but i want to show it at the '' path. -
Complex Python module sorting dependency issue
I have a set of "modules" with dependencies. module B depends A module C depends on A and B module D depends on C I can represent each module as an object, and their dependencies as a property: class Module(): def __init__(self, name): self.dependencies = [] self.name = name def __repr__(self): return self.name A = Module("A") A.dependencies = [] B = Module("B") B.dependencies = [A] C = Module("C") C.dependencies = [A, B] D = Module("D") D.dependencies = [C] modules = [C, D, B, A] Suppose I have a list of modules in arbitrary order e.g. [C, D, B, A] Need to write function to take this input list and return a list of all of these modules in dependency order: e.g. [A, B, C, D] starting with A because it has no dependencies, then B because it only depends on A, then C, D for the same reasons. I am stuck in this please help with code, pseudo code """ class Module(): def __init__(self, name): self.dependencies = [] self.name = name def __repr__(self): return self.name # normal modules A = Module("A") B = Module("B") C = Module("C") D = Module("D") E = Module("E") F = Module("F") A.dependencies = [] B.dependencies …