Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to count validate formset?
How to count how much the filled fields in formset object ? For example, I have a formset of form and each form has ChoiceField. How do I count the total filled ChoiceField in formset when each form of the formset is validated ? Thank you. -
ModelForm with multiple values not responsive
so I encountered this problem with Django and ModelForms. Everything loads as expected but when I'm trying to send data by hitting Enter nothing happens. models.py class Drinks(models.Model): name = models.CharField(max_length=50) number = models.DecimalField(decimal_places=2, max_digits=2000) def __str__(self): return self.name forms.py ( I tried with list and tuple as well ) class DrinksForm(forms.ModelForm): class Meta: model = Drinks fields = [ 'name', 'number' ] views.py def DrinksView(request): form = DrinksForm(request.POST or None) if form.is_valid(): print("VALIDATION COMPLETE") form.save() form = DrinksForm() return render (request, 'form2.html', { 'form' : form }) template.html <form method="POST"> {% csrf_token %} {{ form.as_p }} </form> admin.py from django.contrib import admin from .models import Drinks admin.site.register(Drinks) I did all necessary migrations. Any Ideas what im doing wrong? -
Django static tag variable
I'm trying to get images with Arabic names using this code: {%for book in books%} {% with 'BookCover/'|add:book.BookName|add:'.jpg' as image_static %} <img class="card-img-top" src="{%static image_static%}"> {%endwith%} {%endfor%} But when I'm running the server the name appears like this: <img class="card-img-top" src="/static/BookCover/%D9%81%D8%B5%D9%88%D9%84%20%D9%81%D9%8A%20%D8%A7%D9%84%D8%AB%D9%82%D8%A7%D9%81%D8%A9%20%D9%88%D8%A7%D9%84%D8%A7%D8%AF%D8%A8.jpg"> and if I have any mistakes in the question please correct me -
Using inherited class method on Django models classes
I have two Django model classes with their respective DB tables, both using the same class method. So I refactored and created a parent class with the class method: from django.db import models from django.forms.models import model_to_dict class Parent(models.Model): @classmethod def get_random(cls, variables: Set[str]) -> str: elements: list = [] for o in cls.objects.filter(active=True): elements.append(model_to_dict(o, fields=["id", "string"])) chosen: dict = choice(elements) # some other code... return chosen["string"] class Child1(Parent): string = models.CharField(max_length=100) type = models.ManyToManyField(Type, related_name="article_titles") active = models.BooleanField(default=True) class Meta: db_table = "table_child_1" class Child2(Parent): string = models.TextField() active = models.BooleanField(default=True) class Meta: db_table = "table_child_2" When I call the method on one of the child class with chosen_string: str = Child1.get_random(variables=variables) for example, I get a Django DB error: django.db.utils.OperationalError: no such table: app_name_parent. So it seems the parent class method is called on the default Django DB table name for parent class, instead of the child. What do I miss here? What would be the most elegant solution for using the same custom class method requesting the DB for two Django models? -
can we store rendering object in django
def fun(user, package_id, request): created_payment_request_object = ""; context = {}; return created_payment_request_object, render(request, 'index.html', context=context) I'm returning from fun and storing these returned values as payment_obj and rendered_obj payment_obj, rendered_obj = fun(user, package_id, request) Is it the right way? can we store a rendering object? -
Connecting my Django allauth project to MongoDB
I'm a newbie and I'm trying to connect my Django 3 project to my MongoDb, but when I trying to migrate I get an error code (See below) My DB connection code: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'my2ndBaseDB', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://<username>:<password>@my2ndbasecluster.wbu1f.mongodb.net/my2ndBaseDB?retryWrites=true&w=majority' } } } (In my code I have the correct username and password) This is the error code it throws at me: Error code: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying account.0003_auto_20211102_1418...Not implemented alter command for SQL ALTER TABLE "account_emailaddress" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 441, in parse self._alter(statement) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED … -
Django-CMS nav third child?
I need to display the third level in my navigation. Only the second level is displayed. Like this: |- Home |- About us |-|- History |-|-|- WW1 |-|-|- WW2 |- Contact I still hope there is someone who solved this problem! Thank youuu! {% for child in children %} {% if child.is_leaf_node %} <li><a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}" title="{{ child.get_menu_title }}">{{ child.get_menu_title }}</a></li> {% endif %} {% if not child.is_leaf_node or child.ancestor %} <li class="dropdown"><a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}" title="{{ child.get_menu_title }}">{{ child.get_menu_title }} ></a> <ul class="dropdown-menu xpl1"> {% for kid in child.get_descendants %} {% if kid.is_leaf_node %} <li><a href="{{ kid.attr.redirect_url|default:kid.get_absolute_url }}" title="{{ kid.get_menu_title }}">{{ kid.get_menu_title }}</a></li> {% endif %} {% if not kid.is_leaf_node or kid.ancestor %} <li class="dropdown"><a href="{{ kid.attr.redirect_url|default:kid.get_absolute_url }}" title="{{ kid.get_menu_title }}">{{ kid.get_menu_title }} ></a> <ul class="dropdown-menu xpl1"> {% for kidkid in kid.get_descendants %} <li><a href="{{ kidkid.attr.redirect_url|default:kidkid.get_absolute_url }}" title="{{ kidkid.get_menu_title }}">{{ kidkid.get_menu_title }}</a></li> {% endfor %} </ul> </li> {% endif %} {% endfor %} </ul></li> {% endif %} {% endfor %} ``` -
How to remove a user from all ther groups they belong to in django model?
For instance, I have two model Group and OrganizationUser. members is a field in Group model which defines as members=models.ManyToManyField('organizations.OrganizationUser', related_name="member_in_groups", blank=True) Which means a Group instance can have zero or multiple member and an OrganizationUser instance be a member of zero or multiple Group For a instance of OrganizationUser user1 I can do user1.member_in_groups.all() to access all the groups user1 is a member of. I want to remove user1 from all the groups user1 is a member of. I'm feeling iterating over the groups one by one and remove user1 isn't a right approach. What is the right way of doing so? -
Django template view
I'm just trying to understand something with Django and views. I have a form within an HTML page that I can add data to post to a database. Within this form, I have a field called Twitter Handle. When the field is updated I want to write a function that will call the Twitter API and return the number of followers. But as far as I'm aware, this cannot be done without the use of something like JavaScript that would monitor the field and then send a request to the python function to return the data? What I can't understand is that a view is bound to a function, so if I have a class view class addInvestorView(View): template_name = 'pages/add_investor.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): form = addInvestorForm(request.POST) if form.is_valid(): form.save() data = {"success": "successfully added"} else: data = {"error": form.errors} return JsonResponse(data, safe=False) How do I send a GET from JavaScript without refreshing the page, or how do I call a function without it being rendered within another page? Am I really misunderstanding all of this? -
Why does Django allow incoming connections not specified in ALLOWED_HOSTS?
Scenario - Someone is requesting a url served by a Django app. His IP is 3.3.3.3 . It could be a client but could be a server too, I don't know at the time of the request. In project settings file, there is ALLOWED_HOSTS = ["1.1.1.1", "2.2.2.2"] He (3.3.3.3) is still served. What are the allowed hosts for then? -
CSRF token missing error using vue-recaptcha and a Django Rest Framework middleware
I have the following setup : a frontend app developed with VueJS on which I have a registration form component, including few standard fields, a mandatory checkbox (user agreement), and a Google Recaptcha V2 (vue-recaptcha) checkbox a backend API developed with Django Rest Framework, with a specific route to request Google Recaptcha web service (using rest_framework_recaptcha application) I don't have any issue working in a development environment (frontend and backend accessible on localhost). Yet, when deployed in production (with https enabled), I face the following problem: Checking the user agreement checkbox first, then the Recaptcha works fine Checking the Recaptcha then the user agreement returned a 403 Forbidden error, with the message CSRF token missing or incorrect Once I get the previous error, I always get the error when filling the form again, no matter the order of checking boxes I don't get why: the problem does not occur on localhost the order of filling form lead to different behaviours the problem only occurs on my registration form while I do have several other forms (login, sending data, etc.) that work fine Any ideas to help me understand/investigate the problem ? I have read many posts related to Django and … -
index button to open a contact from in for loop in django
i have a card view in my site how do i address my button which should open a pop up contact form {% for dat in placeddata %} <div class="col-sm"> <div class="card" style="width: 18rem;"> <img src="{{dat.student.profileimg}}" width="250px" height="250px" class="card-img-top"> <div class="card-body"> <h5 class="card-title">{{dat.student.user.get_full_name}}</h5> <p class="card-text">Has been placed in {{dat.company.Comp_name}} Company.</p> <img width="50px" class="img-fluid" src="{{dat.company.profileimg}}"> <a href="" class="btn btn-primary">Contact</a> </div> </div> </div> {% endfor %}``` -
Keeping files uploaded on a site hosted on heroku in heroku postgres
I am hosting a site with django as backend, on heroku, and am using heroku postgres as database. Is there a way of keeping the files uploaded on the site in heroku postgres itself, without it getting removed after a certain period? I am assuming that there a way, since only files uploaded are removed and nothing else stored on the database. Also the organization I am developing a site for cannot use stuff like AWS due to tight budgeting. They do not expect heavy traffic on their site, hence if heroku postgres does not work, please suggest any alternate way to handle file/image uploads, without losing them -
From sqlite to PostgreSQL DB, has_perm method isn't working properly with programatcaly created permissions
I recently switched my django app from sqlite to PostgreSQL. After setting up the PostgreSQL DB, I did a dumpdata into a json file, changed the settings.py file accordingly to the new engine, and then a loaddata. Everything worked properly*. My entry point for my website is the following: @login_required def index(request): """View function for home page of site.""" if request.user.has_perm("myapp.access_main"): return redirect("myapp:main") elif request.user.has_perm("myappp.access_second"): return redirect("myapp:second") else: return PermissionDenied Users don't have permissions in my app, but groups for which they're part of do have. I have 2 groups(mods and group1, both have the "myapp.access_main" permission just like with my old db). If I connect as admin (a superuser, that I created with the sqlite db, which is part of group mods), everything works fine, I'm redirected to the main page. However, if I connect as a user1 (user created through the admin interface, created with the sqlite db too, is part of the group group1), the has_perm(...) method returns always False, hence a PermissionDenied is raised. I don't understand why the has_perm method is not working as intended for non-superusers. *: One important note is that I had to dumpdata with an exception: ./manage.py dumpdata myapp --exclude=myapp.RightsSupport. The … -
Django handle incoming chunked files by JS
I am currently writing a basic Django application which should be able to handle big files, which will be uploaded by a user. By now, as I expect very large files to be uploaded, I am chunking the files on the javascript side according to this https://newbedev.com/split-an-uploaded-file-into-multiple-chunks-using-javascript. To show the code: function fillFastaUploader() { document.getElementById("submitButton").addEventListener('click', function(e) { const size = 40000; let reader = new FileReader(); let buf; let file = document.getElementById('fastaFileUpload').files[0]; reader.onload = function(e) { buf = new Uint8Array(e.target.result); for (let i = 0; i < buf.length; i += size) { let fd = new FormData(); fd.append('fname', [file.name, i+1, 'of', buf.length].join('-')); fd.append('data', new Blob([buf.subarray(i, i + size)])); let oReq = new XMLHttpRequest(); oReq.open("POST", '', true); oReq.onload = function (oEvent) { // Uploaded. }; oReq.send(fd); } } reader.readAsArrayBuffer(file); }); } The problem is that when I try to upload a large file on the server (IIS), the file still seem to be too big (get an internal 500 error, small files are working). In Django I am currently just reading the file in like: readInputFasta = request.FILES['fastaFile'] Do I need to stream in the data in Django somehow or is there another way? Programs used: Django 3.2.4 IIS 10 -
What are the options to get filter on union querysets behavior with Django?
Basically the problem I have: I need an option or alternative approach to filter on annotated fields on union queryset. I have the following simplified models setup: class Course(Model): groups = ManyToManyField(through=CourseAssignment) class CourseAssignment(Model): course = ForeignKey(Course) group = ForeignKey(Group) teacher = ForeignKey(Teacher) class Lesson(Model): course = ForeignKey(Course, related_name='lessons') class AssignmentProgress(Model): lesson = ForeignKey(related_name='progresses') course_assignment = ForeignKey(CourseAssignment) student = ForeignKey(Student) group = ForeignKey(Group) status = CharField(choices=( ('on_check', 'On check'), ('complete', 'Complete'), ('assigned', 'Assigned'), )) deadline = DateTimeField() checked_date = DateTimeField() I need to display a statistics on assignment progresses grouped by lessons and groups for which courses assigned. Here is a my initial queryset, note that lessons are repeated in final result, the difference is in annotated data: def annotated_lessons_queryset(): lessons = None for course_assignment in CourseAssignment.objects.all(): qs = Lesson.objects.filter( course=course_assignment.course ).annotate( completed_progresses=Count( 'progresses', filter=Q(group=course_assignment.group), output_field=IntegerField() ), on_check=Exists( AssignmentProgress.objects.filter( lesson=OuterRef('id'), group=course_assignment.group, status='on_check' ) ) ) lessons = qs if lessons is None else lessons.union(qs) return lessons I canon use | OR operator here, because it returns only distinct lesson values. So far this works until I try filter all the lessons with annotated status on_check: qs = annotated_lessons_queryset().filter(on_check=True) Which fails with the error: raise NotSupportedError( django.db.utils.NotSupportedError: Calling QuerySet.filter() after union() … -
Get current user in Django modelformset_factory
I need to filter employees from same company as current user in forms.py. But the solution I found, work only for single Formsets. If I try to pass the request.user with modelformset_factory to generate a multiple formset, I get the following Error: 'MassnahmeForm' object has no attribute '__name__' What can i Do? Best regards Bostjan views.py: frm = MassnahmeForm(user=request.user) mformset = modelformset_factory(Massnahmen, form=frm, extra=mn.count()) forms.py: class MassnahmeForm(forms.ModelForm): id = forms.IntegerField(widget=forms.HiddenInput()) pdca = forms.IntegerField(widget=forms.HiddenInput()) status = forms.IntegerField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) print(self.user) super(MassnahmeForm, self).__init__(*args, **kwargs) class Meta: model = Massnahmen widgets = { 'massnahme': forms.Textarea(attrs={'onkeyup':'resizeTextarea()', 'rows': 3, 'style': 'margin: -5px;' 'width: 100%;' 'height: 100%;'}), 'umsetzer': forms.Select(choices=users, attrs={'style': 'width: 100%;' 'margin: 0px;' 'font-size: 100%;' 'padding: 0px'}), 'termin': forms.DateInput(attrs={'class': 'flatpickr flatpickr-input active', 'placeholder': 'Termin', 'readonly': 'readonly', 'style': 'width: 100%;' 'margin: 0px;' 'font-size: 100%;' 'padding: 0px'}), } fields = ('massnahme','umsetzer','termin','status') -
Is it possible to redirect to a stripe checkout page without AJAX in Django?
I have a FormView where I do some stuff after submitting the form and then I want to redirect to a stripe checkout. Is it possible without Javascript? class ApplicationForm(forms.ModelForm): class Meta: model = Application fields = "email", "name" def save(self, commit=True): application = super().save(commit=commit) checkout_session = stripe.checkout.Session.create(...) # I'm creating the session here and do some other stuff with the form input return application class ApplicationView(CreateView): template_name = "application.html" form_class = ApplicationForm def get_success_url(self): # TODO: How do I redirect to Stripe checkout here? -
Data in request.body can't be found by request.data - Django Rest Framework
I'm writing a django application. I am trying to call my django rest framework from outside, and expecting an answer. I use requests to send some data to a function in the DRF like this: j=[i.json() for i in AttachmentType.objects.annotate(text_len=Length('terms')).filter(text_len__gt=1)] j = json.dumps(j) url = settings.WEBSERVICE_URL + '/api/v1/inference' headers = { 'Content-Disposition': f'attachment; filename={file_name}', 'callback': 'http://localhost', 'type':j, 'x-api-key': settings.WEBSERVICE_API_KEY } data = { 'type':j } files = { 'file':file } response = requests.post( url, headers=headers, files=files, json=data, ) In the DRF, i use the request object to get the data. class InferenceView(APIView): """ From a pdf file, extract infos and return it """ permission_classes = [HasAPIKey] def post(self, request): print("REQUEST FILE",request.FILES) print("REQUEST DATA",request.data) callback = request.headers.get('callback', None) # check correctness of callback msg, ok = check_callback(callback) if not ok: # if not ok return bad request return build_json_response(msg, 400) # get zip file zip_file = request.FILES.get('file', None) parsed = json.loads(request.data.get('type', None).replace("'","\"")) The problem is that the data in the DRF are not received correctly. Whatever I send from the requests.post is not received. I am sending a file and a JSON together. The file somehow is received, but other data are not. If I try to do something like request.data.update({"type":j}) … -
why do i get error "django.db.utils.OperationalError: no such table:" in django?
i'm using sqlite for my database and all my tables are created but one, when i try "python manage.py migrate. i get error: django.db.utils.OperationalError: no such table: pages_cooptrainee. my models.py: class cooptrainee(models.Model): # التدريب التعاوني Name = models.CharField(max_length=100,default='') College = models.CharField(max_length=40,default='') Major = models.CharField(max_length=30,default='') Gpa = models.CharField(max_length=4,default='') Email = models.CharField(max_length=60,default='') phoneNumber = models.CharField(max_length=15,default='') my views.py: def CoopTraining(request): Name = request.POST.get('Name') College = request.POST.get('College') Major = request.POST.get('Major') GPA = request.POST.get('GPA') Email = request.POST.get('Email') phoneNumber = request.POST.get('Phone Number') trainingPeriod = request.POST.get('Training Period') if request.method == 'POST': data = cooptrainee(Name=Name,College=College,Major=Major,GPA=GPA,Email=Email,phoneNumber=phoneNumber,trainingPeriod=trainingPeriod) data.save() return render(request,'pages/التدريب التعاوني.html') my db.sqlite3.sql: CREATE TABLE IF NOT EXISTS "pages_cooptrainee" ( "id" integer NOT NULL, "Name" varchar(100) NOT NULL, "College" varchar(40) NOT NULL, "Major" varchar(30) NOT NULL, "Gpa" varchar(4) NOT NULL, "Email" varchar(60) NOT NULL, "phoneNumber" varchar(15) NOT NULL, PRIMARY KEY("id" AUTOINCREMENT) ); -
convert word document to pdf using report lab in django
I've a document document = Document("media/template.docx") I want to convert this to a pdf file and save. Any thoughts? -
Historical model does not allow deletion in reverting django data migration
I'v two models class A(models.Model): index = models.SmallIntegerField(primary_key=True) audio = models.FileField(null=True, blank=True) x = models.SmallIntegerField() y = models.SmallIntegerField(null=True, blank=True) and class B(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) index = models.SmallIntegerField() audio = models.FileField(null=True, blank=True) image = models.FileField(null=True, blank=True) I made a data migration that initializes model A objects (every object also creates B objects with it and every created B also creates C objects with it.) Here is the migration: from django.db import migrations def create_as(apps, schema_editor): A = apps.get_model('super_app', 'A') B = apps.get_model('super_app', 'B') C = apps.get_model('super_app', 'C') # C has FK referencing B # Some logic here that creates instances of A (also creates B and C) def delete_as(apps, schema_editor): A = apps.get_model('super_app', 'A') A.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('super_app', '00xx_the_very_previous_migration'), ] operations = [ migrations.RunPython(create_as, delete_as) ] The migrations is applied forward successfully.. but when I try to revert back the migration (Which should call delete_as) I'm always having this error: ValueError: Cannot query "B object (757)": Must be "B" instance. I've been trying and digging but no clue why this happens! Note: The type of models in migrations are historical models (__fake__.{MODEL}) I tried to use the latest state of the model by doing: def delete_as(apps, … -
Unable to activate virtual environment
Virtualenv is installed and created using virtualenv venv command. However I am in same directory and can't activate it. Tried below commands venv/Scripts/activate . venv/Scripts/activate .venv\Scripts\activate Please refer attached screenshot -
The localhost address in front of the django image url
When i get an image, some models put "http://localhost:8000" at the beginning and some models don't. I want to unify it in one way, but how can I express it without attaching "http://localhost:8000"? -
Django: How to filter model property in views
Please how can I filter a queryset in views using model @property method. class TransactionData(models.Model): Nozzle_address = models.CharField(max_length=255) Device = models.ForeignKey(Devices, on_delete=models.CASCADE) Site = models.ForeignKey(Sites, on_delete=models.CASCADE, enter code hererelated_name='transaction_data') Pump_mac_address = models.CharField(max_length=255) @property def product_name(self): try: return f'{(Nozzle.objects.filter(Pump__Device__Device_unique_address=self.Pump_mac_address,Nozzle_address=self.Nozzle_address)).Product.Name}' except : pass Basically I want to be able to write a query in views like this: filtered_product = models.TransactionData.objects.filter(Site=Site_id, product_name='kero') But django does not support this. I think I will need to write a custom manager where I can then query like this filtered_product = models.TransactionData.objects.filter(Site=Site_id).product_name('Key') The problem is that in the property method product_name am making use of Another model like Nozzle Please how can i get this done... I know I would need to use either custom manager or queryset to get this work but can't just figure it out.. I really appreciate your help. Thanks