Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter/annotate prefetched objects in django (more efficiently)?
I would like to filter queryset, with prefetch_related objects. This code works, but I would like to write it more efficiently. Do you have any idea ? queryset = Song.objects.prefetch_related( Prefetch('harmonies', queryset=Harmony.objects.filter(someQuery))) for s in queryset: if s.harmonies.count() > 0: songs.append(s.id) queryset = queryset.filter(id__in=songs) I tried something like this, but it didn't work. queryset = queryset.annotate(h_count=Count('harmonies')).exclude(h_count=0) Thank you , for your help. -
Pandas corelation in Django
guys i am a beginner in programming and I desperately need your help. I am trying to develope a webapp using Django. I have created a HTML form in my index.html file. In my views.py I am trying to use the corr() fundtion of Pandas but every time it says Empty DataFrame index.html <form id='form' name='form' method="post" action=""> {% csrf_token %} <div class="row"> <div class="form-group col-md-2"> <label for="Col 1">col 1</label> <input type="text" class="form-control" id="col1" name="col1"> </div> <div class="form-group col-md-2"> <label for="Col 2">col 2</label> <input type="text" class="form-control" id="col2" name="col2"> </div> </div> <div class="row"> <div class="form-group col-md-2"> <label for="Col 3">col 3</label> <input type="text" class="form-control" id="col3" name="col3"> </div> <div class="form-group col-md-2"> <label for="Col 4">col 4</label> <input type="text" class="form-control" id="col4" name="col4"> </div> </div> <button class="btn btn-primary" id='predict' name='predict'>Run forecast</button> </form> views.py def index(request): if request.method == "POST": col1 = request.POST.get('col1') col2 = request.POST.get('col2') col3 = request.POST.get('col3') col4 = request.POST.get('col4') data = {'X':[col1, col2], 'Y':[col3, col4]} df = pd.DataFrame(data) x = df.corr() print(x) return render(request, 'corelation.html') else: return render(request,'index.html') Every time I run this code it returns Empty DataFrame in terminal. However if I replace col1, col2 with actual numbers it shows the desired result. -
Concept for secured app login: someone here has a better idea, something to add that we have overlooked?
Our Situation: we are in the process of developing a concept for a login screen, for a palette of different online apps. all online apps should be available via the same login, depending on the associated user group. available online apps should be listed after login. except for the security service, all apps are independent of each other, they can be hosted on separate servers, etc. the online applications are React apps (based on TypeScript). the backend runs with Django (based on Python). (the backend framework is fixed for specific technical reasons and will be django, we need no suggestions for a different backend framework) now we are looking for the best prectise and sefest method to prevent insights and attacks as much as possible. Our Conecpt: our idear for this is, to build the login apllication with react native, to render the frontend on server site. so, the maximum visible communication tranfair with the server, will be the user credentials to the server. Login Form (React Native): Login screen as standalone app for all restricted apps Server site website rendering Server site authentication (no API call) Login credentials: "username" and "password" List available apps after sucessfull authentication Redirect with … -
The field was declared with a lazy reference to 'app.model', but app doesn't provide model
Why am I getting errors trying to refer foreign keys? Four out of Six references are working fine. Why are the other two throwing errors? The models are in the same app and file itself. I have even listed the app under INSTALLED_APPS in settings.py. I have defined all the tables according to my ER diagram. Am I missing something? accounts/models.py from django.db import models from django.db.models.deletion import SET_NULL # Create your models here. class Department(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self) -> str: return self.name class UserTypeDepartment(): CATEGORY = ( ('Main Project Contact', 'Main Project Contact'), ('Technical Administrator', 'Technical Administrator'), ('End-User Requestor', 'End-User Requestor'), ) name = models.CharField(max_length=35, null=True, choices=CATEGORY) def __str__(self) -> str: return self.name class UserDepartment(models.Model): fname = models.CharField(max_length=50, null=True) lname = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=10, null=True) email = models.CharField(max_length=100, null=True) department = models.ForeignKey('Department', on_delete=models.CASCADE) userType = models.ForeignKey('UserTypeDepartment', on_delete=models.CASCADE) #THROWS ERROR def __str__(self) -> str: return self.fname + " " + self.lname class Vendor(models.Model): name = models.CharField(max_length=150, null=True) website = models.CharField(max_length=200, null=True) name = models.BooleanField(default=False) def __str__(self) -> str: return self.name class UserTypeVendor(): CATEGORY = ( ('Vendor Contact', 'Vendor Contact'), ('Vendor Technical Contact', 'Vendor Technical Contact'), ) name = models.CharField(max_length=35, null=True, choices=CATEGORY) def __str__(self) -> str: … -
How can use div when using django block
I'm using Django 3.1.7 in the backend and have a three-page 1.index(the home page) 2.Transhow I used block to reduce and reuse index code. I have a few pages and all pages need to use the same CSS but when I use block statement the div doesn't work. <div id="content"> <div id="header"> <div id="brand"> <h1><a href="#">حسابداری</a></h1> </div> <div id="searchbox"> <form action="search" method="get"> <input type="text" placeholder="حساب مورد نظر" class="text"> <input type="submit" value="جستجو" class="submit"> </form> </div> <div class="clear"> </div> </div> <div id="toolbar"> <ul> <li><a href="http://127.0.0.1:8000" class="active">خانه</a></li> <li><a href="Account_show">مدیریت حساب</a></li> <li><a href="Trans_show">مدیریت اسناد</a></li> <li><a href="Article_show">دفتر روزنامه</a></li> <li><a href="Category_show">گروه سرفصل</a></li> <li><a href="about_us">درباره ما</a></li> <li><a href="logout_page">خروج</a></li> </ul> </div> <div id="main"> {% block main %} {% endblock %} </div> <div id="footer"></div> </div> Tran page {%block main%} <table> <tr> <th>ردیف</th> <th>شماره سند</th> <th>تاریخ</th> <th>توضیحات</th> <th>عطف</th> <th>ویرایش</th> </tr> {%for record in records%} <tr> <td><a href="article/{{record.id}}">{{record.id}}</a></td> <td><a href="article/{{record.id}}">{{record.sanadno}}</a></td> <td><a href="article/{{record.id}}">{{record.tdate}}</a></td> <td><a href="article/{{record.id}}">{{record.tdesc}}</a></td> <td><a href="article/{{record.id}}">{{record.tres}}</a></td> <td><a href="edit/Tran_edit/{{record.id}}">ویرایش</a></td> </tr> {%endfor%} {% if records.has_previous %} <a href="?page=1">اولین</a> <a href="?page={{ records.previous_page_number }}">قبل</a> {% endif %} صفحه {{ records.number }} از {{ records.paginator.num_pages }}. {% if records.has_next %} <a href="?page={{ records.next_page_number }}">بعدی</a> <a href="?page={{ records.paginator.num_pages }}">قبلی</a> {% endif %} </table> {%endblock%} css page #content { width: 1050px; border: 1px solid grey; height: 100px; margin: … -
Django DRF - Access to field ForeignKey instance inside a custom serializer validator method
I'm currently having a bit of a conceptual headache over how best to reference the instance of a ForeignKey field inside a custom serializer validator method ... To give an overview of the system. I have the following "Candidate" model, the imporant fields for this question are the user, job* and status fields. from model_utils.fields import MonitorField, StatusField from model_utils import Choices class Candidate(models.Model): class Meta: ... STATUS = Choices( 'matched', 'approached', 'invite_rejected', 'invite_accepted', 'reviewed', 'interview_scheduled', 'hired', 'rejected' ) user = models.ForeignKey('users.User', on_delete=models.CASCADE) job = models.ForeignKey('jobs.Job', related_name='candidates', on_delete=models.CASCADE) ... status = StatusField(default='matched') ... def save(self, *args, **kwargs): super(Candidate, self).save(*args, **kwargs) The status field for the Candidate can only be "updated" to a given value based on who they are, and what they're attempting to update the status to. Effectively, my outlined logic is as follows inside the serializer: from rest_framework import serializers from .candidates.models import Candidate class CandidateSerializer(serializers.ModelSerializer): class Meta: model = Candidate fields = '__all__' def validate_status(self, value): user = self.context['request'].user if user.is_anonymous: raise serializers.ValidationError("The requester must be logged in to make a change to the status field") # Ensure status value is in valid list of statuses if value not in [ 'matched', 'approached', 'invite_rejected', 'invite_accepted', 'reviewed', 'interview_scheduled', … -
How to dynamically set different parameter in setting.py file while working with django multitenant?
I want to send verification email from different email per tenant but unable to override this. How can i set following parameter dynamically per tenant in setting.py file EMAIL_BACKEND EMAIL_HOST EMAIL_USE_TLS EMAIL_PORT EMAIL_HOST_USER EMAIL_HOST_PASSWORD ANYMAIL = { "MAILJET_API_KEY":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "MAILJET_SECRET_KEY": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", } EMAIL_BACKEND = "anymail.backends.xxx.EmailBackend" DEFAULT_FROM_EMAIL = 'dynamic@gmail.com' -
RelatedObjectDoesNotExist: User has no vendor
I'm trying to make a multi vendor website using django. But there is an issue that I have vendor object vendor but it says User has no vendor. Why is this happening and how may I solve this? #models.py from django.contrib.auth.models import User from django.db import models class Vendor(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name #views.py from django.shortcuts import render,redirect from django.contrib.auth import login from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from .models import Vendor def become_vendor(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) vendor = Vendor.objects.create(name=user.username, created_by=user) return redirect('frontpage') else: form = UserCreationForm() return render(request, 'vendor/become_vendor.html', {'form': form}) @login_required def vendor_admin(request): vendor = request.user.vendor return render(request, 'vendor/vendor_admin.html', {'vendor': vendor}) -
In Django, how to display time which updates every minute?
Using tag {% now %}, I can display the time, but the time is static and doesn't update every minute. Is there anyway to update this time? Is it possible to do this with javascript's setInterval and django's {% now %}? Tried this: <script> setInterval(function () { $("#current_time").text("{% now "jS F Y H: i " %}"); }, 60 * 1000); // 60 * 1000 milsec </script> But this doesnt work as django renders now value only once(when page loads) and it remains same all time -
How to do `itertools.product(queryset_a, queryset_b)` via Django ORM?
I have two queryset, and need the product. I could use this: itertools.product(queryset_a, queryset_b) BUT the result is too big, and I need to paginate it. This means, I need to avoid itertools.product() and use the Django ORM to create the product in the database. How to do itertools.product(queryset_a, queryset_b) via Django ORM? I use PostgreSQL. -
Django-crontab - ERROR: sh: line 1: /usr/bin/crontab: No such file or directory
I followed the documentation In my django project specific venv (myproject/venv) I installed django-crontab[0.7.1] using command: (venv) pip3 install django-crontab added to settings.py INSTALLED_APPS = ( ... 'django_crontab', ) CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'django.core.management.call_command', ['my_command']) ] Next when I run python manage.py crontab add I get Error: (venv) python manage.py crontab add /bin/sh: line 1: /usr/bin/crontab: No such file or directory adding cronjob: (b27648b2dab947d53fe7e8c052bcd9a7) -> ('*/1 * * * *', 'django.core.management.call_command', ['my_command']) sh: line 1: /usr/bin/crontab: No such file or directory But I checked manually /usr/bin/ and I see a file named crontab is present. After that when I run python manage.py crontab show there is no job added. At this point I don't know what should I do. Need Help. -
How to add list of unique models to a django model
I am developing a dashboard app for clients to manage their devices with django and mariadb database. I have a Client model (which is the extended user model) and Device model which represents single, unique device. One user can have multiple devices, but one device can be assigned to only one user. Now, what is the best way to create an entry in Client model, that will contain all his assigned devices. What is important, one device (represented by unique device id) can appear only once in all Client.devices tables. Here is the code to visualize my problem: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) devices = <?> class Device(models.Model): type = models.PositiveSmallIntegerField(default=0x00) id = models.PositiveSmallIntegerField(primary_key=True, default=0x00) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) I feel like the answer is out there, but I'm not sure that other similar topics would match my uniqueness -
Django Q filter, cant get results in a single query
I want to make a query with multiple conditions to get some objects out of my Order model, but i can't find a way to get all the results in a single query. Besides the option to make 2 queries, i would like to know if this is possible with just one so i can create a CSV sheet with all of these orders(this part already works so i will stick to the query). The conditions: paymethod: Paypal and Mollie created_at: in hours 15:00 and 16:00 & paymethod: ApplePay created_at: in hours 17:00 and 18:00 The two queries: Order.objects.all() \ .filter(Q(paymethod="Paypal") | Q(paymethod="Mollie") & Q(created_at__hour__in=(15, 16))) Order.objects.all() \ .filter(Q(paymethod="ApplePay") Q(created_at__hour__in=(17, 18))) These two queries work fine seperatly, but i would like to know if it is possible to combine them to a single query. i have tried something like: Order.objects.all() \ .filter(Q(paymethod="Paypal" | "Mollie", created_at__hour__in=(15, 16)) \ & Q(paymethod="ApplePay", created_at__hour__in=(17, 18))) The above does not work because of: TypeError: unsupported operand type(s) for |: 'str' and 'str'. So instead of paymethod="Paypal" | "Mollie" i tried: paymethod="Paypal" | paymethod="Mollie" But unfortunately that doesn't work too.. Would really appreciate if someone can point me into the right direction. I'm still learning django … -
django The current path,didn't match any of these
i want to try another apps in django but i got problem when access another apps. Page not found tree: main: search: index.html scrape.html preprocessing: index.html the scenario like this. from scrape.html i want to access index.html in preprocessing but got an error path not found. I've done to add apps in settings.py main url.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('search.urls')), path('preprocessing/', include('preprocessing.urls')), ] search url.py urlpatterns = [ path('', views.index,), path('scrape/',views.scrape,), ] preprocessing url.py path('', views.index), let me know where did I go wrong, thx for your help -
How to create an approval system for a model in Django?
I created a system for several types of users. These users are analyst, lead, manager, etc. I have a credit limit table (doa) in my system. I want to when a lead type user updates a field in this table it shouldn't be accepted until a manager approves it. So, the old value should be valid until the manager approves the new values, and when the manager approves it the new value should be accepted. How can I do that? Here are my codes: models.py class DoaTable(models.Model): LIMITS = ( ('Low Risk', 'Low Risk'), ('Medium Risk', 'Medium Risk'), ('Moderately High Risk', 'Moderately High Risk'), ... ) RANKS = ( ('Analyst', 'Analyst'), ('Senior Analyst', 'Senior Analyst'), ('Lead', 'Lead'), ('Manager', 'Manager'), ... ('Chief Financial Officer', 'Chief Financial Officer'), ) rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) limit = models.FloatField() ... views.py def update_limit(request, id): limiting = get_object_or_404(DoaTable, id=id) form = UpdateDoaTableForm(request.POST or None, request.FILES or None, instance=limiting) limiting_item = DoaTable.objects.filter(id=id) if form.is_valid(): update_form = form.save(commit=False) update_form.approval = False update_form.save() return redirect('approvals:update_limit_list') context = { 'form': form, 'limiting_item': limiting_item, } return render(request, 'limitUpdate.html', context) forms.py class UpdateDoaTableForm(forms.ModelForm): class Meta: model = DoaTable fields = ('limit',) -
How to use Apache Beam in a Python Class
I am new to Python, I am not sure how to run the apache beam transforms inside a Python Script. This is how I read data from MongoDB and apply transforms right now. It works. pipeline = beam.Pipeline(options=options) ( pipeline | beam.io.ReadFromMongoDB(uri='mongodb://localhost', db='db', coll='coll') | beam.ParDo(Transform()) | beam.io.WriteToMongoDB(uri='mongodb://localhost', db='db', coll='coll') ) But I want to run this inside a Python class like: class ExampleHigherOrderFn(ABC): def init(self, database, input, output, operation): # Operation is what change I want to make in the query. So I need to pass it to transform functions. ... def run(self): # main function basically does two things: # READ FROM DB # WRITE OUTPUT TO DB pass # classes that inherits from the class above class OneTransform(ExampleHigherOrderFn): # This class only applies transforms ??? Should I put beam.DoFn inside of here ??? class Transform(beam.DoFn): def process(self, element): pass class SecondTransform(ExampleHigherOrderFn): # This class only applies transforms How do I achieve this? -
Why can I not execute migrations with Django in poetry venv?
I've setup a virtualenv using poerty==1.1.5 for a Django project in WSL2-Ubuntu. When I try to execute a database migration with Django=3.0.4 I get the following error: (.venv) florian@DESKTOP-G3G6E71-wsl:~/gitlab/mvp-edge-backend/backend$ python manage.py makemigrations 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 "/home/florian/gitlab/mvp-edge-backend/backend/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/florian/gitlab/mvp-edge-backend/backend/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/florian/gitlab/mvp-edge-backend/backend/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 244, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/florian/gitlab/mvp-edge-backend/backend/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 37, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/florian/gitlab/mvp-edge-backend/backend/.venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 11, in <module> from django.db.migrations import Migration File "/home/florian/gitlab/mvp-edge-backend/backend/.venv/lib/python3.8/site-packages/django/db/migrations/__init__.py", line 1, in <module> from .migration import Migration, swappable_dependency # NOQA ModuleNotFoundError: No module named 'django.db.migrations.migration' I've recreated the venv several times like suggested in other related questions. However I get always this same error. The package seems to be installed in the venv properly: (.venv) florian@DESKTOP-G3G6E71-wsl:~/gitlab/mvp-edge-backend/backend$ pip freeze … -
Reliable File transfer from Django to external FTP
I have a Django application that needs to upload files generated upon the update of a model objects. More concretely, once a database entry is modified, a function has to be fired to generate a tiny CSV file and upload it to an (S)FTP server. My question is on how to make the uploads reliable and performant (possibly couple of thousands transactions a day). That is, make sure the files are always uploaded with possibly few duplicates without overloading the Django instance. One option I explored was to send these tiny CSV files to a cloud queue (e.g. AWS SNS/SQS) and have another CRON job (e.g. AWS Lambda) to fetch the queue and upload the files. Any ideias for the architecture? -
How to use a form with autocomplete fields in django admin update action
I am using a custom form in admin panel with two autocomplete fields among the others. My problem is that I don't know how to use the form in update action in order the stored data to appear with the autocomplete functionality. In my implementation in update action the values appearing without autocomplete functionality. How can I fix that? my form class ModelSeoMetadatumForm(forms.ModelForm): name = ModelChoiceField( required=False, queryset=MetaTag.objects.exclude(name__isnull=True).values_list('name', flat=True).distinct(), widget=autocomplete.ModelSelect2(url='seo:name-autocomplete') ) property = ModelChoiceField( required=False, queryset=MetaTag.objects.exclude(property__isnull=True).values_list('property', flat=True).distinct(), widget=autocomplete.ModelSelect2(url='seo:property-autocomplete') ) class Meta: model = ModelSeoMetadatum fields = ('name', 'content', 'property', 'content_type', 'object_id') my admin @admin.register(ModelSeoMetadatum) class ModelSeoMetadatumAdmin(admin.ModelAdmin): add_form = ModelSeoMetadatumForm list_display = ('id', 'name', 'content', 'property', 'content_object') fields = ('name', 'content', 'property', 'content_type', 'object_id') def get_form(self, request, obj=None, **kwargs): defaults = {} if obj is None: defaults['form'] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) -
why i am geting ValueError at /attendance/ while saving data
i can't figure out how to save my form data which I have taken from passwdJSON.I try to convert in dict but it gave me a value error actually I am getting data in form of QueryDict, please suggest to me how to save that data in the database I also tried this method in views save(commit=False) models.py from django.db import models class studentProfile(models.Model): name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(unique=True) rollNumber = models.IntegerField(unique=True) class Meta: ordering = ('name',) verbose_name_plural = 'Student Profile' def __str__(self): return self.name class studentAttendance(models.Model): CHOICES = ( ('present', 'present'), ('absent', 'absent'), ) name = models.ForeignKey(studentProfile, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField(max_length=10, choices=CHOICES) date = models.DateField(auto_now=True) class Meta: verbose_name_plural = 'Student Attendance' def __str__(self): return self.name.name forms.py from django import forms from .models import * class studentProfileForm(forms.ModelForm): class Meta: model = studentProfile fields = '__all__' class studentAttendanceForm(forms.ModelForm): class Meta: model = studentAttendance fields = [ 'status',] views.py from django.contrib import messages from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.db.models import Q from django.shortcuts import render, redirect, get_object_or_404 from django.utils import timezone import ast from .forms import * from .models import * def studentAttendanceView(request): student_status = studentProfile.objects.all() if request.method == "POST": # print(request.POST) my_data … -
Resolve error django-oauth-toolkit: raise AppRegistryNotReady("Models aren't loaded yet.")
How I can resolve error: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I have: Django==2.0.13 django-oauth-toolkit==1.2.0 python==3.6 I run command manage.py runserver and receive traceback: Traceback (most recent call last): File "xxx/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "xxx/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "xxx/models.py", line 20, in <module> from oauth import constants, oauth2_internal, utils File "xxx/oauth2_internal.py", line 15, in <module> oauthlib_core = get_oauthlib_core() File "xxx/lib/python3.6/site-packages/oauth2_provider/oauth2_backends.py", line 194, in get_oauthlib_core validator = oauth2_settings.OAUTH2_VALIDATOR_CLASS() File "xxx/lib/python3.6/site-packages/oauth2_provider/settings.py", line 143, in __getattr__ val = perform_import(val, attr) File "xxx/lib/python3.6/site-packages/oauth2_provider/settings.py", line 97, in perform_import return import_from_string(val, setting_name) File "/xxx/lib/python3.6/site-packages/oauth2_provider/settings.py", line 109, in import_from_string module = importlib.import_module(module_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/xxx/oauth2_validators.py", line 3, in <module> from oauth2_provider import oauth2_validators File "/xxx/lib/python3.6/site-packages/oauth2_provider/oauth2_validators.py", line 41, in <module> Application = get_application_model() File "xxx/lib/python3.6/site-packages/oauth2_provider/models.py", line 400, in get_application_model return apps.get_model(oauth2_settings.APPLICATION_MODEL) File "xxx/lib/python3.6/site-packages/django/apps/registry.py", line 190, … -
Multiple Django subforms displayed with ajax in a main form but data not registered when subforms are submited (without error)
I have a main form (patient.html) and I want to display different subforms (inclusion.html for instance) with ajax in this form. I manage to display a subform when user click on a button in the main form But, data are not stored when submitted and it is quite normal as no view is linked to this subform I have read about this in different post but I miss the concept how to... I thinks it is a common task with web so probably Django as an easy way to do it? thanks for advices urls.py app_name='ecrf' urlpatterns = [ path('', views.index, name='index'), path('patient/<pk>', views.patient, name='patient'), path('sub_form', views.sub_form, name='sub_form'), ] views.py def patient(request,pk): patient = {"id":1,"num":'A-001',"dat":'Mon 11, novembre 2020',"arm":1,"doc":'Slater'} return render(request, 'ecrf/patient.html', {'patient':patient}) def sub_form(request): if request.is_ajax(): return JsonResponse( { 'html_inclusion': render_to_string( 'ecrf/inclusion.html', { 'form': InclusionForm, 'language': request.session.get('language') }, request=request ), }, status=200 ) js $(document).ready(function () { ... $("#add").on("click",function (event) { var csrftoken = getCookie('csrftoken'); $.ajax({ type: "POST", url: '/ecrf/sub_form', data: { csrfmiddlewaretoken: csrftoken, }, dataType: 'html', success: function (data) { $("#sub_form").children().remove(); obj = JSON.parse(data); $("#sub_form").append(obj.html_inclusion); }, error: function (data) { console.log('error'); } }); }); $("body") .on("click", '#inclusion', function (event) { console.log('inclusion click') }) }); -
"attempt to write a readonly database" - Give permissions to db.sqlite3
I am trying to deploy my Django project on a Bitnami server, but when I try to login through admin with my superuser i get the following error: attempt to write a readonly database Exception Location: /opt/bitnami/python/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute I have the following permissions to my project files: drwxrwxr-x 6 bitnami www-data 4096 Mar 12 08:01 . drwxr-xr-x 3 bitnami root 4096 Mar 11 10:00 .. drwxr-xr-x 2 bitnami bitnami 4096 Mar 11 11:48 conf -rw-rw-r-- 1 bitnami www-data 147456 Mar 12 08:01 db.sqlite3 -rw-r--r-- 1 bitnami bitnami 287 Mar 11 13:29 .env drwxr-xr-x 5 bitnami bitnami 4096 Mar 11 10:26 app -rwxr-xr-x 1 bitnami bitnami 667 Mar 11 10:00 manage.py drwxr-xr-x 3 bitnami bitnami 4096 Mar 11 13:52 django_project drwxr-xr-x 5 bitnami bitnami 4096 Mar 11 10:26 users and this to the project directory drwxrwxr-x 6 bitnami www-data 4096 Mar 12 08:01 django_project I tried to run the following to give permission but without luck: sudo chown :www-data /opt/bitnami/projects/django_project/db.sqlite3 sudo chmod 664 /opt/bitnami/projects/django_project/db.sqlite3 sudo chown :www-data /opt/bitnami/projects/django_project/ sudo chmod 775 /opt/bitnami/projects/django_project/ Can you help me? :) -
How to write unittest for django project that using two database (mysql and mongo)
My django projects use two type of database (mariadb and mongoengine) I have no idea how to write the unittest that test both of them in the same testcase. please guide me. now i try to use fixtures_mongoengine to write fixture mongo data but that cannot use with mysql fixture in the same testcase -
Django Choice Field default based on index of queryset
Good day SO. I would like to set my select option default of index 0. This is how I create my form: SOME_CHOICES = [] someObj = SomeModel.objects.filter(type = 1, is_active=True).order_by('id') for x in enumerate(someObj): SOME_CHOICES.append([x.id, x.salary_range_name]) some_field = forms.ChoiceField(choices=SOME_CHOICES) As you can see, I create my choices based on model with filter type of 1. I would like to have the default of the option as the first/index 0