Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to fetch a python file data in Django?
I want to retrieve a python file output in Django. And display the same in a text-area. How to achieve this? I am a beginner in Django. Can anyone please help me? -
How do I get Django values_list to return value of display override and not the actual value?
I noticed that when calling values() or values_list() one a queryset returns the normal value in the field and not the display value I'd like. Is there a way to manupilate the display value of the field while creating a result that is a list of list of the queryset? class FooBar(models.Model): ... foo_bar = models.CharField(_("foo"), choices=[(1, 'foo'), (2, 'bar')]) def get_foo_bar_display(self): return "something" def get_foobar(user): foobar = FooBar.objects.filter(user=user).values_list(.., 'foo_bar') foobar = list(map(list, foobar)) return foobar It always returns the foo_bar original value and not the display value. -
Add Index on field of AbstractClass
I have created one abstract model which provides default timestamp and I want to create Index on the field declared in that model Parent Model class CommonModel(models.Model): """ Provides default timestamp model """ updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True Child Model class EBUser(CommonModel): name = models.CharField(max_length=128, blank=False, null=False) work_email = models.CharField(max_length=128, blank=False, null=False) phone = models.CharField(max_length=20, blank=False, null=False) class Meta: db_table = 'user' I want to apply index on created_at field P.S: I'm using django==2.0.5, djangorestframework==3.8.2, python 3.6.5 -
Python Django /w Microsoft Graphs - I keep getting value error "state missing from auth_code_flow"
Python Django /w Microsoft Graphs - I'm following this Microsoft Tutorial for building Django apps with Microsoft Graph (using it on my existing Django webapp), and I am having an issue with authentication: https://docs.microsoft.com/en-us/graph/tutorials/python I'm on the step 'Add Azure AD authentication' and, after implementing, I hit the sign in button and enter credentials...and I keep getting value error "state missing from auth_code_flow". The "callback" method is only making it to result=get_token_from_code(request) and then fails. Here is the get_token_from_code method: def get_token_from_code(request): cache = load_cache(request) auth_app = get_msal_app(cache) # Get the flow saved in session flow = request.session.pop('auth_flow', {}) result = auth_app.acquire_token_by_auth_code_flow(flow, request.GET) save_cache(request, cache) return result What I'm trying to do is eventually access excel online from my webapp. Any help is greatly appreciated! -
how to return username instead of his ID rest framework
working fine but instead of name getting id number only views.py class createtweet(CreateAPIView): queryset = Tweets.objects.all() serializer_class = TweetsSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) serializers.py class TweetsSerializer(serializers.ModelSerializer): class Meta: model = Tweets fields = '__all__' pls give me a way to return username instead of id -
Django add id field to the model if I have primary key
I need create model that have uuid field set as primary key and id field: class SomeModel(models.Model): id = models._________ ? increment=1 unique=true uuid = models.CharField(max_length=36, unique=True, default=uuid4, editable=False, primary_key=True) -
['“27.10.2016” value has an invalid date format. It must be in YYYY-MM-DD format.']
issue_date = models.DateField(blank=True, null=True) close_date = models.DateField(blank=True, null=True) How to solve? -
=== operator not working inside an html element in Django template
This is my dashboard view in views.py def dashboard(request): return render(request, "account/dashboard.html", {"section": "dashboard"}) This a piece of code in my template. <li {% if section == "dashboard" %} class="selected" {% endif %}> <a href="{% url " dashboard" %}">My dashboard</a> </li> I'm getting this error when i try to access the page. Could not parse the remainder: '=="dashboard"' from 'section=="dashboard"' -
creating a django model which will retain the otherwise deleted (CASCADED) model instances(Like a Watchlist)
I created a model called "Post", another called "Event" and finally "Watchlist". Now, each post is associated with an event.When an event is complete, that instance of the event model is deleted, and with it, the post model is CASCADED. What i want is, for the Post instance to be deleted if the Event is deleted, but retained if the Post is added to Watchlist even after the event is over: My Models right now are: class Post(models.Model): title = models.CharField( max_length=100, validators=[MinLengthValidator(3, "Title must be greater than 3 characters")] ) event = models.ForeignKey(Event, on_delete=models.CASCADE, default=DEFAULT_EXAM_ID) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Event(models.Model): admin = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) participants = models.ManyToManyField(User, related_name="registered") class Watchlist(models.Model): post = models.ManyToManyField(Post, related_name="saved") owner = models.ForeignKey(User, on_delete=models.CASCADE) I am having trouble finding a proper way to implement the described feature. Can someone please help me with this? -
OperationalError at /admin/app/review/ no such column: app_review.startup_id
I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help I keep getting this error whenever I open my django admin page and click these models. I tried everything but none of them works, pls help here is my models.py from django.db import models from django.utils import timezone from django.utils.crypto import get_random_string import string import random code = get_random_string() class Startup(models.Model): code = models.CharField(max_length=12, default=code, unique=True) name = models.CharField(max_length=30) lead = models.CharField(max_length=50, unique=True) problem = models.CharField(max_length=100) solution = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Idea(models.Model): startup = models.ForeignKey(Startup, on_delete=models.CASCADE) summary = models.CharField(max_length=100) attachment = models.FileField(upload_to='attachments/idea') member = models.CharField(max_length=50, unique=True) date = models.DateTimeField(default=timezone.now) DRAFT … -
What is the proper way of unit testing a custom user model using choice field
I'm creating tests for a custom user model in Django that has a choice field. Is it possible to do this? -
UUID shown as integer in rest-framework
This is my model,serializer and 'admin` class UserData(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) pub_date = models.DateTimeField('date published',default=timezone.now) class UserDataSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('id','pub_date') def create(self, validated_data): user_data = UserData() user_data.save() return user_data class UserDataAdmin(admin.ModelAdmin): list_display = ["id","pub_date"] search_fields = ['id'] in admin screen id field is shown like but in rest-framework, id shown as integer. How can I fix this?? -
Python requests download zip file on request.post
I have two servers: First server send some files to second server and then get the zip file. I need get this zip file from response. My first server: files = {'file': ...} ceb_response = requests.post(ceb, files=files) My second server respond: return HttpResponse(open('db.zip', 'rb')) I need to save db.zip file in first server, how can I get the file from <Response [200]> and save file locally on first server? -
How to POST data to a common django view, what is a good approach for it using urllib module
As the title states, i'm using python urllib module to post my credentials to a generic django view for loging in, that's all. I tried some stuff based on the standard basic authentification pattern, modifying the authenticate header.... but all the same, it keeps throwing me a 403 forbidden code. i searched for a answer that address this matter, but as to me.... i couldn't find any. PD: I dont come across this problem only when authenticating, but also in POSTing any data to any view. Many thanks in advance. -
Getting Django Programming Error: column does not exist for a column that does exist
I'm fairly new to Django and still trying to figure things out. I'm trying to create a form to filter courses and populate an HTML dropdown with values from my Postgres database. My models.py from django.db import models # Create your models here. class AgeGroup(models.Model): agegroupid = models.AutoField(primary_key=True) agegrouptitle = models.CharField(max_length=50, blank=True, null=True) agegroupdescription = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'age_group' class Subjects(models.Model): subjectid = models.AutoField(primary_key=True) subjecttitle = models.CharField(max_length=50, blank=True, null=True) subjectdescription = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'subjects' class InstructorProfiles(models.Model): instructorid = models.AutoField(primary_key=True) instructorname = models.CharField(max_length=50, blank=True, null=True) instructordegrees = models.CharField(max_length=100, blank=True, null=True) instructorlongbio = models.CharField(max_length=1000, blank=True, null=True) instructorshortbio = models.CharField(max_length=500, blank=True, null=True) instructorphoto = models.CharField(max_length=1000, blank=True, null=True) class Meta: managed = False db_table = 'instructor_profiles' class Courses(models.Model): courseid = models.AutoField(primary_key=True) coursetitle = models.CharField(max_length=100) # instructorid = models.SmallIntegerField(blank=True, null=True) coursephoto = models.CharField(max_length=1000, blank=True, null=True) coursethumbnailphoto = models.CharField(max_length=1000, blank=True, null=True) credithours = models.DecimalField(max_digits=5, decimal_places=2) courseoneliner = models.CharField(max_length=200) coursedescription = models.CharField(max_length=500) instructor = models.ForeignKey(InstructorProfiles, on_delete=models.CASCADE) class Meta: managed = False db_table = 'courses' my views.py from django_mako_plus import view_function, jscontext from datetime import datetime, timezone from homepage import models as hmod from django.http import HttpResponseRedirect from django.shortcuts import render from django … -
Django: Add foreign key object to an existing object
Maybe a stupid question-- Two models A and B. A has a ForeignKey to B. I want to add another instance of B to an A instance. a = A.objects.create(b=b1) b2 = B.objects.create() So I add b2 to a like follows (so the error could be here): a.b = b2 When I print a.b I get <b1 object>, <b2 object>, which is what I want. But when I try to do a reverse b1.a_set.all(), I get an empty QuerySet. When I try to do a reverse for b2.a_set.all(), I get a in my QuerySet. Does b1 belong to a still? How can I get a to show up in the QuerySet for b1? -
read time not showing
I was trying to add a field "read_time" in my blog created by django3.1.7 I assigned the value to "instance.read_time", but it was still the default value 0 in models.py: class Post(models.Model): read_time=models.IntegerField(default=0) def pre_save_post_receiver(sender,instance,*args,**kwargs): if not instance.slug: instance.slug=create_slug(instance) if instance.content: instance.read_time = get_read_time(instance.get_markdown()) pre_save.connect(pre_save_post_receiver, sender=Post) in views.py, I try to print out related variables: print(get_read_time(instance.get_markdown())) print(instance.read_time) here's what's showing on my terminal: 1 0 Therefore, get_read_time(instance.get_markdown())=1, but instance.read_time =0. The value seemed not successfully passed onto instance.read_time. What's the problem guys? Thanks in advance! -
django: UserCreationForm: add_error to both passwords when pass validation fails
curretly in UserCreationForm (django.contrib.auth.forms) Django has def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) i want both the password fields to be shown error, when password validation fails how can i do this i tried def _post_clean(self): super()._post_clean() # Validate the password after self.instance is updated with form data # by super(). password = self.cleaned_data.get('password2') if password: try: password_validation.validate_password(password, self.instance) except forms.ValidationError as error: self.add_error('password2', error) self.add_error('password1', error) But this does not work