Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does flask and django work together, should I learn them simultaneously?
I recently learned Django & I wonder if I have to learn Flask in order to have a good back end stack? I know Node.js and used it for APIs before but I don't know if it should be mixed with Django in a single project or not. Thanks in advance. Update: I am thinking APIs & Socket wise because I don't feel like Django supports them (Please correct me). -
Django models.CharField max_length not working
I am trying set up a model in Django, the DB I am using is SQLite class MyTable(models.Model): MyField = models.CharField(max_length=5) But when I try to enter a value more with length more than 5 it does not throw any error. >>> from AppOne.models import MyTable >>> MyTable(MyField="12345678").save() >>> MyTable.objects.all()[0].MyField '12345678' I read SQLite there is no length Limit for VARCHAR. So I will be able to connect to the DB out side Django. I will be able enter value with any length. But while doing it from Django should not it be validated. Am I doing anything wrong? What is the correct way? From Admin site it does not let me enter any value greater than 5 though. -
Django postgresql query return an array value in html table
I am trying to fetch array data from Django postgresql database and want to display in a html table. Also I input those data through html table with manual input which are given below: <td><input type="text" name="product_id" value="{{data.product_id}}" readonly></td> <td><input type="text" name="price" value="{{data.price}}" readonly></td> <td><input type="text" name="quantity" value="{{data.quantity}}" readonly></td> In views: product_id = request.POST.getlist('product_id') price = request.POST.getlist('price') quantity = request.POST.getlist('quantity') amount = request.POST.getlist('amount') purchase_table = PurchaseInvoice.objects.create(product_name=product_id, price=price, quantity=quantity) purchase_table.save() data successfully added in my database. data stored like ['value1','value2']. But when I am trying to display those data on my html table its show on same format like ['value1','value2']. I want to display those data separately like in first row value1 and 2nd row value2. my models, views and html code given bellow: models: class PurchaseInvoice(models.Model): product_name = models.CharField(max_length=500) price = models.CharField(max_length=300) quantity = models.CharField(max_length=200) def __str__(self): return self.product_name View: def purchaseDetails(request,pk): invo_data = PurchaseInvoice.objects.all().filter(invoice=pk) return render(request,'purchase/invoice_details.html', {'invoice':invo_data}) HTML: {% for data in invoice %} <tr><td> {{ data.product_name }}</td> <td>{{ data.price }}</td> <td>{{ data.quantity }}</td></tr> {% endfor %} -
How can I download all the files related to a specific request in an zip file at once?
I have a table in which all the files related to specific request are stored(a specific request can have more than one or few related files). I have used a download_zip_file function to download the file at once. But unfortunately I receive an error which says "[WinError 3] The system cannot find the path specified: '/media/documents/my_needs_Zxvf8IN.docx'" The file that is in the url error, exists.I don't know what caused the error and how to fix it. Does anyone has a clue?? my download zip function is here: @login_required def download_zip_file(request, docreq_id): doc_req = Documents.objects.get(id=docreq_id) if doc_req.sent_from_assignee: doc_ups = AMdocDocuments.objects.filter(docrequest__pk=docreq_id) filenames = list(map(lambda f: f.doc_file.url, doc_ups)) zip_subdir = "%s %s" % (doc_req.request_title, doc_req.user_email) zip_filename = "%s.zip" % zip_subdir s = BytesIO() zf = zipfile.ZipFile(s, "w") for i, fpath in enumerate(filenames): fname = fpath.split("/")[-1] # Rename uploaded files to doc file ext = fname.split(".")[-1] if ext: fname = '%s' % smart_str(doc_ups[i].amdoc.doc_name + "." + ext) zip_path = "%s %s" % (zip_subdir, fname) zf.write(fpath, zip_path) zf.close() resp = HttpResponse(s.getvalue(), content_type="application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename return resp return Http404 here is my urls: from django.urls import path from . import views app_name = 'account' urlpatterns = [ path('login/', views.user_login, name='login'), path('signup/', views.user_signup, … -
DRF update the nested foreign key of an object
I am trying to wrap my head around this for too long already :( I need the following output for my frontend (specially the ID & name field in combination): { "serial": "e3461fb0", "shipment": { "id": 1, "name": "via rotterdam" } } model: class Shipment(models.Model): name = models.CharField("name", max_length = 128) date = models.DateField() class Product(models.Model): serial = models.CharField("serial", max_length = 31, unique = True) shipment = models.ForeignKey(Shipment, on_delete = models.CASCADE, blank = True, null = True) serializer: class ShipmentSerializer(serializers.ModelSerializer): class Meta: model = Shipment fields = ["pk", "name",] class ProductSerializer(serializers.ModelSerializer): shipment = ShipmentSerializer() def update(self, instance, validated_data): print("TEST:", instance, validated_data) return super().update(instance, validated_data) class Meta: model = Product fields = ["serial", "shipment",] lookup_field = "serial" read_only_fields = ["serial",] ViewSet: class ProductViewSet(ModelViewSet): serializer_class = ProductSerializer lookup_field = "serial" http_method_names = ["get", "patch", "put"] def get_queryset(self): return Product.objects.all() my problem here is the following: Lets say a product ist linked to a shipment and what I want now is to update that product by linking it to another shipment by using the id. But even in the HTML view of DRF I only get to see the name attribute of shipment. How can I only show/use the id here? I know … -
Change django-autocomplete-light html property
1st How do i change a default html property on django-autocomplete-light? 2nd How does django renders the html elements from a form widget? Hi there! I'm using django-autocomplete-light v3. 1st I will show you how to understand my problem 2nd I'going to ask you for any help Would you like to try django-autocomplete-light in less than a minute and help me? You may follow the steps from here: https://django-autocomplete-light.readthedocs.io/en/master/install.html Or just: pip install django-autocomplete-light Then, to let Django find the static files we need by adding to INSTALLED_APPS, before django.contrib.admin and grappelli if present: 'dal', 'dal_select2', # 'grappelli', 'django.contrib.admin', Install the demo project Install the demo project in a temporary virtualenv for testing purpose: cd /tmp virtualenv -p python3 dal_env source dal_env/bin/activate pip install django pip install -e git+https://github.com/yourlabs/django-autocomplete-light.git#egg=django-autocomplete-light cd dal_env/src/django-autocomplete-light/test_project/ pip install -r requirements.txt ./manage.py migrate ./manage.py createsuperuser ./manage.py runserver # go to http://localhost:8000/admin/ and login Now you are able to help!!! 1.1 Log in to your admin panel 1.2 scroll until you see "SELECT2_ONE_TO_ONE" and click 1.3 Add a new Tmodel clicking in the 'plus' button from the right 1.4 Go to the Inspection mode on you Browser (ctrl+shift+i)and click on any select field there i don't have … -
when i run the server , instead of the localhost:8000, i'm redirected to localhost:8000/app/
Page not found (404) “/home/sowou/Bureau/my_space/etude/IFNTI/stage/Django-CRM/app” does not exist Request Method: GET Request URL: http://127.0.0.1:8000/app/ Raised by: django.views.static.serve Using the URLconf defined in crm.urls, Django tried these URL patterns, in this order: ^swagger(?P<format>\.json|\.yaml)$ [name='schema-json'] ^swagger/$ [name='schema-swagger-ui'] ^redoc/$ [name='schema-redoc'] api/ logout/ [name='logout'] ^(?P<path>.*)$ The current path, app/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Stripe import could not be resolved. Django
As in title i can not import stripe to my django app. I get this message. I use virtual environment for this project if it changes anything. Import "stripe" could not be resolved from source(reportMissingModuleSource) -
Django on Heroku not uploading to S3
I'm working on a project using Django(3) in which I want to upload static files to S3 bucket using boto3 Here's setttings.py: if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' else: STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') django_on_heroku.settings(locals()) options = DATABASES['default'].get('OPTIONS', {}) options.pop('sslmode', None) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' My site is loading correctly and while deployment collectstatic copied all files to S3 bucket but now if I upload a file from django admin, its not uploading to S3 bucket, there's wasn't any mediafiles folder in the bucket, so I manually created that directly but files are not uploading there. -
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') }