Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problem with quering a many to one in django
Im fairly new to Django, I was attempting to make a many to one query in my program. Im making af clinic site, in which I want a list of patients for the given clinic to be shown. I have the following Model.py and views.py: models.py class Klinik(models.Model): class Patient(models.Model): klinik = models.ForeignKey(Klinik, null=True, on_delete=models.SET_NULL) views.py def kartotek(request, kl_id): klinikid = Klinik.objects.get(id=kl_id) patienter = Klinik.Patient_set.all() context = {'patients':patienter,} return render(request,'DentHelp/kartotek.html', context ) The error message is for the _set.all() attribute, but I cant see what the problem should be -
Importing OrbitControls (Django)
So I'm trying to import OrbitControls, but it gives me error. Anyone know way to import it when using Django? Three is imported successfully. code error -
How to create a serializer with multiple models, that are connected to each other?
So I have UserAccount model, which has this fields: class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) iin = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) father_name = models.CharField(max_length=255) phone_number = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_doctor = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['iin', 'first_name', 'last_name','father_name', 'phone_number'] def get_full_name(self): return self.first_name + ' ' + self.last_name + ' ' + self.father_name def __str__(self): return self.email And also this class that has user as a foreign key: class Patient(models.Model): user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) district = models.CharField(max_length=255) def __str__(self): return self.user.email So my question is how to create a serializer for the registration? How am I supposed to create a UserAccount and Patient which has UserAccount as a foreign key together??? PLS HELP This is my diploma work THIS DOES NOT WORK class RegistrationSerializer(serializers.ModelSerializer): class PatientCreateSerializer(serializers.ModelSerializer): class Meta: model = Patient exclude = ['user'] patient = PatientCreateSerializer() class Meta: model = UserAccount fields = '__all__' def create(self, validated_data): patient_data = validated_data.pop('patient') user_instance = UserAccount.objects.create(**validated_data) Patient.objects.create(user=user_instance,**patient_data) return user_instance Also, how am I supposed to send data in POSTMAN? LIKE THIS? { "patient": { "district": "2323232", "user": [{ "email": "someemail@gmail.com", "iin": "02020202002", "first_name": "Some", "last_name": … -
How can we get data of current logged in user in flutter if used django as a backend
I want to show widgets in flutter as per the types of user logged in. For example if the user is logged in as seller, he/she can see widgets to sell the goods and if he/she is buyer they should get option to buy goods. I want to achieve this in flutter with django backend... -
django-tenants: Restrict access to public schema
I am trying to create a multi tenant app (with shared database and isolated schema) using this Django-Tenants package. And I've followed the example videos to setup a demo: video1 and video2 app clients (models.py) from django.db import models from django_tenants.models import TenantMixin, DomainMixin class Client(TenantMixin): name = models.CharField("Customer name", max_length=100) created_on = models.DateField(auto_now_add=True) # default true, schema will be automatically created and synced when it is saved auto_create_schema = True class Domain(DomainMixin): pass app sweet_tenant (models.py) from django.db import models from applications.sweet_shared.models import SweetType class Sweet(models.Model): sweet_type = models.ForeignKey(SweetType, on_delete=models.CASCADE) name = models.CharField(max_length=50) price = models.DecimalField(default=0, decimal_places=3, max_digits=8) def __str__(self): return self.name app sweet_shared (models.py) from django.db import models class SweetType(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name settings # Application definition SHARED_APPS = [ "django_tenants", # mandatory 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # shared apps "applications.clients", "applications.sweet_shared", ] TENANT_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # your tenant-specific apps "applications.sweet_tenant", ) INSTALLED_APPS = SHARED_APPS + [app for app in TENANT_APPS if app not in SHARED_APPS] BEHAVIOUR Public schema are shared with all tenants. Any tenant can see any data form public schema if you don't filter. This is a normal behavior Tenants (clients) are created … -
Django websocket connection failure
Websocket is refusing to connect in my project and showing me this message (index):12 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/[object%20HTMLScriptElement]/' failed: here is my project repo link : Repository link -
Translation Django doesn't work in template and view
I am bulding an app in django, writing all interface messages in english to after translate them to other language. My first attempt is using the spanish as language target. I have been reading other questions, but I have not had success with translation in view and template. Some questions are: Localization doesn't work Django internationalization doesn't work in my project Django translations does not work Many others In the most of them, the problem is LOCAL_PATHS setting is bad set. However, I followed the recommendations of the answers, so I think this is not my problem and I can't figure out what it is. These are my settings. # Notice a LocalMiddleware MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] # I have a special directory to my templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, # Still needed for admin templates ... } # Language settings LANGUAGE_CODE = 'es' LANGUAGES = [ ('en', _('English')), ('es', _('Spanish')), ] # I use BASE/DIR to configure the paths... LOCALE_PATHS = [ BASE_DIR / 'locale', BASE_DIR / 'utils/locale', ] USE_I18N = True Project structure: In each app there are its own 'locale' directories and the tranlations … -
How can I preserve the python '%' character when adding to a string that will be run as html?
Here is some possibly important background info: I am parsing .js paths server-side in python, adding them to the context object. My goal is to reflectively load js packages based on the url endpoint used by the client. @api_view(["GET"]) def home(request, path="tutorial"): return render(request, "template.html", context={ "path" : "{% static '"+ path +".js' %}" }) The issue I've run into is that the '%' character does not convert correctly, as you can see from the server log: [23/Apr/2022 11:05:40] "GET /%7B/%%20static%20'tutorial.js'%20/%%7D HTTP/1.1" 404 2574 I know that '%' is used by python for string manipulation and therefore is added to strings as a multi-char code, but what I can't figure out is how to add a literal %. I've tried '/%', r'', and b'' variations, .encode() too, but none of them change the output. Here is what is being run client side: <script type="text/javascript" src="{{path}}"></script> I've tested everything else, and it all works perfectly. I just can't get python to send html friendly '%'s! -
How To Login A Custom User In Django
Hello This is my models of user app in django, class Customer(AbstractUser): phoneNumber = models.CharField(max_length=30,null=True, blank=True) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False,) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser groups = None user_permissions = None def __str__(self): return self.username class Supplier(AbstractUser): address = models.TextField(max_length=200) phoneNo = models.CharField(max_length=20) staff = models.BooleanField(default=False,) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser groups = None user_permissions = None def __str__(self): return self.username for which i want to implement a login page, i successfully did a signup page using forms class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = Customer fields = UserCreationForm.Meta.fields + ('phoneNumber',) class CustomUserChangeForm(UserChangeForm): class Meta: model = Customer fields = UserChangeForm.Meta.fields class CustomSupplierCreationForm(UserCreationForm): class Meta(UserCreationForm): model = Supplier fields = UserCreationForm.Meta.fields + ('address','phoneNo',) class CustomSupplierChangeForm(UserChangeForm): class Meta: model = Supplier fields = UserChangeForm.Meta.fields then used class SignUpPage(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class SupplierSignUpPage(generic.CreateView): form_class = CustomSupplierCreationForm success_url = reverse_lazy('login') template_name = 'supplier_signup.html' but i am totally lost as how to implement the login stuff as the doc and google search was overwhelming for me, please help. -
How to give access different object of a model to different users in django by the creator of the object
I am working on a classroom project and I am completely new to Django. How to modify my models (course,user) so that I can add students to the course in two ways 1)By entering the class code by students. 2)By sending join invitations to students from a list of all students by selecting some by the teacher and if the student confirms/accepts he will be added. i am attaching the models below user model class CustomUser(AbstractUser): email = models.EmailField() is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) Course Model class Course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(25)]) classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) slug=models.SlugField(null=True, blank=True) def __str__(self): return self.course_name def save(self, *args, **kwargs): self.slug = slugify(self.classroom_id) super().save(*args, **kwargs) def is_valid(self): pass Teacher Views @login_required def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() messages.success(request, "Class Created Sucessfully") return redirect('/tdashboard') context['add_courses'] = form return render(request, 'teacherview.html', context) @login_required def view_courses(request, *args, **kwargs): courses = Course.objects.filter(created_by=request.user) dict = {'course': courses} return render(request, 'teacherhome.html', dict) -
How to Serialize only valid objects in Django Rest Framework with many=True?
I am asking this question after making a search on the Internet and found nothing of use. (Except for this question, which was not answered) I have the following serializer class StudentSerializer(Serializer): name = CharField(help_text="") age= IntegerField(min_value=0, help_text="") last_name = CharField(required=False, help_text="") def validate(self, attrs): return attrs And following data, to be serialized: data = [ { "name":"Burakhan", "age":27, "last_name":"Aksoy" }, { "name":"Mehmet", "age":27, "last_name":"Randomname" }, { "name":"Cevdet", "age":28 }, { "name":"Ahmet", "age":-2, # This is invalid "last_name":"Yilmaz" } ] When I want to serialize this as follows, serialzied.validated_Data returns an empty List even though only a single object is not valid. serialized = StudentSerializer(data=data, many=True) serialized.is_valid() >>> False serialized.errors >>>[{}, {}, {}, {'age': [ErrorDetail(string='Ensure this value is greater than or equal to 0.', code='min_value')]} serialized.validated_data >>> [] My question is, how can I have a serializer so that only valid ones are serialized and invalids are discarded? Thank you -
Django social-auth-app-django error after social login completed
AttributeError at /social-auth/complete/github/ 'NoneType' object has no attribute 'provider' Other solutions on this site did not solve the problem. Sorry if you see this as a dup. copied from reddit: Hello! Hope everybody is doing well. As the title suggest I keep getting this error every time I try to use the social login on my site. This is for a school and we are using github for the authorization. What I believe is happening is, the user social auth data is being sent somewhere else instead of the user social auth database. The reason I think this is because after github auths my account,and crashes, I can see it grabbed my user name and my email from github correctly in the database, I can see it in my admin. However, The user social auth remains empty.I'm pretty confident that there's a problem with my urlpatterns redirecting data into the damn sun instead of the user social auths database. Again I've got no idea how to fix this. I've been at it for about two weeks now and made no progress into solving this problem, Things I've tried: Social_auth_pipeline, dosen't work using django_allauth crashes the site I've changed my settings … -
login with existing users
I am doing a project in Django where I need to log in through existing users on another web page. For this I have a link to consume the web service and to be able to consume it I enter some parameters, among these is the user login (username) and the password, when the web service is consumed (I use the suds library to consume it), It gives me certain user data such as user, profile, name and status. I tried to search how to do this and I found that I can use the request.META['REMOTE_USER'] but I still don't understand how to implement it, is there an example? -
Server Error on connection for jquery.js and bootstrapmin.js
I am writing a Django project and trying to use jquery and bootstrap min js, but I got the error Failed to load resource: the server responded with a status of 404 (Not Found). When I refresh the page thing like this: GET http://localhost:63342/employeeSystem/app01/templates/%7B%%20static%20'plugins/bootstrap-4.0.0/js/bootstrap.min.js'%20%%7D net::ERR_ABORTED 404 (Not Found) GET http://localhost:63342/employeeSystem/app01/templates/%7B%%20static%20'js/jquery-3.6.0.min.js'%20%%7D net::ERR_ABORTED 404 (Not Found) Here is my implementation of code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheets" href="{% static 'plugins/bootstrap-4.0.0/css/bootstrap.min.css' %}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> <script src="{% static 'plugins/bootstrap-4.0.0/js/bootstrap.min.js' %}"></script> </body> </html> Here is my file structure(I still need 3 reputation so … -
When i try to delete a model django gives FOREIGN KEY constraint failed
in django i am trying to delete a news in admin page but it gives FOREIGN KEY constraint failed error -
How to send email with pdf attachment using python Django?
I want to send an email with an invoice to the user after the payment process. How can I do it with Django. I tried a few codes but it is not working. -
How to automatically do calcuations using Javascript in django templates?
I have models: class Payments(models.Model): paymentid = models.IntegerField(primary_key=True) bookingid = models.ForeignKey('Roombookings', models.DO_NOTHING, db_column='bookingid') paymenttype = models.CharField(max_length=255) paymentamount = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'payments' class Roombookings(models.Model): bookingid = models.IntegerField(primary_key=True) customername = models.CharField(max_length=500, blank=True, null=True) customeraddress = models.CharField(max_length=550, blank=True, null=True) bookingfrom = models.DateField(blank=True, null=True) bookingto = models.DateField(blank=True, null=True) assignroomid = models.ForeignKey('Rooms', models.DO_NOTHING, db_column='assignroomid', blank=True, null=True) noofguests = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'roombookings' class Rooms(models.Model): roomid = models.IntegerField(primary_key=True) roomnumber = models.IntegerField() roomprice = models.IntegerField() roomtype = models.CharField(max_length=255) roomcapacity = models.IntegerField() class Meta: managed = False db_table = 'rooms' I want an automatic calculation of paymentamount when a bookingid is entered which works under the formula of 'bookingto-bookingfrom' date * roomprice from another table My django views function: def payments(request): if request.method == 'POST': form = PaymentsForm(request.POST) if form.is_valid(): form.save() return redirect('/payments done/') return render(request,'files/payments.html',{'form': PaymentsForm()} In templates, I'm just using: <form action="" method="POST" > {% csrf_token %} {{form.as_p}} <input type = "submit" value ="Submit"> </form> In the templates section, In the javascript part, I want to autofill the payment amount by doing some calculation. -
why is "no results to fetch" Django error when DB record created
code: print('fork 1:'+str(self.mySessionID)) print('fork 2:'+str(myTimeStarted)) print('fork 3:'+str(self.__uid)) print('fork 4:'+str(why_started)) try: MySessions.objects.create( session_id=self.mySessionID, when_started=myTimeStarted, who_started=self.__uid, why_started=str(why_started) ) except Exception as Sht: print("! "+str(Sht)) # ! no results to fetch reply: fork 1:59092 fork 2:2022-04-23 16:44:59.656620+03:00 fork 3:870806915 fork 4:WAITING FOR ::: vLVlhYyZvIM ! no results to fetch (DB record had been created Ok though;) the problem is, if I do NOT put it all in try-except, the script stops; and I do not want to put all of those db-record-creation blocks inside of try-except, that be stupid I think.) the question is WHY is this error being thrown? -
Django crispy-forms bug: Multiple Image input doesn't show different file names
I have a crispy form with an image input field that accepts multiple images: images = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control', 'multiple': True}), required=False) The form works perfectly fine and the images are uploaded and can be processed in the backend. However, there is a weird frontend bug: Usually when you select multiple images for upload on a crispy image field, it shows all the file names of the selected images as a list in that widget. However, in my case it just shows the name of one of the files, multiple times (to be precise: for every file selected it shows the name of one of the files once). For example, if I select three files with different names, one of which is called 'kangaroo.png', the widget looks like this: Now I've pinned down the problem to this little snippet: <div class="custom-file "> <input type="file" name="images" class="form-control fileinput fileUpload form-control-file custom-file-input" multiple accept="image/*" id="id_images"> <label class="custom-file-label" for="id_images">Choose file</label> <script type="text/javascript" id="script-id_images"> document.getElementById("script-id_images").parentNode.querySelector('.custom-file-input').onchange = function (e){ var filenames = ""; for (let i=0;i<e.target.files.length;i++){ filenames+=(i>0?", ":"")+e.target.files[0].name; } e.target.parentNode.querySelector('.custom-file-label').innerHTML=filenames; } </script> </div> The problem lies in the line that reads: filenames+=(i>0?", ":"")+e.target.files[0].name;. It should clearly be: filenames+=(i>0?", ":"")+e.target.files[i].name;. And sure enough, when I looked into … -
UserCreationForm doesn't save the password commit=False (No password set)
I create a registration form on HTML ajax pull the data and send it to UserCreationForm via a function in views.py. But when I check the user I realized the password is not saved. I am using ajax so I took the data per field. And in the view function, I had to add the field values one by one. I used set_password but didn't help. Any help will very appreciated thank you My Form: class RegisterForm(UserCreationForm): username = forms.CharField(max_length=100 , widget=forms.TextInput( attrs={'class': "form-control"})) email = forms.EmailField(max_length=100, widget=forms.EmailInput()) password1 = forms.CharField(widget=forms.PasswordInput( attrs={'class': "form-control"})) password2 = forms.CharField(widget=forms.PasswordInput( attrs={'class': "form-control"})) email.widget.attrs.update({'class': 'form-control'}) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] user.set_password(self.cleaned_data['password1']) if commit: user.save() return user My View: def home(request): register_form = RegisterForm() workshop_form = WorkshopCreateForm if request.method == 'POST': register_form = RegisterForm(request.POST) username = request.POST.get('username') print(username) email = request.POST.get('email') password1 = request.POST.get('pass1') password2 = request.POST.get('pass2') if register_form.is_valid(): pended_form = register_form.instance pended_form.username = username pended_form.email = email if password1 == password2: pended_form.set_password(password1) pended_form.save() ctx = { 'username': pended_form.username, 'password': pended_form.password, 'created': True, 'success': True, 'status':'You created your account', } return JsonResponse(ctx) else: ctx = { 'username': '', 'password': '', … -
How to test Django view that have a request to API?
I Have a view post that gets post by its id. In the test, I would like to create a new post and then check via API, if the post is available. The problem that I have is that post is being added to the test database but when executing the GET request it makes a request to the development database. views.py def post(request: HttpRequest, id: str): context = {"form": PostForm} url = env("BASE_URL") if id: post = requests.get(f"{url}/api/v1/post/{id}").json() context["post"] = post return render(request, "post.html", context) test_view.py class BlogPageTest(TestCase): @classmethod def setUpTestData(cls): cls.user = UserProfile.objects.create( name="TestUser", email="test@mail.com", password="pass" ) def test_post_render(self): client = APIClient() client.force_authenticate(user=self.user) post = Post.objects.create( title="Test post", body="Test post data", user=self.user, ) post.save() response = client.get(reverse("post", kwargs={"id": str(post.id)})) -
Django monkey patching model with method seems to work correctly as instance method - am I missing something?
I am using Django 3.2 and I am having to monkey patch a model, based on some conditional logic. myapp/models.py class Foo(models.Model): # fields ... # methods ... pass in console from myapp.models import Foo def something(obj): return obj.id # Monkey patching the class (model) setattr(Foo, 'mysomething', something) # Fetch an instance form db f = Foo.objects.all().first() f.mysomething() # return 1 (correct) My surprise is the fact that the something method is not accepting an argument, and instead, seems to be using the argument specified in the definition (obj) as a synonym for self - and therefore, the method is acting like an instance method. Can anyone explain the technical reason why this is happening - and is this documented (and therefore consistent) behaviour I can rely on in my code? -
Django: NOT NULL constraint failed: course_courserating.user_id
i am trying to create a logic where users can review and rate a course, the logic in my views.py looks fine but i keep gettting this errror NOT NULL constraint failed: course_courserating.user_id i removed some null=True from my models but it still keeps showing the error. views.py if request.method == "POST": form = CourseRatingForm(request.POST) if form.is_valid(): rating_form = form.save(commit=False) user = request.user course = course rating_form.save() messages.success(request, f'You review was sent successfully!') return redirect("course:course-detail", course.slug) else: form = CourseRatingForm models.py class Course(models.Model): course_title = models.CharField(max_length=10000) slug = models.SlugField(unique=True) class CourseRating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True) rating = models.CharField(max_length=1000, choices=USER_COURSE_RATING) review = models.TextField() date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return f"{self.course.course_title} - {self.rating}" -
Deploying 'Django for beginners' app to Heroku fails with ModuleNotFoundError: No module named '_tkinter'
I am following William Vincents Django for Beginners, and I'm about to push the blog app to Heroku at the end of chapter 8. I have checked the code several times, and everything is just as in the book, but it fails every time with ModuleNotFoundError: No module named '_tkinter'. Here is the log from Heroku: -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> Using Python version specified in runtime.txt ! Python has released a security update! Please consider upgrading to python-3.10.4 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.10.3 -----> Installing pip 22.0.4, setuptools 60.10.0 and wheel 0.37.1 -----> Installing SQLite3 -----> Installing requirements with pip Collecting asgiref==3.5.0 Downloading asgiref-3.5.0-py3-none-any.whl (22 kB) Collecting Django==4.0.4 Downloading Django-4.0.4-py3-none-any.whl (8.0 MB) Collecting gunicorn==20.1.0 Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB) Collecting sqlparse==0.4.2 Downloading sqlparse-0.4.2-py3-none-any.whl (42 kB) Collecting tzdata==2022.1 Downloading tzdata-2022.1-py2.py3-none-any.whl (339 kB) Collecting whitenoise==5.3.0 Downloading whitenoise-5.3.0-py2.py3-none-any.whl (19 kB) Installing collected packages: whitenoise, tzdata, sqlparse, gunicorn, asgiref, Django Successfully installed Django-4.0.4 asgiref-3.5.0 gunicorn-20.1.0 sqlparse-0.4.2 tzdata-2022.1 whitenoise-5.3.0 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_8fe73f22/manage.py", line 22, in <module> main() File "/tmp/build_8fe73f22/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in … -
Django models: dynamic inheritance from classes defined in standalone app
I am using Django 3.2 I have written a standalone app social that has models defined like this: from abc import abstractmethod class ActionableModel: # This MUST be implemented by ALL CONCRETE sub classes @abstractmethod def get_actionable_object(self): pass # This MUST be implemented by ALL CONCRETE sub classes @abstractmethod def get_owner(self): pass def get_content_info(self): actionable_object = self.get_actionable_object() ct = ContentType.objects.get_for_model(actionable_object) object_id = actionable_object.id return (ct, object_id) # ... class Likeable(models.Model, ActionableModel): likes = GenericRelation(Like) likes_count = models.PositiveIntegerField(default=0, db_index=True) last_liked = models.DateTimeField(editable=False, blank=True, null=True, default=None) # ... in my project (that uses the standalone app), I have the following code: myproject/userprofile/apps.py class UserprofileConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'userprofile' verbose_name = _('User Profile') def ready(self): # Check if social app is installed from django.apps import apps if apps.is_installed("social"): # check some condition # inherit from social.Likeable # ... ? How can I dynamically get my model userprofile.models.UserAccount to derive from Likeable?