Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
With CVAT, can we avoid storing images in docker container?
Is it possible to set up CVAT do not storage the actual image files locally on the container? I am trying to create a modular CVAT instance which can be easily deployed on various AWS instances. Right now, I am piping in a local storage folder into the docker for both the DB and CVAT (Django/data, django/keys, django/logs). It is working, but as we add more data to the project, the size of these folders is going to increase rapidly. Since we will be uploading from the same folders each time CVAT is deployed, is there a way to just work with the filenames and pull the images when needed vs. storing? -
object of type 'function' has no len()
Iam currently working on a pagination. My main concern in here is that, my try statement is not working correctly as i thought This is a Util.py, i used to get the range of pagination and the objects def PagePaginator(request,projects,result): page=request.GET.get('page') paginator=Paginator(projects,result) try: projects=paginator.page(page) except PageNotAnInteger: page=1 projects=paginator.page(page) except EmptyPage: page=paginator.num_pages projects=paginator.page(page) leftindex=int(page)-1 if leftindex < 1: leftindex=1 rightindex=int(page)+2 if rightindex > paginator.num_pages: rightindex=paginator.num_pages custom_range=range(leftindex,rightindex) return custom_range,projects Here is a part of html where i get the page value <a href="?page={{page}}" class='btn page-link btn--sub'>{{page}}</a> I get the error in the try statement. -
Calling Ajax from Python in Django
I have a website hosted using Python on Django framework. There's a logout button and the requirement is to call some APIs before logging out. I am easily able to call those APIs using requests.Session.get. However, I am supposed to make an Ajax call to one of the API. Can someone please guide me what approach I should be following? Thanks in advance. -
Custom Django Adminsite Doesn't show link to read_only ForeignKey field
In the default Django Admin Site, if a model is registered with ForegingKey fields and those are included in readonly_fields (using the model property or the get_readonly_fields method) the value of the field is rendered with a link to the Change View, but this Doesn't work on a custom Django Admin Site. E.g.: I have this two models: class ModelA(models.Model): field_a = models.CharField(max_length=50) class ModelB(models.Model): model_a = models.ForeignKey(ModelA, on_delete=models.PROTECT) I registered in the default Django Admin Site: admin.register(ModelA) @register(ModelB) class ModelBAdmin(admin.ModelAdmin): model = ModelB readonly_fields = ["model_a"] So I get in the Change View of ModelB in the Admin the value of the field (str of the model) with a link to the Change View of the related model: Link pointing to Chang View But if I register the models in a Custom Admin Site, the link is not generated. How can I extends my Custom Admin Site in order to generate those links? PD1: I know I can code custom methods to build the links, but this is not a DRY way of do it and doesn't work well with get_readonly_fields method PD2: If I register the related model (ModelA in the example) in the default Admin Site the … -
Pycryptodome: cipher_rsa.decrypt(byte_string, sentinel) returning sentinel value everytime
Below is my code from base64 import b64encode, b64decode from pathlib import Path from Crypto.Cipher import AES, PKCS1_v1_5 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 def decrypt(base64_ciphertext): recipient_key = RSA.import_key(open(f"key.key).read()) ciphertext = b64decode(base64_ciphertext) print(ciphertext, 'ciphertext is here') cipher_rsa = PKCS1_v1_5.new(recipient_key) print(cipher_rsa, 'cipher_rsa is here') data = cipher_rsa.decrypt(ast.literal_eval(str(ciphertext)), 'Error occured') print(data, 'data is here') return data The value returned is Error occured everytime I run this function. I read all the references I could find but I can't seem to understand the issue. Please help. Is there any way to log the actual error instead of sentinel value -
Django detail_route PUT. Empty body without trailing slash
This question is not for solving the problem rather to understand why it works this way. I have ViewSet with some detail_route defined: views.py from rest_framework import viewsets class MyViewSet(viewsets.ViewSet): mgr_id = 'my_resource' @detail_route(methods=['put']) def history(self, request): print(request.body) urls.py router = DefaultRouter() router.register(r'my_resource', MyViewSet, 'r'my_resource') Now if I call my API without trailing slash: url = "http://myserver/my_resource/history" requests.put(url, data=json.dumps({'test': 'passed'}) There is no error but in history request.body is empty. However, when there is a trailing slash: url = "http://myserver/my_resource/history/" request.body suddenly transferred as expected. I'd like to know why exactly this happens? No error but payload is empty... (Plus, this might help if someone struggles with that as well) -
Apache AWS lightsail python configuration ModuleNotFound error
I want to configure my python project to make use of apache, All the configuration settings I have done to have my project to run apache as its server did not work but it was producing ModuleNotFound error, but when I checked using pip list I saw that the package was installed. However when I run python manage.py runserver ipaddress:8000 it worked perfectly without any error. This show that there is configuration which was not working. However all tutorials I have studied used apache2 directory as the location where their configuration takes place. But when I checked apache2 directory I discovered that it was pointing to apache directory and if I tried to enter into apache2 directory it would redirect me to apache directory so all my work is taking place in apache directory and not apache2 directory. How can I get my project to make use of apache server and probably access apache2 as it is done in all the tutorials. -
Custom mapmarker according to django category model
I am stuck on this for a week i have a category model class Category(models.Model): name = models.CharField(max_length=24, help_text="category") color = models.ForeignKey(Color, on_delete=models.CASCADE, null=True, blank=True) objects = CategoryManager() class Meta: unique_together = [['name','color']] def __str__(self): return f"{self.name}" in which i have color field and having colors according to code there so how can i import that in my javascript so that my marker color changed according to the category this is my js code function addMarker(map, each) { const marker = {'lat': each.fields.latitude, 'lng': each.fields.longitude} const insideMarker = new google.maps.Marker({ position: marker, map: map, }); please help me out -
When I try to filter, I get a page not found
I encountered a problem that does not allow me to filter by Choice. When I try to filter by this field I get json: {'detail':'Page not found'}, although the rest of the filtering field works fine. I'm attaching the code below Request: "http://127.0.0.1:8000/api/v1/events/?format=1" Answer: "{"detail": "Page not found."}" my models.py: FORMAT_CHOICE = ( (0, 'Online'), (1, 'Offline'), ) class Events(models.Model): format = models.IntegerField("", choices=FORMAT_CHOICE, default=0) my filters.py: class EventsFilter(FilterSet): format = django_filters.ChoiceFilter(choices=FORMAT_CHOICE) class Meta: model = Events fields = ['format'] my views.py: class EventsListView(ListAPIView): queryset = Events.objects.all() serializer_class = EventsSimpleSerializer pagination_class = LimitOffsetPagination authentication_classes = (CsrfExemptSessionAuthentication,) filter_backends = [DjangoFilterBackend] filter_class = EventsFilter -
How to copy file from FileField to another FileField with different upload path Django?
I am using Django to build a website and I am using two FileField one for user to upload the document ant the other the system will take the document to save a backup of it. My Model def file_path_dir(instance, filename): return "File/{0}/{1}".format("File" + datetime.now().strftime("%Y.%m.%d"), filename) def file_path_dir_copy(instance, filename): return "FileBackUp/{0}/{1}".format("FileBackUp" + datetime.now().strftime("%Y.%m.%d"), filename) class MyModal(models.Model) UPLOAD_ROOT = "C:/" UPLOAD_COPY = "C:/" upload_storage = FileSystemStorage(location=UPLOAD_ROOT, base_url="/uploads") upload_storage_copy = FileSystemStorage(location=UPLOAD_COPY, base_url="/uploads") attachment_number = models.FileField( verbose_name=_("Attachment"), upload_to=file_path_dir, storage=upload_storage, blank=True, null=True, ) attachment_copy = models.FileField( verbose_name=_("Backup Attachment"), upload_to=file_path_dir_copy, storage=upload_storage_copy, blank=True, null=True, ) My save view function def save_model(self,request,obj,*args,**kwargs): print(obj) for sub_obj in obj: ",sub_obj.attachment_number.__dict__) path = sub_obj.file_path_dir_copy(sub_obj.attachment_number.name) sub_obj.attachment_copy=path return super(AttachmentFormsetView,self).save_model(request,obj,*args,**kwargs) I used the code above but does not work. Please help me solving this problem. -
How to get the current user object inside a Serializer method field in Django (while doing GET request)?
Below is my Serialzer method where I need the current user object to perform a logic. but it throws keyerror 'request' def get_can_vote(self,obj): user = self.context['request'].user print(user) if obj.id and user: voter_data = CommentVotes.objects.filter(voter=user, comment=obj.id) if len(voter_data) > 0: return False else: return True -
wkhtmltopdf to pdf of Django
Me aparece este error al tratar de convertirlo a pdf FileNotFoundError at /carga/profesores/4/anexo/ [Errno 2] No such file or directory: 'wkhtmltopdf' -
django migrate is throwing error after configuring mongodb
I'm trying to integrate mongodb to a existing project which is using sqllite. This is the mongodb changes I added in settings.py to replace sqllite. import mongoengine DATABASES = { 'default': { 'ENGINE': 'djongo', }, } SESSION_ENGINE = 'mongoengine.django.sessions' #_MONGODB_USER = 'db_user' #_MONGODB_PASSWD = 'db_pa' _MONGODB_HOST = '127.0.0.1' _MONGODB_NAME = 'adas_cvat' _MONGODB_DATABASE_HOST = 'mongodb://%s/%s' % (_MONGODB_HOST, _MONGODB_NAME) mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST) AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) My versions are Django==3.1.13 sqlparse==0.3.1 djongo==1.3.6 Here is the output of makemigrations and migrate command KOREAN-M-91FL:cvat-backend korean$ python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'v1' isn't unique. You may not be able to reverse all URLs in this namespace No changes detected (sri) KOREAN-M-91FL:cvat-backend korean$ python manage.py migrate System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'v1' isn't unique. You may not be able to reverse all URLs in this namespace Operations to perform: Apply all migrations: account, admin, auth, authtoken, contenttypes, dataset_repo, engine, sessions, sites, socialaccount Running migrations: Applying engine.0001_release_v0_1_0...This version of djongo does not support "column type validation" fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using NOT NULL" fully. Visit https://nesdis.github.io/djongo/support/ WARNING - 2021-08-30 12:59:41,978 - query - Not implemented alter … -
OperationalError at /movies/ (1226, "User 'b55b31a3611152' has exceeded the 'max_questions' resource (current value: 18000)")
Myself Dileep kumar. This is my first time using Stack Overflow. I have designed and developed a movie streaming website, It's been nearly 3 months and it used to run completely fine. But now I'm seeing this error message. I tried upgrading my heroku ClearDB plan but stil i'm having this error message. Quick answers would be appreciated. THANK YOU -
re_path syntax in *application* urls.py
I have been getting this error for almost a week. I have googled and checked the docs and looked for youtube videos. I cannot find an answer to this seemingly simple and obvious question: What is the syntax for re_path() in the included urls from my apps? error: Reverse for 'jhp_url' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P<twodigit>[a-z]{2,3})/courts/(?P<slug>[-a-zA-Z0-9_]+)/$'] That pattern is correct! So obviously, the problem is slug has an empty string. But why? I have it in reverse(): def get_absolute_url(self): return reverse('jhp_url', kwargs={'slug': self.slug}) Q1:Why isn't it seeing the kwarg from reverse() and using self.slug? If I try to put self.slug in the view or the url as extra arguments, PyCharm complains. Putting the namespace in reverse() and the template makes absolutely no difference! I get the same error. BUT, if I take the namespace out of those two(1) places, I get a different error: Reverse for 'jhp_url' not found. 'jhp_url' is not a valid view function or pattern name. (1) as opposed to having it in one but not the other So it seems like the first error I mentioned here is closer to being right. My debug_toolbar template context says: 'slug': '^(?P<slug>[-a-zA-Z0-9_]+)/$' I'm … -
Error when using rpy2 to call the R script in Django:UnicodeDecodeError, invalid continuation byte
I am using a Django development server that requires rpy2 to call the R script, but there is an error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd4 in position 40: invalid continuation byte Python code is try: robjects.r.source("static/R/Sequence.R") except Exception as e: message={"status":1,"error":str(e)} return JsonResponse(message) try: robjects.r.sequence(PACds,getup,getdown) except Exception as e: message={"status":0,"error":str(e)} return JsonResponse(message) R code is library(movAPA) library(BSgenome) library("BSgenome.Oryza.ENSEMBL.IRGSP1") sequence<-function(PACds,up,down){ bsgenome=getBSgenome(genome = "IRGSP1") faFiles=faFromPACds(PACds=PACds,bsgenome=bsgenome,what='updn',up=up,dn=down,fapre='sq') plotATCGforFAfile(faFiles, ofreq=FALSE, opdf=TRUE, refPos=301, mergePlots = TRUE,filepre='Download/seq') } -
How to handle file after saving and save that file in django?
I want to user to upload file, and then I want to save that file (that part is working), then I want to calculate data in this document and export it in results.html. Problem is this, I already used return function but I want to do some calculation and save that file and for user to download.How to additionally save edited file, and forward to user to download and to see data? def my_view(request): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload as many files as you want!' if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #This part is doing calculations for uploaded file dfs = pd.read_excel(newdoc, sheet_name=None) with pd.ExcelWriter('output_' + newdoc + 'xlsx') as writer: for name, df in dfs.items(): print(name) data = df.eval('d = column1 / column2') output = data.eval('e = column1 / d') output.to_excel(writer, sheet_name=name) return redirect('results') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) def results(request): documents = Document.objects.all() context = {'documents': documents} return render(request, 'results.html', context) -
DRF not showing PK field in serializer
Similar to this, I want to show all related information in the serializer output on the HTML page: Model: class Shipment(models.Model): name = models.CharField("name", max_length = 128) date = models.DateField() class DebitSum(models.Model): name = models.CharField("name", max_length = 128) shipment = models.ForeignKey(Shipment, on_delete = models.CASCADE, blank = True, null = True) serializers: class ShipmentSerializer(serializers.ModelSerializer): class Meta: model = Shipment fields = ["pk", "name", "date",] class DebitSumSerializer(serializers.ModelSerializer): shipment = ShipmentSerializer() class Meta: model = DebitSum fields = ["name", "shipent",] This leads to a HTML page where I can fill in a name for the shipment, but not just an ID or PK. I tried altering to: class ShipmentSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Shipment fields = ["id", "name", "date",] The request.data reads as follows: <QueryDict: {'shipment.name': ['2'], ...}> #oviously fails whereas I would want it to look that way: <QueryDict: {'shipment.pk': [2], ...}> -
Getting KeyError in SAML response; django-saml2-auth, django 2.2.2
Error Getting KeyError (see image above) in SAML response, I can see that decoded response says success and I am assuming that this is related to claim mapping but I have commented "ATTRIBUTES_MAP" in setting as it said optional setting. Any help is appreciated. -
Why do we use css files for each APP in Django?
I'm following a Django course on Udemy where the instructor used specific css files for each app he created, my question is very simple: Why do need to create css files for each app? i'm asking this because those specific css files for that particular can affect other styles of the website. Like why can't we just create global css files for the whole website and thats it? -
TypeError __init__() got an unexpected keyword argument 'uploads_to'
I created models for my project but am getting the following error. Help. -
How to approach complex circular relations between models?
I'm trying to set up a database for my media files, but can't find a way to translate the data to models and useful, but not redundant relationships. There are Photos and Videos as models on the media side. class Photo(MediaFile): file = UniqueNameImageField(upload_to="photos/") preview = UniqueNameImageField(upload_to="previews/", blank=True) thumbnail = models.ImageField(upload_to="thumbnails/", blank=True) mediatype = "photo" class Video(MediaFile): file = UniqueNameFileField(upload_to="videos/") preview = UniqueNameFileField(upload_to="previews/", blank=True) thumbnail = models.ImageField(upload_to="thumbnails/", blank=True) mediatype = "video" ... As Metadata I want to store Persons, Quotes, and Releases (contracts with the appearing person). class Person(models.Model): name = models.CharField(max_length=255) age = models.IntegerField(null=True, blank=True) city = models.CharField(max_length=255, blank=True) district = models.CharField(max_length=255, blank=True) occupation = models.CharField(max_length=255, blank=True) def __str__(self): return " ".join([self.name, "("+str(self.age)+")", self.city]) class Release(models.Model): person = models.ForeignKey("Person", on_delete=models.PROTECT) file = models.FileField(upload_to="release_docs/") class Quote(models.Model): person = models.ForeignKey("Person", on_delete=models.PROTECT) #alternative by-line if it should not be name+age alt_by = models.CharField(max_length=255) text = models.TextField() Every Release should be tied to a person. Every Quote should be tied to a person. But then every Person, Release, and Quote will be tied to the Photos and Videos. The tricky part is this: Not every release counts for every photo a person is in, but rather just for a specific set of photos … -
Django-polymorphic child with foreign key to another child
I have a polymorphic model of which one of the children is dependent on another child. Below you can see a simplified version of these models. from django.db import models from polymorphic.models import PolymorphicModel class Poly(PolymorphicModel): name = models.CharField(max_length=100) class ChildA(Poly): some_field = models.CharField(max_length=100) class ChildB(Poly): some_other_field = models.CharField(max_length=100) childa = models.ForeignKey(ChildA, on_delete=models.CASCADE) When I run migrations, the error is: poly.ChildB.childa: (models.E006) The field 'childa' clashes with the field 'childa' from model 'poly.poly'. What am I doing wrong? -
How to get all the duplicated records in django?
I have a model which contains various fields like name, start_time, start_date. I want to create an API that reads my model and displays all the duplicated records. -
How do I access a property attribute of a Django model through a QuerySet filter in Django Views?
I have a model: class IpdReport(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) package=models.ForeignKey(Package, on_delete=CASCADE) The Patient model looks like this: class Patient(models.Model): name=models.CharField(max_length=100) mr_uid=models.CharField(max_length=9) #A gender field needs to be added here later @property def patient_number(self): if self.pk: return "{}{:04d}".format('PN/D/', self.pk) else: return "" def __str__(self): return self.name+"-"+self.patient_number Now, I want to filter data of IpdReport to in a views function to display a table based on the property attribute of the Patient model, that is, patient_number. Here's what I tried but it didn't work: def sort_by_pt(request): if request.method=='POST': pn=request.POST.get('enter_patient_number') report=IpdReport.objects.filter(patient__patient_number=pn) total1=report.aggregate(Sum('realization__amount_received')) total2=report.aggregate(Sum('realization__deficit_or_surplus_amount')) context={'report': report, 'total1':total1, 'total2':total2} return render(request, 'account/ipdreport.html', context) else: sort=EnterPatientNumber() return render(request, 'account/sort.html', {'sort':sort}) The error it threw: Related Field got invalid lookup: patient_number What are my options to achieve it?