Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Keep same URL after form POST
Good day SO, I am a beginner in Django and I have a quick question with Form submission and redirecting. I have been following a guide and am using function-based views as of now. The main problem I have now is that after form submission, the URL changes from http://127.0.0.1:8000/projects/1/ to http://127.0.0.1:8000/projects/1/updateReport How can I make it such that my URL, after form submission, goes back to http://127.0.0.1:8000/projects/1/ (without the /updateReport/). Thank you very much for your help! Here are my urls: url(r'^(?P<project_id>[0-9]+)/$', views.projectView, name='projectView'), url(r'^(?P<project_id>[0-9]+)/updateReport/$', views.updateReport, name='updateReport') Here are my views: def projectView(request, project_id): project = get_object_or_404(Project, id=project_id) reportSet = project.report_set.all() context = { 'project': project, 'reports': reportSet } return render(request,'projectMgmt/projectView.html',context) def updateReport(request, project_id): project = get_object_or_404(Project, id=project_id) sys_msg = "Report Updated!" #Increment Report Version reportSet = project.report_set.all() if reportSet.last(): version = reportSet.last().reportVersion + 1 else: version = 1 #New Report for project #New Report Text (name="reportText" from textarea in page) newText=request.POST['reportText'] try: newReport = Report(project=project, reportVersion=version, reportText=newText) newReport.save() except: sys_msg="Error!" context = { 'project': project, 'reports': reportSet, 'sys_msg': sys_msg } return render(request, 'projectMgmt/projectView.html',context) -
Proper way of handling multiple models in a single session
I'm using Django 2.2.1 to create an app for accept applications from one or multiple applicants. When the first applicant finishes entering their info, they can choose to add another applicant so they can get prompted with a similar form still tied to the same application. My current approach has been creating a hash that will be a field for the application model, then passing that hash through a hidden form between applicants on the same application. This will allow someone to query the existing application with the app hash. Is there a more efficient and secure way to handle multiple models within the same session? In apply/models.py: def Application(models.Model): app_hash = models.CharField(max_length=64, unique=True) In apply/index.html: <input type="hidden" name="h" value="{% if app_hash %} {{app_hash}} {% else %}None{% endif %}"> -
Why are row columns overflowing down on larger screens?
My first row behaves exactly as I want it to on small and larger screen. However, my second row works on smaller screens, but the columns are stacking on top of each other on the right side on larger screens even though there seems to be plenty of room. I want four columns to line together. I have tried playing with the left and right margins and padding, but it has not helped. <div class="row"> <div class="col-sm-6 order-fisrt col-md-6"> <div class="vl"> <a href="{% url 'detail' article.id %}"> <div class="text-center"> <img src="{{ article.pic.url }}" class="img-fluid"> </div> <h1 class="title">{{ article.headline }}</h1></a> <p>{{ article.pub_date|date:"F j, Y" }}</p> <p class="article">{{ article.content|truncatewords:"35" }}</p> </div> <hr class="firstline" /> </div> <div class="col-sm-3"></div> {% elif article.rank == 2 %} <div class="col-sm-3 order-md-first"> <a href="{% url 'detail' article.id %}"> <div class="text-center"> <img src="{{ article.pic.url }}" class="img-second"> </div> <h2 class="title-two">{{ article.headline }}</h2></a> <p>{{ article.pub_date|date:"F j, Y" }}</p> <p class="article">{{ article.content|truncatewords:"20" }}</p> <hr /> </div> </div> {% else %} <div class="row"> <div class="col-sm-3"> <a href="{% url 'detail' article.id %}"> <div class="text-center"> <img src="{{ article.pic.url }}" class="img-second"> </div> <h2 class="title-two">{{ article.headline }}</h2></a> <p>{{ article.pub_date|date:"F j, Y" }}</p> <p class="article">{{ article.content|truncatewords:"20" }}</p> <hr /> </div> </div> -
How to make relationship between a model and AbstractUser/AnonymousUser based on authentication?
I'm trying to make a Pastebin clone using Django. In my models.py file, I have two models: CustomUser which is inherited from AbstractUser Snippet which is inherited from Model from .helpers import url_shortner from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) def __str__(self): return self.username class Snippet(models.Model): id = models.CharField(primary_key=True, max_length=19, default=url_shortner, editable=False) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=50, default="Untitled") content = models.TextField() creation_date = models.DateTimeField(auto_now_add=True) expiration_date = models.DateTimeField(null=True, blank=True) def __str__(self): return self.title Now if there's a guest user want to make a snippet, as far as I know the owner field for this snippet should have a relation to AnonymousUser object so, How to implement it? Is there any kind of relations can relate Snippet object to these two models (CustomUser & GuestUser)? -
How to 'unable to import storages module' error when hosted on heroku although same code is working locally?
I am working on a Django project to the point where it is able to fetch images and static file from Amazon s3 bucket locally but when I push the same code on Heroku app it gives me an application error. When I checked logs it gives unable to import module storages. To verify this when I went to Heroku bash and run pip freeze I can see it has all modules present whatever is required. Although I am running migrate, collectstatic, its not working. How do I fix this problem please help? -
How can I rollback REST api interactions within Django Rest Framework?
I'm working on a project in which multiple REST endpoints are hit on a Django server from a web client in order to create data. If there's an error, sometimes we want to delete the earlier data we created. For example, if I create a car via POST /cars/, and I want to create wheels through a separate endpoint via POST /wheels/ { "car": 1 } I want to delete the car if I wasn't able to add any wheels. Creating endpoints that do all of the actions we may want to rollback at once (instead of hitting multiple endpoints) would require a lot of refactoring and is not really an option. What we'd really like is some a way to do something like this: POST /transaction/start POST /cars/ POST /wheels/ { "car": 1 } POST /transaction/end We'd open a transaction, attach it to the user's session, add the data under that transaction, then close the transaction either when POST /transaction/end is hit or a timeout is reached. I have two major questions about this: Are there any packages out there that do this/is this an accepted pattern? I did a little bit of research and didn't see anything django … -
Django: AttributeError: 'UniqueConstraint' object has no attribute 'fields_orders'
I have a model called "Employment" in my app, which references two models called "User" and "Company". In the Employments table in the database, there is a composite index on the two foreign keys preventing the same user from having two employments with the same company. I am trying to represent this composite index in Django using the UniqueConstraint class, but it is throwing an error which I cannot find any documentation for. This model usually works perfectly fine. However, when I add the UniqueConstraint to the model's indexes, the server throws an error. I've looked at the documentation for UniqueConstraint, as well as the rest of Django's documentation, but could not find any mentions of the error I receive. I've also tried replacing 'User_ID' and 'Company_ID' with 'user' and 'company' in the fields argument for UniqueConstraint, but I obtained the exact same error. Not sure if this is relevant to the issue, but I'm running the Django server with Docker in a python:3.6 container with Django version 2.2. Here is the Employment model: from django.db import models from app.models import User, Company class Employment(models.Model): Employment_ID = models.AutoField(primary_key=True) user = models.ForeignKey(User, db_column='User_ID', on_delete=models.CASCADE) company = models.ForeignKey(Company, db_column='Company_ID', on_delete=models.CASCADE) class Meta: … -
How to Submit Form Data
I want to submit form data to an email template and then send said email. However, no data is being returned in the response. I believe this is an easy problem, but I am inexperienced with Python/Django. I think there is some minor detail I have wrong which is causing issues. Any input is very much appreciated! Views.py def new_opportunity_submit(request): form_class = OpportunityForm if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): account_manager = request.POST.get('account_manager') inside_solutions = request.POST.get('inside_solutions') selected_company = request.POST.get('selected_company') # Email the profile with the # contact information template = get_template('new_opportunity_submit.txt') context = { 'account_manager': account_manager, 'inside_solutions': inside_solutions, 'selected_company': selected_company } content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" + '', ['youremail@gmail.com'], headers={'Reply-To': ''} ) email.send() return redirect('opportunities') return render(request, 'website/opportunities.html', {'form': form_class}) Opportunities.html <form action="{% url 'new_opportunity_submit' %}" method="post" id="newOpportunityForm" data-location-url="{% url 'new_opportunity_location' %}" data-contact-url="{% url 'new_opportunity_contact' %}" novalidate> {% csrf_token %} <div class="field"> <label class="label">Account Manager:</label> <div class="select"> <select name="account_manager" id="account_manager"> <option value="">Select</option> <option value="">Person 1</option> <option value="">Person 2</option> </select> </div> </div> <div class="field"> <label class="label">Inside Solutions:</label> <div class="select"> <select name="inside_solutions" id="inside_solutions"> <option value="">Select</option> <option value="">Person 1</option> <option value="">Person 2</option> </select> </div> </div> <div class="field"> <label class="label">Client Information:</label> <div class="select"> <select … -
How do I make Postgres server talk to Django using my own host ip?
I install ubuntu server on a local machine with host 10.2.10.987. I installed Django, postgressql, and deployed a website on it. I have a mac and im trying to connect to my website on the ubuntu local server using http://10.2.10.987:8000 using a browser I've created a database, a user, and granted ownership of the database to the user. I was able to run the django website on localhost of the ubuntu machine but when I change the ALLOWED_HOSTS to ['localhost']. When I change host to 10.2.10.987:8000 and try to connect from my mac, I get an error Here is my settings.py ''' ALLOWED_HOSTS = ['10.2.10.987'] ''' ''' DATABASES = { default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', 'USER': 'andy', 'HOST': '10.2.10.987', 'PASSWORD': 'testpass', 'PORT': '', } } ''' When I run 'python3 manage.py runserver 10.2.10.987:8000,' I expect to see Performing system checks... System check identified no issues (0 silenced). June 07, 2019 - 19:22:11 Django version 2.2.2, using settings 'project.settings' Starting development server at http://10.2.10.987:8000/ Quit the server with CONTROL-C. BUt i get Performing system checks... System check identified no issues (0 silenced). June 07, 2019 - 19:22:11 Django version 2.2.2, using settings 'project.settings' Starting development server at http://10.1.10.258:8000/ Quit the … -
Inconsistent results between Django admin and unit test with on_delete=PROTECTED
I am making a "simple" part inventory app in Django. I have this as my models.py. from django.db import models # Create your models here. class Site(models.Model): create_date = models.DateField(auto_now_add=True) name = models.TextField(max_length=150, null=False, unique=True, verbose_name="Site name") update_date = models.DateField(auto_now=True) def __str__(self): return self.name class Location(models.Model): create_date = models.DateField(auto_now_add=True) name = models.TextField(max_length=150, null=False, unique=False) site = models.ForeignKey(Site, null=False, on_delete=models.PROTECT) update_date = models.DateField(auto_now=True) @property def site_name(self): try: return self.site.name except Exception as ex: return 'Unknown' def __str__(self): return self.name class Part(models.Model): create_date = models.DateField(auto_now_add=True) name = models.TextField(max_length=150, null=False, unique=True) verbose_name = models.TextField(max_length=150, null=True) update_date = models.DateField(auto_now=True) def __str__(self): return self.name class PartLocation(models.Model): create_date = models.DateField(auto_now_add=True) location = models.ForeignKey(Location, null=False, on_delete=models.PROTECT) number_of_parts = models.IntegerField(null=False) part = models.ForeignKey(Part, null=False, on_delete=models.PROTECT) update_date = models.DateField(auto_now=True) @property def site(self): try: return self.location.site.name except Exception as ex: return 'Unknown' def __str__(self): return f'{self.part.name}/{self.location.name}/{self.site}/{self.number_of_parts}' I added an admin.py that looks like this: from django.contrib import admin from .models import Location, Part, PartLocation, Site class PartLocationAdmin(admin.ModelAdmin): ordering = ('id', 'location', 'part', 'location__site__name', 'number_of_parts',) list_display = ('id', 'part', 'get_part_verbose_name', 'location', 'site', 'number_of_parts',) list_filter = ('id', 'part', 'location', 'location__site__name', 'number_of_parts',) search_fields = ('id', 'part__name', 'location__name', 'location__site__name', 'number_of_parts',) def get_part_verbose_name(self,obj): if obj.part.verbose_name is None: return "-" return obj.part.verbose_name get_part_verbose_name.command_order_field = 'Verbose name' … -
What I should write in my models.py to connect two ManyToMany forms?
Please help me to write code I'm a beginner trying to make website. here is url to picture, take a look https://ibb.co/31DZZJ1 -
how to fixe django.contrib.auth.models.AnonymousUser to User
hi everyone i'm making ecommerce web project and i try to associate user to carts but i have problem with is_authenticated () method when the user is login it's work but it's is logout it's show this error ""ValueError: Cannot assign ">": "cart.user" must be a "User" instance""" model.py def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj i expected to work -
Is it possible to insert raw HTML into TinyMCE?
I have a dump of csv file from older database and need to insert to it to new one. Content field contains raw html, something like: <p>This is great article.</p> <p>Look at this table</p> <h5><table border="0" width="100%" class="text"> <tbody><tr align="center" bgcolor="#d5e2f3"><td>№</td><th> Player</th><th> Club </th><th colspan="2"> Goals</th></tr> <tr align="center" bgcolor="#f6f9fa"><td>1. </td><td align="left"> Klose </td><td> Werder </td><td> 14</td><td>... If I copy and paste whole html code to tinymce in django admin with clicking button edit as html, save it and with {{ content|safe }} django renders text properly. But directly input to database not works - after that django renders raw html. How to insert data to tinymce and tell to editor that it's already html code? I'm using python 3.7, django 2.1. Thanks for your time. -
Django TypeError at / 'set' object is not reversible
Error during template rendering In template /app/templates/base.html, error at line 13 'set' object is not reversible 3 <html> 4 <head> 5 <title>Django blog</title> 6 <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" rel="stylesheet"> 7 <link href="{% static 'css/base.css' %}" rel="stylesheet"> 8 </head> 9 <body> 10 <div> 11 <header> 12 <div class="nav-left"> 13 <h1><a href="{% url 'home' %}">Django blog</a></h1> 14 </div> 15 <div class="nav-right"> 16 <a href="{% url 'post_new' %}">+ New Blog Post</a> 17 </div> 18 </header> 19 {% if user.is_authenticated %} 20 <p>Hi {{ user.username }}!</p> 21 <p><a href="{% url 'logout' %}">Log out</a></p> 22 {% else %} 23 <p>You are not logged in.</p> I am learning Chapter 7: User Accounts of the book Django for Beginners using 2.1.5. It works on localhost. It is not working on the cloud (Heroku) with the error. It says 'set' object is not reversible. I have used versions of the following. django = "==2.1.5", gunicorn = "==19.9.0", whitenoise = "==3.3.1", python_version = "3.7" # blog/urls.py from django.urls import path from .views import ( BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, BlogDeleteView, #new ) urlpatterns = [ path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'), # new path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'), path('post/new/', BlogCreateView.as_view(), name='post_new'), path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), path('', BlogListView.as_view(), name='home'), ] # blog/views.py from django.views.generic import ListView, DetailView from django.views.generic.edit … -
how to define class based views in url.py
I created a class based view for Login and Logout which works completely fine when called with .as_view() but if i use same for another app it gives me function object has no attribute as_view created a class based view added it to url.py created new app->model->form->class based view secondApp/views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.core.mail import send_mail, EmailMessage, BadHeaderError from django.template.loader import render_to_string from django.contrib.sessions.models import Session from django.views.generic import CreateView, View from django.conf import settings from .forms import * from .models import * from login.models import User class addDirector(CreateView): form_class = addDirectorMultiForm template_name = 'admin/add_director_account.html' success_url = 'administrator/' def form_valid(self, form): user = form['user'].save() profile = form['profile'].save() return redirect(self.success_url) urls.py urlpatterns = [ path('admin/', admin.site.urls), #accounts path('accounts/', include('django.contrib.auth.urls')), path('', HomeView.as_view(), name='home'), path('accounts/login', LoginView.as_view(), name = 'LoginView'), # Admin path('administrator/', views.admin_home_view, name = 'admin_home_view'), path('administrator/add_director', views.addDirector.as_view(), name = 'addDirector'), ] error_message: path('administrator/add_director', views.addDirector.as_view(), name = 'addDirector'), AttributeError: 'function' object has no attribute 'as_view' -
how to turn class based view variable to function based view?
in the classs based view I can just go "paginate_by = 8" and in html I can do {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} But for function based view, is there anything i can do such as paginate_by such that I don't have to modify my html from what i have? -
Send two objects to Django Rest framework with React in frontend but only the lastest one appears in Django Rest framewwork
I'm trying to create a data structure like this in Django Rest Framework: [ { "id": 1, "name": "Alamos", "model": [ { "uid": "1", "priority": 1, "task": { "time": 0.0, "student": 0 } } , { "uid": "2", "priority": 2, "task": { "time": 0.0, "student": 0 } } ] However even when I send two objects with 2 "uid" as above with React and send it to Django.I checked with React tool for Mozilla and it shows both objects in the front end. However after sending them to backend, there is only the lastest object appears in django rest framework, in the case above is the object with ("uid": "2") only. So I don't know where it goes wrong? My models.py class Main(models.Model): id= models.AutoField(primary_key=true) name = models.CharField(max_length=120, blank=True, null=True) def __str__(self): return self.mill_name @property def model(self): return self.model_set.all() class Model(models.Model): uid =models.CharField(max_length=120, blank=True, null=True) priority= models.IntegerField(blank = True, null=True) main = models.ForeignKey(Main, on_delete=models.CASCADE) def __str__(self): return self.uid class Task(models.Model): time = models.FloatField(blank=True, null=True) student =models.IntegerField(blank=True, null = True) -
install MySQL-client for django in widows 10
i started a django project on my windows machine and i changed the db to my sql like below : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost' } } now when i wanna migrate tables it gives this error : django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. but when i run pip with version it says that this version is not available like below : pip install pymysql==1.3.14 and it returns this error : ERROR: Could not find a version that satisfies the requirement pymysql==1.3.14 (from versions: 0.3, 0.4, 0.5, 0.6, 0.6.1, 0.6.2, 0.6.3, 0.6.4.dev1, 0.6.4, 0.6.6, 0.6.7, 0.7.0, 0.7.1, 0.7.2, 0.7. 3, 0.7.4, 0.7.5, 0.7.6, 0.7.7, 0.7.8, 0.7.9, 0.7.10, 0.7.11, 0.8.0, 0.8.1, 0.9.0, 0.9.1, 0.9.2, 0.9.3) ERROR: No matching distribution found for pymysql==1.3.14 any idea what should i do ?? -
'tag' is not a registered tag library. Must be one of: - Django app
I added my simple tags to my file in template tags. My first tag is visible and it works properly, but the second one does not work. I recives information ''deposit_earn' is not a registered tag library. Must be one of:' after i added tags to my tempate {% load deposit_earn %}. My tag file looks like this: @register.simple_tag() def multiply(number_instalment_loans, rrso, balance): rrso_percent = rrso/100 return round(discounted_interest_rate(12, number_instalment_loans, rrso_percent, balance)) @register.simple_tag() def deposit_earn(period, interest, balance): interest_percent = interest/100 equals = balance * interest_percent * period / 12 return round(equals) Why is my first tag working and not the second one? I tried to reset the server after registering the tags, but it did not help. Any help will be appreciated. -
Django is crashing and log is showing "ModuleNotFoundError: No module named 'encodings'" after Ubuntu Upgrades
So I made a huge mistake.. We had a running Django app on an Ubuntu server on AWS I was in the process of updating the website, and after I pulled my latest ORIGIN, everything was ok, and the changes were applied. Ubuntu asked me to update/upgrade 150+ packages + 2 important security ones.. I am mostly a front-end developer and this was very new to me, so I thought what's the worst that can happen? I used the command do-release-upgrade as Ubuntu suggested, and I wish it did not.. After everything was done updating, the website crashed, and the error log is being filled up by this error: [Fri Jun 07 07:36:52.723940 2019] [authz_core:error] [pid 9174:tid 139960510220032] [client 202.142.63.118:42070] AH01630: client denied by server configuration: /home/ubuntu/foodlegal/foodlegal-repo/foodlegal/uploads/documents/1704.pdf$ [Fri Jun 07 17:37:27.338040 2019] [wsgi:error] [pid 9171:tid 139960774047488] ERROR django.security.DisallowedHost 2019-06-07 17:37:24,205 exception 9171 139960774047488 /home/ubuntu/foodlegal/foodlegal/lib/python3.5/site-packages/djang$ //this is when the website was working last, below is when it stopped [Fri Jun 07 07:39:24.035879 2019] [mpm_event:notice] [pid 9168:tid 139960902834048] AH00491: caught SIGTERM, shutting down Exception ignored in: <object repr() failed> Traceback (most recent call last): File "/home/ubuntu/foodlegal/foodlegal/lib/python3.5/site-packages/PIL/Image.py", line 572, in __del__ NameError: name 'hasattr' is not defined [Fri Jun 07 07:39:55.591467 2019] [wsgi:warn] … -
How to filter by model proprety
i'm developing a web app that will guide the student what to choose on his next year , if the general average > 12 and specialite ==Si he can choose Si else he is obliged to choose ISIL i want to filter the genral average proprety and compare it with specialite object from MyUser model PS : im new at django views.py : def resultats(request,id=None): etudiant = MyUser.objects.all etud_si = MyUser.objects.all().filter(specialite='SI') etud_isil = MyUser.objects.all().filter(specialite='ISIL') moy = MyUser.objects.all().annotate(moyenne =(F('moyenne_s1')+F('moyenne_s2'))/2) if etud_si and (moy > 12): etud_si.specialite = 'SI' etud_si.save() if id: pr = get_object_or_404(MyUser,id=id) else: pr = request.user context = { 'etudiant':etudiant, 'profile':pr, } return render(request,'resultats.html',context) models.py : class MyUser(AbstractBaseUser,PermissionsMixin): SI = 'SI' ISIL = 'ISIL' SPEC_CHOICES = [ (SI,'SI - System Informatique'), (ISIL,'ISIL - Ingenieur system informatique et logiciels') ] username = models.CharField( max_length=300, validators = [ RegexValidator(regex = USERNAME_REGEX, message = 'Nom d\'utilisateur doit etre Alphanumeric', code = 'nom d\'utilisateur invalid' )], unique = True ) email = models.EmailField(unique = True) nom = models.CharField(default=' ',max_length=300) prenom = models.CharField(default=' ',max_length=300) moyenne_s1 =models.DecimalField(default=00.00,max_digits=4,decimal_places=2) moyenne_s2 = models.DecimalField(default=00.00,max_digits=4,decimal_places=2) specialite = models.CharField(max_length=300,choices=SPEC_CHOICES,default=SI) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','moyenne_s1','moyenne_s2'] def get_update(self): return reverse("edit", … -
Get JSON using Django Recursive Query
I have this: Model: class Category(models.Model): categoryId= AutoField(primary_key=True) parentId = models.ForeignKey('self',on_delete=models.CASCADE,null=True) name = models.CharField(max_length = 200, db_index = True) Table: categoryId parentId name 1 NULL 'Vehicle' 2 1 'Car' 3 1 'Bike' 4 NULL 'Wood' 5 4 'Table' In the HTML template, I want to show the parent categories(categories with parentId as NULL) and the subcategories(categories with parentId as one of the categoryIds) as dropdown items of the parent category Now I want to fetch the data in a way that I can get the JSON data like below so I can easily iterate through it in the template: { {"parent":parentData_1, "child":[c1,c2,....] }, {"parent":parentData_2, "child":[c1,c2,....] }, .....and so on } I guess it is possible with the recursive query. Can anyone please show me how I can achieve this in Django. -
Hosting django to Heroku and getting application error code 10
I think the error may lie in the procfile, but nothing that I try has any luck I have tried at least a dozen different Procfile changes but nothing seems to work, I have tried changing the path thinking that that may be the problem. I have also tried changing creative_agency.wsgi to creative_agency.wsgi.application and creative_agency.WSGI_APPLICATION as these are how the variable is saves in the settings.py file log files 2019-06-07T16:16:19.567443+00:00 app[web.1]: ModuleNotFoundError: No module named 'creative_agency.wsgi' 2019-06-07T16:16:19.567565+00:00 app[web.1]: [2019-06-07 16:16:19 +0000] [10] [INFO] Worker exiting (pid: 10) 2019-06-07T16:16:19.592819+00:00 app[web.1]: [2019-06-07 16:16:19 +0000] [4] [INFO] Shutting down: Master 2019-06-07T16:16:19.592959+00:00 app[web.1]: [2019-06-07 16:16:19 +0000] [4] [INFO] Reason: Worker failed to boot. 2019-06-07T16:16:19.668495+00:00 heroku[web.1]: Process exited with status 3 2019-06-07T16:16:21.000000+00:00 app[api]: Build succeeded 2019-06-07T16:17:25.387844+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=westandfaring.herokuapp.com request_id=f7e8183d-83cb-4802-b148-d96012042df e fwd="68.180.94.197" dyno= connect= service= status=503 bytes= protocol=https 2019-06-07T16:17:25.626514+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=westandfaring.herokuapp.com request_id=523ff9c5-1c50-4521-b1b3- a815108f8af7 fwd="68.180.94.197" dyno= connect= service= status=503 bytes= protocol=https 2019-06-07T16:21:26.403447+00:00 heroku[web.1]: State changed from crashed to starting 2019-06-07T16:21:31.577667+00:00 heroku[web.1]: Starting process with command `gunicorn creative_agency.wsgi` 2019-06-07T16:21:33.645817+00:00 heroku[web.1]: State changed from starting to crashed settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'webpage.apps.WebpageConfig' WSGI_APPLICATION = 'creative_agency.wsgi.application' Procfile web: gunicorn creative_agency.wsgi Also, … -
Count most used words from Django Model
I got basic Django app with BeautifulSoup webscrapped that gets data about Author and Content then saves it to the database. I need to get top 10 most used words from that Content Models. I know how to get the top 10 from a url source but i have to get it from Model, can anyone help me with idea behind that? -
Create availability calendar with Python HTMLCalendarModule
I'm building a rental system for my university project where you can rent mainly tools. When someone wants to rent a tool, he should choose a date in the calendar to make a reservation. After making the reservation, the date should get colorized, which implies you can't rent this specific tool anymore on this date. I am working with Django and Python. I am trying to get this task done with the Python HTMLCalendarModule, but I really struggle with it as I am a total beginner. My question is if it is even possible to get this task done only with the Python Calendar? I am not asking for a complete guide or code (I won't reject it though :P), I just need some guidance