Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Как правильно реализовать ajax рендер модели в Django? [closed]
Есть страница с мероприятиями и некоторое количество фильтров, хочется сделать фильтрацию без перезагрузки страницы. Только учусь и задумался над тем правильно ли я собираюсь делать реализацию AJAX в CMS Wagtail а Django. Как я понял рендер делается не силами шаблона а уже javascript. Мой план 1. Делаю view возвращающую json 2. Обрабатываю JSON и генерирую HTML 3. Profit Вопрос в том что мне кажется что можно рендер сделать силами шаблона django. Просьба описать правильный workflow в этом случае и на что обратить внимание -
Django - upload_to dynamic path from different models
I'm trying to use ImageField upload_to to save the image in organize manner, but I cannot figure out if this is possible or how to. I'm trying to have this folder hierarchy inside media: Book-title Chapter 1 img1 img2 Chapter 2 img1 Models: class Book(models.Model): title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) author = models.ManyToManyField(Author) chapter = models.ManyToManyField(Chapter, related_name='books') def image_dir_path(instance, filename): chapter = instance.slug return os.path.join(chapter, filename) class Chapter(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=130, unique=True) slug = models.SlugField(max_length=150, unique=True, blank=True) picture = models.ImageField(upload_to=image_dir_path) created_at = models.DateField(auto_now_add=True) I'd like to have something like this, so I can use the book title to build the path: def image_dir_path(instance, filename): book = instance.book.slug chapter = instance.slug return os.path.join(book, chapter, filename) This do not work, instance it's only related to the class where you call image_dir_path. It's something similar possible? -
Django rest framework, serializer serializer method field doesn't save changes to db?
I have a DRF API which contains a field that's being set in the serializer: class KnownLocation(models.Model): latitude = models.FloatField(name="Latitude", verbose_name='Latitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", ) longitude = models.FloatField(name="Longitude", verbose_name="Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", ) elevation = models.FloatField(name="elevation", help_text="Enter the location's ~Sea Level~ elevation, or Leave empty for auto-fill " "by me :). ", verbose_name="Elevation in meters", blank=True, default=DEFAULT_VALUE ) And the serializer: class KnownLocationSerializer(HyperlinkedModelSerializer): date_added = DateTimeField(format="%d-%m-%Y", required=False, read_only=True) elevation = SerializerMethodField() def validate_elevation(self, value): """ Validate that elevation of location has been updated already. """ if value is None or 1: raise APIException.elevation.throw() return value def get_elevation(self, obj): """ This method, which is connected to SerializerMethodField, checks if the object's elevation value exists, if not, it fetches it. """ elevation = obj.elevation if elevation is None or 1: elevation = get_elevation(lat=obj.Latitude, lon=obj.Longitude) elevation = round(elevation) return elevation pass The method works and fetches the elevation, yet, it doesn't save it to the DB. did I miss that part in the docs? so, how can I save it to the DB, using save didn't work for me: def save(self, **kwargs): latitude, … -
Django User-Interests App and its database Model design
I'm am building a django app which takes user Interests as inputs. Now I have 2 Questions - First is that, what model should I use, should I just add a field to user model or a separate Interest Model and link via Foreign Key? I know the former design is bad, and so I.m trying latter one, I'm having a hard time in Django to create Interest Model and its view to save the user interests. Any help is appreciated. -
Django Rest Framework: @Action Route with same url_path as Viewset
I want to POST to a DRF Viewset Detail Route. is this possible? I know with DRF you can override the Create field, but this won't allow you to access the detail route. Here's what I want to accomplish, notice the IS_THERE_A_WAY_TO_DO_THIS: class FooViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): """ Foo-related viewsets. """ permission_classes = [IsAuthenticated] queryset = models.Foo.objects.all() serializer_class = serializers.FooSerializer @action( methods=["post"], detail=True, permission_classes=[IsAuthenticated], url_path="", <-- IS_THERE_A_WAY_TO_DO_THIS? Normally this wont work. url_name="foobar", ) def foobar_process(self, request, pk=None): pass -
Django + Bokeh: How to pass (a large set of) model objects to bokeh server app?
I'm new to both Bokeh and Django, so bear with me please. I have a bokeh app written and rendering through Django (I am able to navigate to the website, and pull up my bokeh app, which right now reads from a local CSV to render plots). I have since set up models in Django, and a table holds the same data as the CSV. Based on the URL that a user of the (future) Django website navigates to, I can filter out the QuerySet (objects of interest) from the database (sqllite), but now I'm stuck. How do I pass it to the bokeh app? I do not want to read from a csv. Here are the options I've come up with Include it in the request arguements: I can't do this (see bigreddot's comment here), my set of objects is large (i.e. I can covert it to a dataframe, and then to a string, but again, too large. script = server_document(url=request.build_absolute_uri(), arguments={'data_input': df') I can try to read from the sqllite database/Django ORM within the app, but this seems like overkill. I literally need to read the data once, when the page is first loaded. No updates to the … -
After a comment is posted and I try to like it, ajax lags and doesn't work immediately
I have a comment liking system in a Django website I'm building, where when a comment is liked, an ajax function is called. However, I've found that right after I post a comment, and try to like my own comment, the request.is_ajax() == FALSE instead of TRUE like it normally is. After a few minutes, and I reload it, the like button works fine. Is there an explanation for this, or has anyone encountered something similar? What was your solution? I'll put my code underneath in case it's relevant, but it's strange to me because it normally works well, it's only when I try to like a comment I just posted that it glitches out. AJAX: $('#comment-form').submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response) { $('.comments-section').html(response['form']); $('.reply-link').click(function(event){ event.preventDefault(); $(this).parents('.parent-comment').next('.replies').fadeToggle(); }) $('textarea').val(''); console.log('work') }, error: function(rs, e) {console.log(rs.responseText)} }) }) VIEWS.PY: @never_cache @login_required(login_url='login') def change_comment_like(request, pk): comment = Comment.objects.get(pk=pk) print(comment) print(request.method) print(request.is_ajax()) if request.method=='POST' and request.is_ajax(): print('work') user = request.user liked = False if user in comment.likes.all(): comment.likes.remove(user) else: comment.likes.add(user) liked = True comment.save() print(comment) return JsonResponse({'liked': liked}) return redirect('post_detail', pk=comment.post.pk) -
django rest framework serializer field validation when creating and updating instance
I have a Django application which I create a new instance or update an existing one in same view function. If instance_id is not give, so I create object, else I update data of existing object using instance_id. My views.py file is: def insert_update_country(request): country_serializer = serializers.Country(data=request.data) if country_serializer.is_valid(): country_id = country_serializer.validated_data.get('country_id', None) country_name = country_serializer.validated_data.get('country_name', None) country_code = country_serializer.validated_data.get('country_code', None) country, is_created = models.Country.objects.update_or_create( id=country_id, defaults={ 'country_name': country_name, 'country_code': country_code, } ) return Response( { 'Message':_('CHANGES_HAVE_BEEN_SAVED_TO_DATABASE'), 'Succeed': True }, status=status.HTTP_200_OK ) else: return Response( { 'Message': country_serializer.errors, 'Succeed': False }, status=status.HTTP_400_BAD_REQUEST ) The problem is even if I am doing an update on an existing instance, the serializer throw error as some fields must be unique. In my example when updating a country_name due to a typo, it says an instance with this country_code exists. The reason I have found in similar questions is: Django REST Framework (DRF) expects a POST request to only create new instances. I don't want to change my request method, it should be POST. How can I change my serializer to say if country_id is None, means I am creating new instance, so do the unique validation. Otherwise if country_id is not Node, means … -
How can i get image of Profile model, in my Post model
Here is two model Profile and Post. How can i get image from Profile model in my Post model? -
Add row dynamically in django formset
In my django app I have two models i.e Player and Team which are connected by many to many relatioship. To add the data dynamically in my tables I want to use javascript to add Add row or Remove Row button in my forms but unable to do so. Here are the details: Models.py class Player(models.Model): pname = models.CharField(max_length=50) hscore = models.IntegerField() age = models.IntegerField() def __str__(self): return self.pname class Team(models.Model): tname = models.CharField(max_length=100) player= models.ManyToManyField(Player) def __str__(self): return self.tname Forms.py class PlayerForm(forms.Form): pname = forms.CharField() hscore= forms.IntegerField() age = forms.IntegerField() PlayerFormset= formset_factory(PlayerForm) class TeamForm(forms.Form): tname= forms.CharField() player= PlayerFormset() Views.py def post(request): if request.POST: form = TeamForm(request.POST) form.player_instances = PlayerFormset(request.POST) if form.is_valid(): team= Team() team.tname= form.cleaned_data['tname'] team.save() if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() else: form = TeamForm() return render(request, 'new.html', {'form':form}) new.html <html> <head> <title>gffdfdf</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="/static/jquery.formset.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form id="myForm" action="" method="post" class=""> {% csrf_token %} <h2> Team</h2> {% for field in form %} {{ field.errors }} {{ field.label_tag }} : {{ field }} {% endfor %} {{ form.player.management_form }} <h3> … -
Copy many-to-many entries for new element
Django beginner here. I want to create a new row in a table and copy the references many-to-many entries from another row. I have the following models (simplified): class Missions(models.Model): player = models.ForeignKey(Players, null=True, on_delete=models.CASCADE) units = models.ManyToManyField( Units, through='MissionUnits' ) class MissionUnits(models.Model): mission = models.ForeignKey(Missions, models.CASCADE) unit = models.ForeignKey(Units, models.CASCADE) count = models.PositiveIntegerField() class Meta: constraints = [ models.UniqueConstraint(fields=['unit', 'mission'], name='unique_mission_units') ] as well as two tables where unit player are defined. So what I want to do is the following: I have an existing "Missions" entry with associated "MissionUnits" entries. I want to create a new "Missions" entry with the same "MissionUnits" as the old one The new entries should persist even if I delete the old "Missions" entry Of course I could select all the "MissionUnits" entries, and extract and copy the information in a for loop, but is there also a more direct and elegant way to do this? If I just assign the oldmission.units to newmission.units, will this copy the elements? -
Get Minimum value of Each Query in Filter
I have two tables 1 product and 2nd price.like this class Activity(models.Model): activityName = models.CharField(max_length=50 , null=False, blank=False) activityId = models.CharField(max_length=20, null=True, blank=True) class PerPersonTire(models.Model): activity = models.ForeignKey(Activity, on_delete=models.CASCADE) name= models.CharField(max_length=100 , null=True , blank=True) minNumerofParticipents = models.IntegerField(default=0) price=models.IntegerField(default=0) Now case is in every activity have many price in foreign key. So when I Query on Activity I need minimum price from that table aswell. like Activity.object.all() I need here minimum price of each activity from price table as well. Any help regarding this would be highly appreciated. -
Django enctype=multipart/form-data on localhost returns white screen
I am running django on a pipenv virtual machine on my MacBook on localhost:8000. I created a django form to upload an image with enctype=multipart/form-data. When clicking on submit, on all browsers, I get a white page. Checking the browsers network status, its a 400 error, and in Firefox I get: The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature. When removing the enctype, everything works fine - but of course the image isn't uploaded. The error seems to occur before any data manipulation on my side. On a remote development server, everything works fine with and without encoding - so it seems to be related to my development environment. Unfortunately I can't find any hints on why this error occurs. Does anybody have a hint or an idea on how to solve this? More Information Macbook Pro Catalina 10.15.3 Django 2.2 Running with the django internal server (manage.py runserver) -
Django Polls App Part 3 Template Syntax Error
I am new to Django and going through the tutorial of polls app. I am stuck on part 3 with Template syntax error. I have searched all related posts on stackoverflow but can not find the problem. Below are my files: Polls/Views.py: from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) Polls/models.py: from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Polls/templates/polls/index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} polls/urls.py: from … -
product weight in ebaysdk
how can i can get product weight ? I used trading api but most of weight of the products equal to 0. is there any way to get product weight all the time? I requested like this: response = api_trading.execute('GetItem' , {"ItemID":"184097524395",'DestinationPostalCode':'2940','DestinationCountryCode':'GB'}) -
Django: Unable to Write File from ModelForm on Apache and Mod_wsgi
I have a Django 3.0.3 site running on RHEL 7 and Apache using mod_wsgi. On my development machine (Windows) I am able to save a file via a FileField field type. However, when deploying on production (RHEL 7 and Apache using mod_wsgi) I get an "[ErrNo 13] Permission denied" error when trying to save the file. I have set folder permissions to drwxrwxrwx. for the MEDIA_ROOT folder for the apache user which is named "apache" in my instance (as confirmed by both calling getpass.getuser() within the program and also from the httpd conf settings. It is also the name listed on mod_wsgi.process_group on the Django debug page. I have included my relevant code and debug: Debug Environment: Request Method: POST Request URL: https://www.samplesite.com/samples/addpatient/ Django Version: 3.0.3 Python Version: 3.7.1 Installed Applications: ['samples.apps.SamplesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'bootstrap3', 'django.contrib.staticfiles', 'notifications'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch … -
Run Django server at Single Host IP address
I am trying to restrict Django server to single Host IP in Local PC. Initially I am running Django server at Host IP lets say 127.0.0.1. Again I am starting server at different Host IP 127.0.0.2 (in same PC) than mentioned in step1. Now I am able to browse my website at both IPs. But I need server should be working at last given host IP i.e 127.0.0.2 and old IP address shouldn't give response to any requests from 127.0.0.1 IP. IP address I have given here is just sample IPs. Note: I will not be restarting the server. -
How does the functionality of a function in has_object_permission differs when both return same Boolean value?
Recently I started to learn about permissions in Django rest framework, and I find below code a bit confusing. class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user I know that has_object_permission is linked to a specific instance and is called from get_object, but I don't know how it works under the hood. I mean if the condition is met, both returns True, but first one is ready-only and second one is update and delete. What puzzled me though is how one gives read-only access and second gives write and delete access under ceiling of same function? Please help me understand this. Thank you. -
Weird behavior in django __date filter
I'm trying to filter the model by date. class Participant(models.Model): email = models.CharField(unique=True, max_length=255) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email There are 4 entries that were created at date(2020, 3, 28): 2020-03-28 06:28:14.475307+00:00 2020-03-28 06:16:05.312023+00:00 2020-03-28 06:11:27.322146+00:00 2020-03-28 06:03:27.500164+00:00 When I'm doing this: Participant.objects.filter(created_at__gte=datetime.date(2020, 3, 28), created_at__lt=datetime.date(2020, 3, 29)) I'm getting these 4 entries. But, when I'm doing this: Participant.objects.filter(created_at__date=datetime.date(2020, 3, 28)) I'm getting an empty queryset. I have: TIME_ZONE = "UTC" USE_TZ = True I'm in timezone Asia/Kolkata I'm using django version 2.2, Mysql, python version 3.6.7 I have seen this answer: https://stackoverflow.com/a/55608903/5157204 but I'm unable to figure out what the problem is. Can anyone help me figure out the problem? -
Calculate book value of share positions in Django
I'm working on a small project where I want to show a summary of accounts in cash and shares. There is some Python code involved and I want to present the output in a template. I'm trying to calculate the book value of each position of the share portfolio however I’m getting an error and I don’t know what to do. Your help would be much appreciated. model.py class Shares(models.Model): name = models.CharField(max_length=128) ticker = models.CharField(max_length=128) date = models.DateField() quantity = models.FloatField(default=0) price = models.FloatField(default=0) currency = models.CharField(max_length=128) view.py class SharesListView(ListView): model = Shares context_object_name = 'shares_details' def get_context_data(self, **kwargs): context = super(SharesListView, self).get_context_data(**kwargs) latest_fx = fx_table.objects.last() queryset = context['shares_details'].annotate(book_value=Case( When(Q(quantity >0, then=F('price')*('quantity'))), default=Value(0), output_field=FloatField() ) ) context['shares_details'] = queryset context['total_shares'] = queryset.aggregate(sum=Sum('book_value'))['sum'] return context Error details Exception Type:NameError Exception Value:name 'quantity' is not defined Exception Location:...views.py in get_context_data, line 58 Thanks -
Django bootstrap modal not showing
I am trying to show a modal on a button click, however, after I click on the modal it does not show the modal, I do not know what seems to be the issue since I followed the exact tutorial on bootstrap and W3Schools. Here, is my template: {% for comment in comments %} <div class="border-bottom"> <div class="row pt-1 pl-4"> <div class="col-xs"> <img class="img-create-post rounded-circle mr-1" style="width: 2.1rem;height: 2.1rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> </div> <div class="col-xs" style="margin-bottom: 0;"> <span class="text-dark font-size-smaller" href="#" style="font-weight: 500;">{{ comment.name.first_name }}</span> <span class="text-muted small">•</span> <a class="text-muted small" href="#">@{{ comment.name.username }}</a> <span class="text-muted small">•</span> <span class="text-muted small">{{ comment.get_created_on }}</span> <p class="font-weight-light pl-1">{{ comment.body }}</p> </div> </div> <div class="d-flex justify-content-between"> <div> <span class="text-muted small view-replies">view {{ comment.replies.count }} replies <i class="fas fa-caret-down"></i></span> </div> <div> <!-- button to show modal --> <button class="btn btn-sm small float-right text-muted button-outline-light reply-btn" type="button" data-toggle="modal" data-target="modal-comment-reply">Reply</button> </div> </div> <div class="comment-replies"> {% for reply in comment.replies.all %} <div class="row pt-1 pl-4"> <div class="col-xs"> <img class="img-create-post rounded-circle mr-1" style="width: 2.1rem;height: 2.1rem;" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> </div> <div class="col-xs" style="margin-bottom: 0;"> <span class="text-dark font-size-smaller" href="#" style="font-weight: 500;">{{ comment.name.first_name }}</span> <span class="text-muted small">•</span> <a class="text-muted small" href="#">@{{ comment.name.username }}</a> <span class="text-muted small">•</span> <span class="text-muted small">{{ comment.get_created_on }}</span> <p … -
How can I pull data from my database using the Django ORM that annotates values for each day?
I have a Django app that is attached to a MySQL database. The database is full of records - several million of them. My models look like this: class LAN(models.Model): ... class Record(models.Model): start_time = models.DateTimeField(...) end_time = models.DateTimeField(...) ip_address = models.CharField(...) LAN = models.ForeignKey(LAN, related_name="records", ...) bytes_downloaded = models.BigIntegerField(...) bytes_uploaded = models.BigIntegerField(...) Each record reflects a window of time, and shows if a particular IP address on particular LAN did any downloading or uploading during that window. What I need to know is this: Given a beginning date, and end date, give me a table of which DAYS a particular LAN had ANY activity (has any records) Ex: Between Jan 1 and Jan 31, tell me which DAYS LAN A had ANY records on them Assume that once in a while, a LAN will shut down for days at a time and have no records or any activity on those days. My Solution: I can do this the slow way by attaching some methods to my LAN model: class LAN(models.Model): ... # Returns True if there are records for the current LAN between 2 given dates # Returns False otherwise def online(self, start, end): criterion1 = Q(start_time__lt=end) criterion2 = … -
Sprinkling VueJs components into Django templates
I'm working on a Django site and I'm looking to "sprinkle" in some Vue components to the Django rendered templates. I'm working in a single repository and have webpack setup to create style/js bundles that I use within the Django templates. I'm struggling to get the functionality working how I'd like it, mainly regarding renderless Vue components, since I want to handle all (or at least the vast majority) of html within the Django templates and just use Vue components for some logic in some places. I'm using some of the advice from here but it didn't quite work as they'd suggested (although that's exactly how i'm hoping it can work) and I feel like I need to take advantage of scoped-slots. I am using the Vue esm distribution to include the Vue compiler. The setup I'm currently using is as follows: // webpack_entrypoint.js import Vue from "vue"; import RenderlessComponent from "./components/RenderlessComponent.vue" // I will also be registering additional components here in future for other pages // and I'm under the impression that doing it this way allows me to reuse the Vue instance // defined below Vue.component("renderless-component", RenderlessComponent) new Vue({ el: "#app" }) // components/RenderlessComponent.vue <template></template> <script> // Other … -
How to store attachement files(image) to remote location?
I am using django-summernote, now i want to change upload location to remote(Another hosting platform) , Please anyone help me. Thanks in advance. -
How to access django tenant_schemas Tenant URL in browser
Good day! I am using django tenant_schemas (https://django-tenant-schemas.readthedocs.io/en/latest/) to develop a SaaS web application. I have created a Tenant with a domain_url but I cannot access it through a web browser. Here is some parts of my settings.py: ALLOWED_HOSTS = ['*'] SHARED_APPS = ( 'tenant_schemas', 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps # Third Party Apps 'corsheaders', 'rest_framework', 'dynamic_preferences', # For Pref # 'api.apps.ApiConfig', 'revproxy', # For Reports 'tenant_schemas', #'taggit', 'taggit_serializer' # For tags - might not use with Vue..) TENANT_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',) INSTALLED_APPS = ( 'tenant_schemas', 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom Apps # Third Party Apps 'corsheaders', 'rest_framework', 'dynamic_preferences', # For Pref 'api.apps.ApiConfig', 'revproxy', # For Reports #'taggit', 'taggit_serializer' # For tags - might not use with Vue.. ) DEFAULT_FILE_STORAGE = 'tenant_schemas.storage.TenantFileSystemStorage' MIDDLEWARE_CLASSES = ( 'tenant_schemas.middleware.TenantMiddleware', # ...) DATABASE_ROUTERS = ( 'tenant_schemas.routers.TenantSyncRouter', ) TENANT_MODEL = "tenant_public.Tenant" # app.Model Created Tenant using python manage.py shell: tenant = Tenant(domain_url='tenant.demo.com', schema_name='tenant1', name='My First Tenant') Save: tenant.save() However, when I run python manage.py runserver and access tenant.demo.com, I get a 404 Not Found response.