Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Go to next page when True
JavaScript was created as follows: If the diction value is true, I want to go to another page, and if it is false, I want to let you go to Home. What should I do? async function predict() { // predict can take in an image, video or canvas html element var image = document.getElementById("face-image") const prediction = await model.predict(image, false); prediction.sort((a,b) => parseFloat(b.probability) - parseFloat(a.probability)); switch (prediction[0].className){ case "True": resultMessege = "성공" break; case "False": resultMessege = "실패." break; default: resultMessege = "알 수 없는 오류가 발생하였습니다. 다시 시도해보시길 바랍니다." } $('.result-message').html(resultMessege); -
How to add links to other apps working with markdown?
I have a project with 2 apps: main and articles. main contains some products (the Product model) and it's linked to project's main url (i.e. 'main.urls') so if you type example.com/products/best-product you'll go (via slug) to this product view. No need to add .../main/... articles app is like blog app that under example.com/articles/art-1 you'll see obviously some Article object. It is rendered with markdown by markdown() function defined in markdown_extras.py Now, what I want to do is inside any Article have links to any Product objects. It's trivial without markdown: {% url 'main:product' prod_obj.slug %} but how to do this with markdown? Ideally the syntax (considering different target models) would be: I recommend [this product](main:product best-product) for you. I tried with basic syntax but any link leads to example.com/articles/art-1/name So containing: app name, target model, slug/id. I've found some solutions but mostly for external links or internal (this page, not this django project). -
Getting Count Result With Multiple Conditions
I have models named Class, StudentList, Child, TakingQuiz and TakingQuizAnswer. Students can take exams. In this case, when they start the exam, data is added to the 'TakingQuiz' table. With each new answer, the answers are also recorded in the TakingQuizAnswer table. The result I want to reach -> The question with the most mistakes in the exams solved by the students in a class. I tried to use Count for this. I'm filtering answer_is_correct to False but that is insufficient. I also need to filter this data for the question column. So I need to get rows where both question and answer_is_correct = False columns are the same and return the first few most repetitive data as results. I always get a general result in my experiments. I can't include rows where the question column is the same. How can I access the questions with the most mistakes in exams solved by students studying in a class? Serializer class ClassSerializerReport(ModelSerializer): instructor = InstructorSerializerReport(source="instructor.user") students = StudenListSerializerReport(many=True, source="student_list_class") max_incorrect_question = serializers.SerializerMethodField() class Meta: model = Class exclude = [ "created_at", "updated_at", "school", ] def get_max_incorrect_question(self, obj): data = Class.objects.filter(id = obj.id).values('student_list_class__child__child_taking_quiz__taking_quizes').annotate(res = Count('student_list_class__child__child_taking_quiz__taking_quizes__question', filter = Q(student_list_class__child__child_taking_quiz__taking_quizes__answer_is_correct = False))) print(data) return … -
How to show a loader when one of the paypal payment options gets clicked
I've been working on a Django project, and I added paypal to my site. I know basic python and javascript, but i'm still new to them. After payment by paypal it takes some time to do some code internally, so I want to show a loader when user clicked one of the paypal payment options. I have no idea to do this. Thank you in advance. -
How to display django array data
I am using Django postgresql. I have insert some data into models array field. My models are like class PurchaseInvoice(models.Model): invoice = models.CharField(max_length=20) date = models.DateField(default=date.today) product_name = ArrayField(models.CharField(max_length=500)) price = ArrayField(models.CharField(max_length=300)) quantity = ArrayField(models.CharField(max_length=200)) amount = ArrayField(models.CharField(max_length=300)) I have insert data successfully but when I try to query my data I got like ["['LNB Inverto', 'Dish']"]. I want to view my data on html table. My views.py are following def purchaseDetails(request,pk): invo_data = PurchaseInvoice.objects.filter(invoice=pk) return render(request,'purchase/invoice_details.html',{'invoice':invo_data}) and my html tables like {% for data in invoice %} <tr> <td >{{data.product_name}}</td> <td >{{data.price}}</td> <td >{{data.quantity}}</td></tr> {% endfor %} -
Security concerns for posting live site code on GitHub public repo
First, I am trying to get my first software engineering job and have limited "completed" projects including my resume site (built in Django). I currently self host on my a dokku home server and I want to put the code for the few sites I do have live to GitHub for sharing with potential employers. I've mostly kept my sites in private repos but with now wanting to make them public, I'm having security concerns. A few security precautions I have taken already: Change my admin login route (if posting code that route is made public) Removed all domain specific items (With resume site, that will be public) All keys for apis are in ENV files that are not shared Things I'm considering doing: At minimum migrating my sites to public hosting because I don't think I monitor my security well enough. Have 2 different repos for each site, private and public. I'd hate to do it, because of complicating things in my already complicated career change, but I could see the benefits. What are some security concerns I didn't think of or how do people keep public repos for live sites? -
OperationalError - no such table - Django Dynamic URL
I have a list like this (as return, this list returns directly.); list1 = [ {'ID': 0, 'IP': '192.168.1.1', 'Hostname': 'Hostname1', 'Ports': '23,53,80,139,443,445'}, {'ID': 1, 'IP': '192.168.1.1', 'Hostname': 'Hostname2', 'Ports': '23'}, {'ID': 2, 'IP': '192.168.1.1', 'Hostname': 'Hostname3', 'Ports': '5555,8009'}, {'ID': 3, 'IP': '192.168.1.1', 'Hostname': 'Hostname4', 'Ports': '135,139,443'} ] And I have a table like below. <tr> <th scope="col">#</th> <th scope="col">IP</th> <th scope="col">Hostname</th> <th scope="col">Ports</th> </tr> {% for i in searchin %} <tr> <td>{{i.ID}}</td> <td scope="row">{{i.IP}}</td> <td scope="row">{{i.Hostname}}</td> <td><a href = "/ports/{{i.ID}}" class="btn btn-danger">Ports</a></td> </tr> {% endfor %} In each row, when the 'Ports' link is clicked ../ports/{{i.ID}} and I want it to go and bring the ports according to the in the first list. For example; ports/0 >>output in html>> '23,53,80,139,443,445' ports/1 >>output in html>> '23' In django, I could not set this algorithm in model and views files or forms. Thanks. -
FactoryBoy is accessing normal DB instead of TEST DB
I'm trying to create some objects in setUp method of Django test case. I use FactoryBoy that helps me with creating the objects. But it seems that FactoryBoy can't find any objects in the database. class ProductFactory(DjangoModelFactory): ... market_category = factory.fuzzy.FuzzyChoice(list(MarketplaceCategory.objects.all())) class Meta: model = Product class MyTestCase(TestCase): def setUp(self) -> None: ... self.marketplace_category = MarketplaceCategoryFactory.create() print(MarketplaceCategory.objects.first().pk) # prints 1 self.product = ProductFactory(created_by=self.user) As you can see, ProductFactory tries to populate Product.market_category by random MarketCategory object. The problem is that it seems like it does not exist even when I've created it before and made sure it is in the db (it has pk). EDIT: It chose a MarketCategory object with pk=25 but there is only one such objects in the test db with pk=1. I think it accesses Django development DB instead of testing one. The error: psycopg2.errors.ForeignKeyViolation: insert or update on table "products_product" violates foreign key constraint "products_product_market_category_id_2d634517_fk" DETAIL: Key (market_category_id)=(25) is not present in table "marketplaces_marketplacecategory". Do you have any idea why it behaves this way? It looks like the Factory is accessing the real DB instead of testdb for some reason. -
Django, user can update email and username but not Image
As in title I have a problem with updating form because everything works as I want but not an image updating feature.It sends success message but it does not change the image for the profile. views.py def profileView(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user,) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your account has been updated!') return redirect('profile-page') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form} return render(request, 'shop/profile.html', context) HTML: <div> {{ user.username }} <img src="{{ user.profile.user_image.url }}"> <a href="{% url 'delete-page' pk=user.id %}">Delete</a> <form method="POST"> {% csrf_token %} {{ p_form.as_p}} {{ u_form.username }} {{ u_form.email }} <button type="submit">Update</button> </form> </div> signals.py @receiver(post_save, sender=User) def profile_creation(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() {{ u_form.email }} <button type="submit">Update</button> </form> </div> -
In local machine, django project run on which server?
i have only query to in which server python run and django run please help , on which server Django run locally? gunicorn and uwsgi is same? -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8c in position 119485: invalid start byte (while migrating sqlite3 to postgreSQL - djangocms)
I have been trying to migrate the database of my djangocms project from the default sqlite3 to postgreSQL. But at the end of the process I got this error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8c in position 119485: invalid start byte. I am not sure how to handle this issue as I have no experience in databases and most posts about this type of issues on the internet are not database-related from what I have seen. What I did to reach this point: I have created a local djangocms website with sqlite. To make the database migration, I have followed the procedure described here: I dumped the database into a db.json file then created the new postgres database on pgAdmin. I modified the field DATABASES in my django settings.py, installed psycopg2 and ran python manage.py makemigrations and python manage.py migrate and then (in the Python shell) I ran: from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() before python manage.py loaddata db.json. I also had to re-create a superuser which helped me to log into djangocms admin. But as expected my website was absent (and even the layout of djangocms was wrong). Any help would be much appreciated! Many thanks. Here are the … -
how do i display another website data in django template
**urls.py** urlpatterns = [ path('',views.index,name='index'), ] **views.py** def index(request): return render(request,"index.html") template.html my template has 1)input box 2)search button 3)bootstrap card when i enter any url and hit search button, the website data should appear in the card <input type="text" value=""> <button type="button">Search</button> <div class="row"> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Search results will appear here</h5> </div> </div> </div> </div> -
Django - Custom Join's F('') includes single quotes in column reference, causing Postgres to think it's string and not a column reference
I've created a custom join that allows a queryset to join onto a custom Postgres function. The parameters for this function require an outer ref to the overall query to be passed as part of the parameter list. When Django does this for an F(''), it includes single quotes around the double quotes such that postgres believe's the parameter is a string, not a reference to the outer alias. Custom Join: def join_to_function(table, function_model, table_field, function_field, queryset, alias, table_function_params): foreign_object = ForeignObject(to=function_model, on_delete=DO_NOTHING, from_fields=[None], to_fields=[None], rel=None) foreign_object.opts = Options(table._meta) foreign_object.opts.model = table foreign_object.get_joining_columns = lambda: ((table_field, function_field),) # table._meta.db_table is passed twice, once as the base table name, and once as the parent alias join = TableToFunctionJoin( table._meta.db_table, table._meta.db_table, alias, "LEFT JOIN", foreign_object, True, table_function_params=table_function_params, queryset=queryset) queryset.query.join(join) # hook for set alias join.table_alias = alias queryset.query.external_aliases[alias] = alias return queryset class TableToFunctionJoin(Join): def __init__(self, table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation=None, table_function_params=None, queryset=None): super().__init__(table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation) self.table_function_params = table_function_params self.queryset = queryset def as_sql(self, compiler, connection): # Sets up the on clause '{join_info} on lhs = rhs' # lhs / rhs come from a tuple of joinable columns for (lhs_col, rhs_col) in self.join_cols: on_clause_sql = '{}.{} … -
How to filter distinct objects in a many-to-many relationship in Django?
I have a page where I show all workout plans from each user. But I want to show only one entry per user, so then I can click and get all workouts plans of that user. So, instead of showing: User 1 - Day 1 USer 1 - Day 2 User 2 - Day 1 USer 2 - Day 2 I want to show: User 1 User 2 I was using the following view: planos = Workout.objects.all() But this would show everything, so I tried: plan = Workout.objects.values('member').distinct() But this returns {'member': 1} and {'member': 2}. How can I access the name of the user? class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) socio = models.CharField(max_length=6) address = models.CharField(max_length=200) city = models.CharField(max_length=200) class Exercise(models.Model): exercise = models.CharField(max_length=166) series = models.CharField(max_length=2) reps = models.CharField(max_length=2) maquina = models.ForeignKey(Maquina) class Workout(models.Model): member = models.ForeignKey(Membro) day = models.CharField(max_length=1) exercises = models.ManyToManyField(Exercise) -
Python Social Auth with Instagram Basic Display API
I'm developing an app that lets users see their own social media data. I'm using python-social-auth with Django and it works great with twitter and facebook. However, I'm having some trouble getting it working with instagram. The 'authorize with Instagram link' takes the user to the following URL: https://www.instagram.com/oauth/authorize?client_id=******&redirect_uri=https://example.com:8000/social-auth/complete/instagram/?redirect_state=******&state=******&response_type=code&scope=user_profile+user_media The user clicks 'allow', at which point python-social-auth produces the following URL and raises an exception: https://example.com:8000/social-auth/complete/instagram/?code=******#_ social_core.exceptions.AuthCanceled: Authentication process canceled I found the reponse object and call response.text to get this output: {"error_type": "OAuthException", "code": 400, "error_message": "Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request"}' I've checked the redirect uri is the same in the Instagram basic display settings. https://example.com:8000/social-auth/complete/instagram/ Any suggestions very welcome! Thanks Lloyd -
x and y must have same first dimension, but have shapes (3000,) and (1,)
I have the code to plot functions with django and when entering a function by keyboard I get the error mentioned above. How the code should work is that when a user enters a mathematical function by keyboard it graphs it for me. Function import numpy as np import matplotlib.pyplot as plt, mpld3 def Graficador(request): x = symbols('x') t = np.arange(-10.0, 20.0, 0.010) s = (request.POST['funcion']) s = parse_expr(s) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='tiempo (s)', ylabel='voltaje (mV)') ax.grid() g = mpld3.fig_to_html(fig) fig.savefig("test.png") context = {'g': g} return render(request, 'Graficar.html', context) The error appears when I wrap it in the plot, i.e. in the line "ax.plot(t,s)" the x and y error appears. HTML <div class="news_posts"> <center> <form class="form" action="/GraficarSolucion/" method="POST"> {% csrf_token %} <div class="camposLogin"> <input type="text" placeholder= "Ingrese una función" id="id_username" class="form-control" name="funcion" required> </div> <input class="btn" type="submit" value="Calcular"> </form> {% autoescape off %} <div>{{ g }}</div> {% endautoescape %} </center> </div> </div> URLS path('graficas/', views.vistaGraficador, name='graficas'), path('GraficarSolucion/',views.Graficador, name='GraficarSolucion'), -
get() got an unexpected keyword argument 'title'
i want to fetch a blog with a model field which is unique and but when i click on a perticular blog it throw me above mentioned error here is my views class Blogs(View): def get(self, request): blog_list = Blog.objects.order_by('-joined_date') return render(request, 'blogs.html',{'blog_list':blog_list}) class ReadBlogs(View): def get(self, request, url_title): blog = Blog.objects.filter(title=url_title) return render(request,'blogs_read.html',{'blog':blog}) my model class Blog(models.Model): title = models.CharField(max_length=48, blank=False) urltitle = models.SlugField(max_length=48, blank=False, unique=True) title_image = models.ImageField(upload_to='blog',blank=True, null=True) subone = models.CharField(max_length=80, blank=False) subone_image = models.ImageField(upload_to='blog',blank=True,null=True) onedes = models.TextField(blank=False) my html for fetching right blog <div class="blogs"> {% for blogs in blog_list %} <a class="products" href="{% url 'blogs:readblog' title=blogs.urltitle %}"> <div class="blog col-4" style="width: 18rem; height:350px"> <img class="img" src="{{ blogs.title_image.url }}" alt="" height="250px" width="100%"> <div class="detail"> <h4 class="title text-center" style="color: #025; font-family:cursive;">{{blogs.title}}</h4> </div> </div> </a> {% endfor %} </div> my url.py urlpatterns = [ path('blogs/',Blogs.as_view(),name="Blogs"), path('<slug:title>/',ReadBlogs.as_view(),name="readblog") ] as you can see mu urltitle is unique slug field so but when i clicked on a particular blog i got above mentioned error any idea what causing error -
Django Rest Framework : Why Complex nested serializer tries to create nested fields in database when calling .is_valid()?
Context I have a project in which there are three entities : Account, Community and JoinRequest. A JoinRequest binds an Account (user) with a Community. And there should not be more than one JoinRequest for any couple (Account, Community). Problem I coded the respective models, serializers and unittest, which you can see below. But when I run my test, I get the following error... I don't understand, it seems the .is_valid() method of the JoinRequestSerializer tries to recreate an Account and a Community, whose data were previously passed as arguments at construction of the instance... Any idea why this error appears? join_request_serializer.errors {'user': {'email': [ErrorDetail(string='account with this email already exists.', code='unique')], 'username': [ErrorDetail(string='account with this username already exists.', code='unique')], 'password': [ErrorDetail(string='This field is required.', code='required')]}, 'community': {'name': [ErrorDetail(string='community with this name already exists.', code='unique')]}} Account class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): # This method must be overridden to use MyAccountManager class user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser … -
The source code of the code pen is not applied
I've tried pasting the code copied from the code pen site below in the vault, but it doesn't work. I wonder why it's not working. What do I have to do to make it work? The CSS source code was imported using Viw compiled. Does this matter? Code Pen Address https://codepen.io/dodozhang21/pen/vNOmrv Paste Source Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <style> @import url(https://fonts.googleapis.com/css?family=Nunito); @import url(//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css); *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } html { height: 100%; } body { background: #ffd16e; height: 100%; padding: 0; margin: 0; font-size: 16px; display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; } .uploadWrapper { font-family: "Nunito", sans-serif; } .imageUploadForm { background: #6e95f7; height: 400px; width: 500px; position: relative; display: -webkit-flex; display: flex; -webkit-align-items: flex-end; align-items: flex-end; -webkit-justify-content: center; justify-content: center; -webkit-flex-wrap: wrap; flex-wrap: wrap; } .imageUploadForm .helpText { color: white; display: block; position: absolute; top: 2%; left: 0; width: 100%; height: 100%; text-align: center; font-size: 30px; } .imageUploadForm .helpText:after { content: "\f067"; font-family: "FontAwesome"; font-size: 150%; color: rgba(255, 255, 255, 0.5); display: -webkit-flex; display: flex; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; margin: 4% auto auto auto; width: 50%; height: 50%; border: … -
Unable to migrate in django
model.py class Staff(models.Model): organization = models.ForeignKey( Organization, related_name='staff_organization', on_delete=models.CASCADE, blank=True) user = models.OneToOneField( User, on_delete=models.CASCADE, blank=True) phone = models.CharField(max_length=15, blank=True) address = models.CharField(max_length=200, blank=True) I am trying to add the new field in the database table. II just added the address field. I got following error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Project\AIT Project\project\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\base\schema.py", line 142, in execute cursor.execute(sql, params) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\Project\AIT Project\project\venv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user_email_1c89df09_uniq" already exists -
How to develop webapps for manage other webapps as plugin
Is it possible to develop a web application that will dynamically connect and manage other web applications. These applications must be on the same domain name, with different prefixes. Is it possible on python? If so, tell me /mange/ app1 #url_prefix=/app1 | ***files app1*** app2 #url_prefix=/app2 | ***files app2*** run.py -
django - ValueError: Dependency on app with no migrations
I'm deploying my Django project to a VPS using Dokku. My project uses a CustomUser model, and there are two apps in the project: accounts which has the CustomUser and gradebook. During deployment the process runs makemigrations and migrate. After deployment when I run python manage.py showmigrations I get the following: account [X] 0001_initial [X] 0002_email_max_length accounts (no migrations) admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name gradebook (no migrations) sessions [X] 0001_initial sites [X] 0001_initial [X] 0002_alter_domain_unique Where account is from django-allauth. It looks like my apps are not being migrated. So I then do: me@myserver:/home$ dokku run gradebook python manage.py makemigrations accounts success Migrations for 'accounts': accounts/migrations/0001_initial.py - Create model CustomUser me@myserver:/home$ And it looks like things are ready migrate. I then run migrate and get an error django - ValueError: Dependency on app with no migrations: accounts: shmish@Henry:/home$ dokku run gradebook python manage.py migrate accounts success Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/loader.py", line 174, in check_key return self.graph.root_nodes(key[0])[0] IndexError: list index out of range During handling of … -
What will be the best approach for setting up multiple subdomains in a single django project using mysql?
I am about to build a web-app and use it as a product for multiple organizations. Let's say my domain name is example.com And I have 2 customers, org1 (Organization 1) and org2 (Organization 2) So, my sub domains would be org1.example.com and org2.example.com Now, I have gone through the Django tenant approach which uses PostgreSQL. But I am looking for something in MySQL. But my question is that is it possible for me to use MySQL and use separate databases, to maintain risk free and also data privacy for orgs, and also use Django tenant or is there some different approach to solve this subdomain issue? Do note, I'll be using my platform as a product so the subdomains would be given to each client who would be given credentials to access the platform (Kinda like an inventory system). Any links or videos is highly appreciated. -
Display objects related to requested object and children in Materialized Path trees
categories/models.py from django.db import models from treebeard.mp_tree import MP_Node class Category(MP_Node): title = models.CharField(max_length=50) slug = models.SlugField(unique=True) node_order_by = ['title'] class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return 'Category: {}'.format(self.title) categories/views.py from django.views.generic import DetailView from .models import Category class CategoryDetailView(DetailView): model = Category context_object_name = 'category' template_name = 'categories/category_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["products_in_category"] = self.object.products.filter(active=True) return context category_detail.html ..... {% for p in products_in_category %} <h2><a href="{{ p.get_absolute_url }}">{{ p.title }}</a></h2> ..... The code above works well to display products that belong to a specific category but I would also be able to display the products that belong to its descendants. Example: shoes ├── sneakers │ ├── laced sneakers │ └── non-laced sneakers If I'm on the category page for sneakers I would want to be able to see products related to both Laced Sneakers and Non-laced Sneakers. My thought was that the get_context_data could look something like this def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["products_in_category"] = self.object.get_descendants().products.filter(active=True) return context But unfortunately, that did not work out. I was thinking about using ListView instead but the category page will have a description describing the category and for that reason, I figure DetailView would … -
Sorting a JSONField by adding an index value?
I am using a JSONField to store a custom form with field labels/values. I am having an issue when rendering the form. Each time the form gets rendered, the order is changed since I am using a dictionary. I was thinking of adding an extra value to my JSONField just to store an integer, in which I can order by. I am wondering if this is a possible solution, or if there was any other "best" way to keep this form in order. I have a simple model, class House(models.Model): form = JSONField(default=dict) Which in my view a json file is loaded into it with a json file as such. { "outside": [ { "fields": [ { "label": "Pool", "value": "" }, { "label": "Shed", "value": "" }, ], "index": 0 } ], "inside": [ { "fields": [ { "label": "Bedrooms", "value": "" }, { "label": "Baths", "value": "" }, ], "index": 1 } ], When the form is rendered in my view, I am using basic logic house = House.objects.get(id=1) form = house.form.items() return render(request, template, context={'form': form} The json loads fine the first time, with all fields with the label outside leading, and then fields with the label …