Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"No module named 'django_heroku' " app won't start on Heroku
Trying to push to the heroku server, I get this: git push heroku master remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.7.3 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing requirements with pip remote: remote: -----> Downloading NLTK corpora… remote: ! 'nltk.txt' not found, not downloading any corpora remote: ! Learn more: https://devcenter.heroku.com/articles/python-nltk remote: -----> Discovering process types remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: Done: 206.4M remote: -----> Launching... remote: Released v10 remote: https://versally.herokuapp.com/ deployed to Heroku However, when I go to my app, it tells me there's an error. When I check in on the logs, I see this: 2019-04-30T13:22:00.633794+00:00 app[web.1]: import django_heroku 2019-04-30T13:22:00.633801+00:00 app[web.1]: ModuleNotFoundError: No module named 'django_heroku' 2019-04-30T13:22:00.634020+00:00 app[web.1]: [2019-04-30 13:22:00 +0000] [11] [INFO] Worker exiting (pid: 11) 2019-04-30T13:22:00.789044+00:00 app[web.1]: [2019-04-30 13:22:00 +0000] [4] [INFO] Shutting down: Master I'm yet to setup the database, but I'm just looking to get a debug message from the django code so I can start with configuration of the database. -
Django REST framework serializer for custom form data
I've started learning how to use the Django REST Framework along with React and I have a quick question. I made a form and use CreateAPIView and UpdateAPIView to create/update items, respectively. But how do I get the contents to populate my <select> field if the list comes from a variable in one of my models? from model_utils import Choices class Author(models.Model): GENDER = Choices('male', 'female', "I don't know really") # How do I get this? gender = models.CharField(max_length=10, choices=GENDER) What will the serializer and views for Author.GENDER look like since it's not a model? At the moment, this is what I have for now. Django (nothing out of the ordinary here, I think.). # Serializer. class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'gender') # View class AuthorUpdateView(UpdateAPIView): queryset = Author.objects.filter(deleted_at__isnull=True) serializer_class = AuthorSerializer React. componentDidMount() { const pk = this.props.match.params.pk axios.get(`http://localhost:8000/api/authors/${pk}`) .then(response => { const pk = response.data.id const gender = response.data.gender this.setState({gender}) }) .catch(err => console.log(err)) } I'm open to any direction or concept you might have when using DRF so I can also learn from how you would do it. -
How to return the first serialized object rather than all in Django?
I have an API (using django-rest-framework) with two models (e.g. Users and Cars). I'm trying to get the user's latest (highest ID) Car also returned when the User is queried. I've tried including cars = CarSerializer(many=True), which returns all cars for that user. I've tried cars = CarSerializer(), which returns the format I want, but no cars turn up. car model class Car(models.Model): name = models.TextField(default='') year = models.IntegerField(null=True) owner = models.ForeignKey('User', related_name='cars') car serializer class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = ('id', 'name', 'year', 'owner') user serializer class UserSerializer(serializers.ModelSerializer): car = CarSerializer() class Meta: model = User fields = ('id', 'first_name', 'last_name', 'car') What I'm looking for Given two cars: id: 1 owner: 1 name: "kinda okay car" year: 2012 id: 2 owner: 1 name: "the fastest one" year: 2020 JSON Result of GET /users/1 { "id": 1, "first_name": "Bob", "last_name": "McFastCar", "car": { "name": "the fastest one", "year": 2020 } } Thanks, I wheely hope you can help drive me towards a solution. -
How to read ordereddict from json
i have a json like, d = {"id": 1, "company_car": 1, "manufacture_stage": OrderedDict([("id", 4), ("company", OrderedDict([("id", 1), ("name", "BMW"), ("icon", "http://test.com/ta/")]))]), "manufacture_car_stage_status": "Scheduled", "start_datetime": "2019-04-30 17:24:32", "end_datetime": "2019-05-30 17:54:32", "taken_datetime": None, "is_active": true, "manufacture_car_stage_detail": {"assessment_scores": None}, "is_shortlisted": false, "is_rejected": false} how can i get name which has BMW value form oderedDict? -
Django url's NoreverseMatch
I have two buttons that appointing to different paths. And i want to pass the object.id with parameter. my urls urlpatterns = [ path('', admin.site.urls, name ='home'), path('dpo/imprimir/aprovado/<int:id>/',Aprovado, name ='aprovado'), path('dpo/imprimir/reprovado/<int:id>/',Reprovado, name ='reprovado'), ] My views from django.http import HttpResponse from django.shortcuts import render from django.shortcuts import render_to_response from .models import Projeto def Aprovado(request, id): obj = Projeto.objects.get(id=id) context = { "object": obj } return render(request, "dpo/imprimir/aprovado.html", context) def Reprovado(request, id): obj = Projeto.objects.get(id=id) context = { "object": obj } return render(request, "dpo/imprimir/reprovado.html", context) ** My template** {% load i18n admin_urls %} {% block object-tools-items %} <li> <a href="{% url 'aprovado' object.id %}">{% trans "Aprovado" %}</a></a> </li> <li> <a href="{% url 'reprovado' object.id %}">{% trans "Aprovado" %}</a> </li> {% endblock %} i think i am doing this the wrong way -
get models fields after save
I have model with these fields : Now when the model is saved I wanted to show those fields in the Hospital Pack tab in the following format : How do I do this ? I am using django admin panel. -
Django Admin Deleting All Records Bad Request [400]
I'm trying to delete multiple records in Django Admin. If I select a page of 1000 rows and delete, I get Bad Request [400] error. Bad Request (400) Deleting rows individually works. This is only occurring in production. I am hesitant to turn debug to True. Model objects I am trying to delete: class Case(models.Model): caseId = models.AutoField(primary_key=True) dataCheckContactId = models.ForeignKey(DataCheckContact, on_delete=models.DO_NOTHING , related_name="dchk") caseDteProg = models.DateTimeField(null=True, blank=True) caseIntComplete = models.IntegerField(null = True, blank = True, default = 0) caseDteStart = models.DateTimeField(null=True, blank=True) caseType = models.CharField(null = True, max_length = 36, blank=True) caseInputJSON = models.TextField(null = True, blank=True) # data prior to submission caseReturnJSON = models.TextField(null = True, blank=True) #submission data caseIntStatus = models.IntegerField(null = True, blank = True, default = 0) caseBPMUuid = models.CharField(null = True, max_length = 36, blank=True) def __str__(self): return self.caseBPMUuid Is turning Debug to True to only way to see any error messages? Thanks Edit 1. Using Apache2 as web-server. Possible request size bottleneck? -
Is There A Tool To Measure Effectiveness of Django Tests [on hold]
I am trying to gain some kind of metric to show how effective our Django tests are. We have a Django app with a moderately large API surface area, a suite of tests, some of which are skipped. We are aware that there are gaps in what is tested. The Django app uses django-rest-framework and Django filters libraries. There are class based views based on DRF generic views. This means that the code is highly declarative in nature. Some of those declarations have complicated filters. We are wanting a metric to show how many of the API URL's are visited when ./manage.py tests is called. Ideally it show what filters have been applied in those views, to gain some idea of what is not exercised in test at all. The usual python tool, coverage, does not give a good metric for this as it only shows lines executed and the declarative code is always executed upon reading the declaration, despite the filters/views/columns it declares not being used at all. I have been trying to find a tool that gives API or feature visiting metrics for Django and have turned up a blank. I would be surprised if this is a … -
ImproperlyConfigured exception but it works anyway
I have following code: import django def process(): django.setup() from django.conf import settings print(settings.configured()) print(settings.SECRET_KEY) if __name__ == "__main__": process() When I try to run it with all the env variables defined with cron inside docker, I get: cron_1 | Traceback (most recent call last): cron_1 | File "process_tasks.py", line 16, in <module> cron_1 | process() cron_1 | File "process_tasks.py", line 8, in process cron_1 | django.setup() cron_1 | File "/usr/local/lib/python3.7/dist-packages/django/__init__.py", line 19, in setup cron_1 | configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) cron_1 | File "/usr/local/lib/python3.7/dist-packages/django/conf/__init__.py", line 57, in __getattr__ cron_1 | self._setup(name) cron_1 | File "/usr/local/lib/python3.7/dist-packages/django/conf/__init__.py", line 42, in _setup cron_1 | % (desc, ENVIRONMENT_VARIABLE)) cron_1 | django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. cron_1 | app.settings.dev cron_1 | True cron_1 | dev When I run it without cron, I dont get the exception. But everything seems to work fine, eventhough there is this exception. For the cronjob, I am using: * * * * * root . /root/env.sh; cd /app/; python3 process_tasks.py > /proc/1/fd/1 2>/proc/1/fd/2 In env.sh file, there are just env variables written as export VAR=VALUE list. So my question is, why the exception? -
Django change field for each object in ManyToManyField
I have two models with a ManyToMany relationship like this: # models.py class Fileset(models.Model): fileset_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) name = models.CharField(max_length=50) in_content_build = models.BooleanField(default=False) class ContentBuild(models.Model): content_build_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) filesets = models.ManyToManyField(Fileset, related_name='content_filesets') When a ContentBuild is created I want all the Filesets that are in this ContentBuild to have their in_content_build field set to True. I tried to achieve this by using a post_save signal but I have no idea how to get all the Filesets. My attempt at a signal: # signals.py @receiver(post_save, sender=ContentBuild) def set_fileset_as_deployed(sender, instance, **kwargs): try: content_build = ContentBuild.objects.get(content_build_uuid=instance.content_build_uuid) for fileset in content_build.filesets: fileset.in_content_build = True fileset.save() except ContentBuild.DoesNotExist: pass How would I be able to set in_content_build to True for all Filesets in the created ContentBuild instance? -
Display point cloud with three.js. How to load the file locally?
I am building a little website to display point cloud in the browser. I had a sample three.js file which can display each point with (x,y,z,r,g,b) But I don't know how to load a large point cloud file in the javascript. I use Django as the framework. I tried to render and send a dictionary but the script cannot compile. <!DOCTYPE html> <html lang="en"> ... // {% block content %} // // // {% for p in point %} // // <p>{{p.0}}</p> // var particle = new THREE.Vector3(p.0,p.1,p.2); // geometry.vertices.push(particle); // geometry.colors.push(new THREE.Color(p.3,p.4,p.5)); // {% endfor %} // // // {% endblock %} for (var x = -5; x <= 5; x++) { for (var y = -5; y <= 5; y++) { var particle = new THREE.Vector3(x * 10, y * 10, 0); geometry.vertices.push(particle); geometry.colors.push(new THREE.Color(+randomColor())); } } ... I just want to load a big 2d array file in the local directory(.ply or .txt or whatever format). Say x,y,z,r,g,b every line for each point so that I can display these points in three.js . I am a newbee in building a website so I really don't know how to load it. Please help! -
Django Permission denied: '/media/images' uploading image
Please help. I'm trying to follow along with the following tutorial https://wsvincent.com/django-image-uploads/ I am getting the permission denied error as soon as I attempt to post the djangopony.png image in the section. I'm using Ubuntu 19 and Django 2.1.5. My virtual environment and project are located in the direcotry /home/sgoodman/insta ├── db.sqlite3 ├── insta_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── media │ └── images ├── Pipfile ├── Pipfile.lock └── posts ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── tests.py └── views.py permissions: drwxrwxrwx 5 sgoodman sgoodman 4096 Apr 30 13:53 ./ drwxr-xr-x 9 sgoodman sgoodman 4096 Apr 30 13:50 ../ -rw-r--r-- 1 sgoodman sgoodman 135168 Apr 30 13:53 db.sqlite3 drwxrwxr-x 2 sgoodman sgoodman 4096 Apr 30 13:50 insta_project/ -rwxrwxr-x 1 sgoodman sgoodman 545 Apr 30 12:57 manage.py* drwxrwxrwx 3 sgoodman sgoodman 4096 Apr 30 13:46 media/ -rw-rw-r-- 1 sgoodman sgoodman 176 Apr 30 12:56 Pipfile -rw-r--r-- 1 sgoodman sgoodman 3914 Apr 30 12:56 Pipfile.lock drwxrwxr-x 3 sgoodman sgoodman 4096 Apr 30 13:46 posts/ MEDIA_ROOT and MEDIA_URL setting in settings.py: STATIC_URL = '/static/' MEDIA_ROOT = '/media/' MEDIA_URL = os.path.join(BASE_DIR, '/media/') Thank you. -
How can i create some adding fields on django?
I have a class, a form thats is about a Person. All the information about the person(name, identification, contact), but i also, need information about the family of that person, the name of the family members etc.... I wanna do this in a way that the user can add a family member one by one, because some persons could have 2 family members and others 4.. or 10. And i wanna do this automatically, in the form of the person the user should be able to fill the information of the person and add the family members... -
How to filter queries within a same page in django?
I have an application for some cafe and it has only one homepage .I want to filter dishes based on the menu category.How can i filter and return it within the same page.I got no idea how to do it ? models.py class MenuCategory(models.Model): title = models.CharField(max_length=250) slug = AutoSlugField(populate_from='title') active = models.BooleanField(default=True) featured = models.BooleanField(default=False) def __str__(self): return self.title class Meta: verbose_name_plural = 'Menu Category' class Food(models.Model): name = models.CharField(max_length=250) price = models.CharField(max_length=100) detail = models.TextField(blank=True) category = models.ForeignKey(MenuCategory,on_delete=models.DO_NOTHING) image = models.ImageField(upload_to='Foods',blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: verbose_name_plural = 'Foods' views.py def homepage(request): headers = HeaderSection.objects.filter(active=True) about_sections = AboutSection.objects.filter(active=True) about_section_images = AboutSectionImage.objects.filter(featured=True) menu_sections = MenuSection.objects.all() menu_categories = MenuCategory.objects.filter(active=True) featured_dishes = Food.objects.filter(featured=True) special_dishes_section = SpecialDishSection.objects.all() foods = Food.objects.filter(active=True) category_foods = Food.objects.filter(category=menu_categories) return render(request,'cafe/base.html',{'headers':headers, 'about_sections':about_sections, 'about_section_images':about_section_images, 'menu_sections':menu_sections, 'menu_categories':menu_categories, 'featured_dishes':featured_dishes, 'special_dishes_section':special_dishes_section, 'foods':foods, 'category_foods':category_foods}) base.html <div class="iso-menu"> <ul> <li class="active" data-filter="*">All</li> {% for category in menu_categories %} <li data-filter=".{{category.foods}}">{{category.title}}</li> {% endfor %} </ul> </div> urls.py urlpatterns = [ path('',views.homepage,name='home'), # path('category/<slug>/',views.categories,name='categories') ] -
Is it possible to restrict the number of http (80) session (only one) in django?
I've developed a system which uses django for web service. Because of some security issues on network firewall device ( backend logic order firewalls to do this&that using ansible), the number of web http (80) session should be restricted to only one. Is it possible in django ? ( for example, by using some django middleware or something ) If not, is there any solution to restrict the number of http 80 session to only one? For now, it happens that not only multiple 80 session but even multiple login with same accounts. Thank you for your help in advance. -
Django rest framework: A new object is created with new id when trying to update nested object
I am trying to update multiple nested objects but never worked as expected. I've seen docs and some questions here but it doesn't work as well. models are like this models.py class Parent(models.Model): name = models.CharField(max_length=20) class Child(models.Model): ... parent = models.ForeignKey(Parent, related_name='children', on_delete=model.CASCADE) class Grandchild(models.Model): ... child = models.ForeignKey(Child, related_name='grandchildren', on_delete=models.CASCADE) and serializers.py class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(many=True) class Meta: model = Parent ... def create(self, validated_data): ... def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.save() # Update children # Update grandchildren return instance The first problem is how to update existing objects. I tried like children = validated_data.pop('children') for child in children: child = Child(parent=instance, **child) child.save() But new object is created with a new id even though the data is including the original id. How can I fix this? Also do I have to update all attributes of the object I try to update? What is the better way to update an object? -
Displaying data from intermediate table in a many-to-many relation
I have 3 models that follow the principle described in Django documentation (https://docs.djangoproject.com/en/2.2/topics/db/models/#extra-fields-on-many-to-many-relationships): class Topic(models.Model): key = models.CharField(max_length=255, primary_key=True) persons = models.ManyToManyField('Person', through='Interest') class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) interests = models.ManyToManyField('Topic', through='Interest') class Interest(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) source = models.ForeignKey(TopicSource, on_delete=models.CASCADE) The views.pyis really simple: class TopicsView(generic.ListView): template_name = 'app/topics.html' context_object_name = 'topics_list' def get_queryset(self): return Topic.objects.all() The template is actually giving me headaches: <table> <tbody class="list"> {% for item in topics_list %} <tr> <td>{{ item.key }}</td> <td>{{ item.person_set.all.count }}</td> <td> <ul> {% for person in item.person_set.all %} <li>{{ person.last_name }}, {{ person.first_name }} [{% person.interests_set.get(cluster=item) %}]</li>{% endfor %} </ul> </td> </tr> {% endfor %} </tbody> </table> With {% person.interests_set.get(topic=item) %}, I'm trying to access data from the intermediate table. How can I display the source of the interest next to the name of the person? This solution is giving hint on how to do this from the shell but I cannot figure out how to achieve that in the template. -
How to filter a queryset of a modelchoicefield in a form?
Basically I have a model named "Category" which contains a ForeignKey of a model named "Tournament". A tournament has several categories. I have an other model named "Team" which contains a ForeignKey of the "Category" model.# Currently I'm building the form to add a Team in my database. I have a ModelChoiceField and I'd like to know how can I acess to categories related to the Tournament where I'm adding my teams. class Team(models.Model): name = models.CharField(max_length=16) totalpoints = models.IntegerField(default=0) position = models.IntegerField(default=0) matches = models.ManyToManyField(Match, default=None, blank=True) category = models.ForeignKey(Category, default=None, on_delete=models.CASCADE) class TeamCreationForm(forms.ModelForm): name = forms.CharField(label='Name', widget=forms.TextInput(attrs={ 'class':'form-control', 'placeholder': 'Enter the name of the team'})) category = MyModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={ 'class':'form-control'})) class Meta: model = Team fields = [ 'name', 'category', ] class Tournament(models.Model): name = models.CharField(max_length=32) dateStart = models.DateField(auto_now=False, auto_now_add=False) dateEnd = models.DateField(auto_now=False, auto_now_add=False) nbMaxTeam = models.IntegerField() nameGymnasium = models.CharField(max_length=32, blank=True, null=True) addressGymnasium = models.CharField(max_length=254, blank=True, null=True) sport = models.ForeignKey(Sport, default=None, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, default=None, on_delete=models.CASCADE) class Category(models.Model): description = models.CharField(max_length=128) tournament = models.ForeignKey(Tournament, default=None, on_delete=models.CASCADE) -
Do I need to use set_unusable_password() when creating new users in my Django application?
I have an application where users are authenticated using active directory. This means that there is no need to store passwords in our application database. We store each users details such as username etc in a users table in our application database. I am working on implementing functionality to allow users to be added to the application. I am using a ModelForm to generate the form. The model form looks like this: class GeminiUserAccessForm(ModelForm): class Meta: model = GeminiUser fields = ['email', 'is_authorised'] labels = { 'is_authorised': 'Is authorised?' } The method in the view to handle requests from the form page: def manage_user_access_view(request): template_name = 'gemini_users/manage_access.html' if request.method == 'POST': form = GeminiUserAccessForm(request.POST) if form.is_valid(): new_user = form.save() pass else: form = GeminiUserAccessForm() return render(request, template_name, {'form': form}) Everything works as expected, a user with the given email and is authorised value is saved to the database. The password is left blank. Do I also need to use set_unusable_password() before saving the user? -
Calling a function inside another function (in two separate py files - with a external database) in Flask
I have a main python file(home.py) in my project, and I have a python file(ofScheduler) that holds several functions. Also, I have 2 SQLite databases. One created by me(landscapes.sqlite3), and one more created by someone else(ofDB.sqlite) and I added it to the project directory. Here's my home.py: import sqlite3 from ofScheduler import * app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///landscapes.sqlite3' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ofDB.sqlite' app.config['SECRET_KEY'] = "random string" ** AND HERE IS *landscapes* TABLES THAT I DEFINED ** @app.route("/sch_execqueue", methods=['POST']) def sch_execqueue(): return render_template("sch_execqueue.html" ) @app.route("/sch_execqueue_add", methods=['POST']) def sch_execqueue_add(): return ofScheduler.registerCommnadsOnExecQueue() And here's ofScheduler.py: def registerCommnadsOnExecQueue(self,commnadRecords,sourceOfCommand): if (self.verboseOutput): print ("registerCommnadsOnExecQueue") sqlBase="insert into tblExecQueue (dt,ti,Source,SourceSchlIndex,command) values({0},{1},{2},{3},{4})" dt=CU.getDateNowString() ti=CU.getTimeNowWithSecString() if (commnadRecords is not None): for r in commnadRecords: indexOfSchRecord=r[0] command=r[1] sql=sqlBase.format(CU.q(dt),CU.q(ti),sourceOfCommand,indexOfSchRecord,CU.q(command)) res=self.db.executeNonQuery(sql) else: print ("nocommands to register") def processExecuteQueue(self): if (self.verboseOutput): print ("processExecuteQueueregis") sql = "select Ind,command,Source,SourceSchlIndex from tblExecQueue" rows=self.db.executeQuery_fetchAllMethod(sql) if (rows is not None): for r in rows: ind=r[0] commd=r[1] src=r[2] indSch=r[3] result,date,time=self.executeCommand(commd) self.updateCommandLogs(commd,result,date,time,src,indSch) sql="delete from tblExecQueue where ind={0}".format(ind) self.db.executeNonQuery(sql) And here's sch_execqueue.html: <form action="/sch_execqueue_add" method="POST"> <br> <p style="display: inline-block;">dt:</p> <input type="text" name="dt"> <br> <p style="display: inline-block;">ti:</p> <textarea style="margin-top: 20px;" name="ti"></textarea> <br> <p style="display: inline-block;">Command:</p> <input type="text" name="Command"> <br> <p style="display: inline-block;">Source:</p> <input type="text" name="Source"> <br> <p style="display: inline-block;">SourceSchlIndex:</p> <input type="text" name="SourceSchlIndex"> <br><br> … -
Get data from excel to website no need to import(direct load without using tables/mpdels)
I'm trying to create a website which will be loading the data from one excel sheet. If there is any update in the sheet, website will be populated with the same. Can anyone suggest me something for this using django ? -
Application management - how many accounts, how many users
I'm trying to create an application based on django-tenants. My question concerns account management, senise counting how many accounts there are, how many people are in the company etc. At the moment I do not have for the "public" schema the possibility to access other schemas. At this point in my settings, it looks like this: SHARED_APPS = ( 'django_tenants', # mandatory 'accounts', # you must list the app where your tenant model resides in 'app_1', 'app_2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) TENANT_APPS = ( 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.messages', 'widget_tweaks', 'accounts', 'base', 'app_1', 'app_2', 'django.forms', ) # Application definition INSTALLED_APPS = list(set(SHARED_APPS + TENANT_APPS)) I mean mainly applications app_1 and app_2. If they are in SHARED_APPS - no problem - there is access to them from the /admin/ level. However, if they are in TENANT_APPS - there is no access. If I put app_1 and app_2 in SHARED_APPS - it is not safe. So is there any way to solve it (I mean management, checking accounts and users). Thank you in advance for every hint. Have a nice day. -
Django -when i update datefields and choicefield i can t see curent value
I want to edit something but some fields don t fill with the current selected value. exemple: datefield and choicefield This is my current code views.py def pacient_update(request, pk): instance = get_object_or_404(Pacient.objects.filter(medic=request.user.medic), pk=pk) instance_a = get_object_or_404(AdresaUseri, pk=pk) pacient = PacientForm(request.POST or None, instance=instance) adresa = AdresaForm(request.POST or None, instance=instance_a) if pacient.is_valid() and adresa.is_valid(): instance = pacient.save(commit=False) instance.save() context = { 'instance':instance, 'form': pacient, 'form_a': adresa, } return render(request, 'pacienti/adaugare.html', context) -
How to make django globally available
How can i make my Django project accessible via internet? When i execute project in Windows OS by typing with disabled firewall it works and reachable via internet. But in Linux OS it does not. I tried same actions. Executed it by typing and made sure my firewall is disabled python manage.py runserver 0.0.0.0:8000 Expected result is that project is accessible via internet like in windows OS -
How to load large array on memory when django starts and get it
I have a project on django. My site solve the problem by loading data from csv files and calculating them on python script Every calculation needs loading data from csv , so that I think that this is inefficient. I think the best way is to pre-load data on memory and get them when calculation starts Is it possible with only simple python script?