Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
psycopg2.IntegrityError: duplicate key value violates unique constraint “engine_attackimage_pkey” DETAIL: Key (id)=(19) already exists
I am not setting the primary key manually. How could this be happening? relevant code: for im_url in image_urls: print(im_url) if im_url.split('.')[-1] != 'gif' and '/' in im_url.split('.com/')[1]: img_temp = NamedTemporaryFile(delete=True) img_temp.write(urllib.request.urlopen(im_url).read()) img_temp.flush() img_filename = slugify(im_url.split('.com/')[1].split('/')[1])[:50] print(img_filename) try: attack_image_object = AttackImage.objects.create( title=img_filename, source_url=im_url, creator=mike ) except Exception as e: print(e) continue attack_image_object.image.save(img_filename, File(img_temp)) attack_item_object = AttackItem.objects.create( attack_image=attack_image_object, attack='SPA', creator=mike, ) attack_item.hidden_data_found = (attacks.spa(attack_image.image) > 0.05) attack_item.save() print('%s created' % (img_filename)) models class AttackImage(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='attack_images', blank=True, null=True) source_url = models.URLField(blank=True,null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) slug = models.SlugField(blank=True,null=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title)[:50] if self.source_url and not self.image: result = urllib.request.urlretrieve(self.source_url) self.image.save( os.path.basename(self.source_url), File(open(result[0], 'rb')) ) if self.source_url: if '//' in self.source_url: d = self.source_url.split('//')[1].split('/')[0] else: d = self.source_url.split('/')[0] try: domain = Domain.objects.get(domain_url=d) except Exception as e: print(e) domain_object = Domain.objects.create(domain_url=d) domain = domain_object self.domain = domain return super(AttackImage, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("attack_image_detail", kwargs={ 'pk': str(self.id), 'slug': str(self.slug)}) traceback Traceback (most recent call last): File "crawl_ebaumsworld.py", line 91, in <module> crawl(first_url) File "crawl_ebaumsworld.py", line 65, in crawl creator=mike File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 422, in … -
Django automatically performing the collectstatic command
In my project, I have a main static folder and a sub folder named static. When I make changes in my sub folder named static (which I specified in COLLECTSTATIC_DIRS within the settings file), I save the file and run the collectstatic command. This successfully saves the changes, however is really inefficient as I am constantly changing css and Javascript files inside my project, which I store as static files. I browsed the web, and came across a solution named whitenoise, which is a pip package. But this package only works for a short period of time, and after a few times of closing and opening my project folder, it completely stopped working. Does anybody have another solution to deal with this problem? Thank you. -
View doesn't recognise list index?
i am driving myself mad with the below issue, the View wont recognise the 2nd item on the list, and will return the error below. Although if i print it, the console prints it just fine? Please help views.py def statement(request,action,param): if request.method=="POST": transaction=Transaction() filecsv = request.FILES["fileToUpload"] file_data = filecsv.read().decode("utf-8") lines = file_data.split("\n") for line in lines: linex=line.split(",") #Comment: it recognises linex[0] just fine, but when moving to [2] the following error appears(included below) transaction.name=linex[0] transaction.number=CreditCard.objects.get(pk=1) transaction.date=linex[2] transaction.postingdate=linex[3] transaction.description=linex[4] transaction.employee=linex[5] transaction.internalnote=linex[6] transaction.city=linex[7] transaction.category=linex[9] transaction.originalcurrencyamount=linex[10] transaction.currency=linex[11] transaction.amount=linex[12] transaction.save() return render(request,'sandbox/uploadstatement.html') else: print("no post") return render(request,'sandbox/uploadstatement.html',{'data':"no data"})``` error indexError at /sandbox/statement/view/view list index out of range Request Method: POST Request URL: http://127.0.0.1:8000/sandbox/statement/view/view Django Version: 3.0 Exception Type: IndexError -
Django rest framework ordering - set the location of None values
Using Django Rest Framework 'ordering_fields' for allowing sorting by all the model fields. I've added a new field that allows sorting by, but the requirement is that when sorting ASC - the None values will be first, and when sorting DESC - they will be last. The default behavior seems to be the opposite. Is there a quick way to tell the view where I want to put the None values results? Django version is 2.1.5. Django rest Framework version is 3.7.7 This is part of the model - class Item(models.Model): PRIORITIES = ( ('1', 'Low'), ('2', 'Normal'), ('3', 'High'), ) identifier = models.IntegerField(default=-1) title = models.CharField(max_length=1000) priority = models.CharField(max_length=50, choices=PRIORITIES, null=True, blank=True) Part of the view: class ItemViewSet(viewsets.ModelViewSet): ordering_fields = tuple(serializer_class.Meta.fields) -
could not translate host name "db" to address when running Django test in Docker through PyCharm
I have a simple Django project with a PostgreSQL backend: version: '3' services: db: image: postgres:12 ports: - '5432:5432' volumes: - postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_USER: pycharm POSTGRES_PASSWORD: pw123 POSTGRES_DB: pycharm app: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - '8000:8000' volumes: - .:/app depends_on: - db volumes: postgres_data: With the following database settings in settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "pycharm", "USER": "pycharm", "PASSWORD": "pw123", "HOST": "db", } } And a simple test: from django.test import TestCase class MyTestCase(TestCase): def test_example(self): assert 1 == 1 Everything works fine when I run the project with docker-compose: docker-compose up I can exec into the container running the django app and successfully execute the test: docker-compose run app bash $ python manage.py test demo.tests.MyTestCase Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.002s OK Destroying test database for alias 'default'... I want to run the test in PyCharm, instead of having to exec into the container every time. I've setup the remote interpreter using Docker. However, when I run the test in PyCharm I get the following error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or … -
Django form values not getting posted in database
Django form is not posting any values to the database. I was initially making the mistake of using <button type = 'submit'/> but I change it to <input type="submit" value="save"/> still nothing is posting to database. Form {%extends "main/base.html" %} {%block title%}create{%endblock%} {%block content%} <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" value="save"/> </form> {%endblock%} views.py if request == 'POST': form = createnewlist(request.POST) if form.is_valid(): n = form.cleaned_data['Name'] t = ToDoList(name = n) t.save() return HttpResponseRedirect("/%i" %t.id) else: form = createnewlist() return render(request,"main/create.html",{'form':form}) contents class createnewlist(forms.Form): name = forms.CharField(label = 'Name',max_length = 300) check = forms.BooleanField(required = False) I tried all the other solutions to similar problems but its not working. I might be making a very silly mistake but I am not able to figure it out. Any help will be appreciated. -
Setup apache and django with letsencrypt
In produktion i have successfully pointed apache with wsgi to my django service. However when i try to setup an SSL sertificate with letsencrypt, i can make the redirect from http :80 to https :443 work just fine. But when my browser tries to load the https site, it gets a timeout. My apache conf files looks like this, and i am using apache 2.4 on raspbian, and django version 2.2. I really hope one of you can help me find the error. 000-default.conf <virtualHost *:80> ServerName hansenbrew.dk ServerAdmin admin@example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # This is optional, in case you want to redirect people # from http to https automatically. RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] RewriteCond %{SERVER_NAME} =hansenbrew.dk RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </virtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet default-ssl.conf <VirtualHost *:443> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this … -
Default image in Django model ImageField does't work
I have a huge problem with default image in my django model, in model.ImageField. My users/models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=120) image = models.ImageField(default='default.jpg', upload_to='profile_pics') And my project/urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my project/settings.py I have: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' On website, src of my image is (unknown)... Every image I upload in my admin panel is ok. Just this default, when user has no image. What is wrong with this? I done it once in the past and everthing worked. Could you help me? -
python ../manage.py collectstatic - RuntimeError: Max post-process passes exceeded
I have a Django app with a React frontend deployed on Heroku. When I try to make changes then run python ../manage.py collectstatic it seems to be post-processing an infinite amount of files. It just goes on forever until it finally times out. When I run the same command in my development mode everything works fine. I can't figure out what's wrong. Is the files being brought over incorrectly? Here is the full message: Post-processing 'All' failed! Traceback (most recent call last): File "../manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/home/hzren/dev/t_and_b_website/venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect raise processed RuntimeError: Max post-process passes exceeded. npm ERR! Linux 5.0.0-37-generic npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "run" "collectstatic" npm ERR! node v8.10.0 npm ERR! npm v3.5.2 npm ERR! code ELIFECYCLE npm ERR! frontend-app@0.1.0 collectstatic: `python ../manage.py collectstatic --no-input` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the frontend-app@0.1.0 collectstatic script 'python ../manage.py collectstatic --no-input'. npm ERR! Make sure you have the … -
Django: Adding 2 variables and getting a response on the same page
Any help would be greatly appreciated index.html {% extends 'base.html' %} {% block content %} <div> <h1>Welcome Home</h1> <form action="{% url 'calc:home' %}" method="GET"> <!-- {% csrf_token %} --> Enter 1st Number : <input type="text" name="num1"><br><br> Enter 2nd Number : <input type="text" name="num2"><br> <input type="submit" name="" value="Add"><br><br> </form> Result of the game is : {{result}} </div> {% endblock %} views.py from django.shortcuts import render from django.http import HttpResponse def home_view(request): if request.GET.get('num1'): val1 = int(request.GET.get("num1")) val2 = int(request.GET.get("num2")) res = val1 + val2 return render(request, 'calc/index.html',{'result':res}) urls.py from django.urls import path from . import views app_name = 'calc' urlpatterns = [ path('', views.home_view, name='home'), ] i get this error when running the server: UnboundLocalError: local variable 'res' referenced before assignment -
Django model two step filter one is user and the other is custo
I am creating a project management app Each user has multiple projects and each project has a set of data When first logged in the user sees a list of all the projects only he created.i am able to do this. Then when clicked on the project the data related only to that project is to be shown. How do i do that in django? -
How do i fix this error in my Comments view in my Django app?
I'm trying to develop an app in Django. At the moment I'm trying to create a comment section for the users to write and submit comments by using a form. I made a template which shows the info of a movie as well as a form through which users can write comments on the film. The problem is that when i write the comment and try to submit it this error shows up : IntegrityError at /myapp2/2/ NOT NULL constraint failed: myapp2_comentario.pelicula_id my Views.py def detallesPelicula(request, pelicula_id): peliculas = get_list_or_404(Pelicula.objects.order_by('titulo')) pelicula = get_object_or_404(Pelicula, pk=pelicula_id) actor = get_list_or_404(Actor.objects) comentarios = Comentario.objects.filter(pelicula=pelicula).order_by('fecha') if request.method =='POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.save() texto = request.POST.get('texto') comentario = Comentario.objects.create(usuario=request.user, pelicula=pelicula, texto=texto) comentario.save() return HttpResponseRedirect(pelicula.get_absolute_url()) else: comment_form= CommentForm() context = {'pelicula': pelicula, 'peliculas': peliculas, 'comentarios':comentarios,'comment_form':comment_form} return render(request, 'detallesPelicula.html', context) my Forms.py class CommentForm(forms.ModelForm): class Meta: model = Comentario fields = ['texto'] my Models.py class Comentario(models.Model): usuario = models.ForeignKey(Usuario, on_delete=models.CASCADE) pelicula =models.ForeignKey(Pelicula, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now_add=True,null=True,blank=True) texto = models.TextField(max_length=2000, default="") -
Connect to docker database
I got a docker composer which initializes my Django project and a PostgresSQL database to it, but when I add network_mode: bridge so I can connect to the database I get the following error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known This is my docker-compose file version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres My question to you now is, how could I possibly connect to that database with pgAdmin4? -
How to render a form 'n' number of times based on the dropdown selected integer in main Form
1.I have the below requirement in django to implement. a)I have a main form with a few fields [text input fields,choice fields ] b)Based on the user input on integer field from the dropdown box in a template, i need to display few more fields waiting for the user input. Ex:If user selected an integer :3 i need to display another form 3 times containing few fields [ text input fields,choice fields] in the same html django template.[Say it is SubForm1] c) Again based on dropdown selection in subform1 i need to display few more fields waiting for the user input. Ex:If user selected an integer :4 i need to display another form 3 times containing few fields [ text input fields,choice fields] in the same html django template.[Say it is SubForm2] Screenshot is shown below. How to accomplish this .Can some one please share if any tutorial or any similar post already done at any place or clarify this. Basically i dont know much javascript/jquery .can we accomplish this only using django forms & templates with out using javascript or jquery? -
Pass active class to one of dynamically generated bootstrap tabs in django
I have read other questions (like this one) related to the same which suggested the use of custom template filters/tags but I have no idea how to implement such. Here is the code that is generating tabs and of course the class active is being repeated in all tabs: {% for day in day_list %} <li class="nav-item"> <a class="nav-link active" id="{% cycle 'monday-tab' 'tuesday-tab' 'wednesday-tab' %}" data-toggle="tab" href="{% cycle '#step-one' '#step-two' '#step-three' %}" role="tab" aria-controls="{% cycle 'step-one' 'step-two' 'step-three' %}" aria-expanded="true">{{ day }}</a> </li> {% endfor %} -
'touch' not recognized as internal or external command' (django)
I am attempting to create a django app but I am getting the 'touch' not recognized as internal or external command' error. C:\Users\blake\Documents\ProgrammingProjects\orwell84\apps> touch __init__.py 'touch' is not recognized as an internal or external command, operable program or batch file. my python version is 3.7.3 and my django version is 2.2.4 . Am I missing something ? -
Keep existing Image in database when API client sends no Image while updating in Django REST
While Updating the User Profile, I want to keep the previous image in Database when API client do not sends any image. Profile Data before update... { "first_name": "Minhajul", "last_name": "Islam", "gender": "Male", "profile_pic": "/media/ProfilePic/minhaj/IMG_5441_zjuUKoe.JPG", "bio": "bio" } Profile Data after update... { "first_name": "Minhajul Islam", "last_name": "Sifat", "gender": "Male", "profile_pic": null, "bio": "new bio" } Here my existing image has replaced with null when API client do not sends any image while updating. This is screenshot of API Client's data This is my views.py from.serializers import UpdateSerializer class Test(generics.UpdateAPIView, generics.ListAPIView): queryset = User.objects.all() serializer_class = UpdateSerializer lookup_field = 'username' def list(self, request, *args, **kwargs): username = self.kwargs.get('username') if username != str(self.request.user): return Response({"Invalid Request"}, status=status.HTTP_401_UNAUTHORIZED) queryset = self.get_queryset().filter(username=self.request.user) serializer = UpdateSerializer(queryset, many=True) return Response(serializer.data[0], status=200) def patch(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) This is my serializer.py class UpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'first_name', 'last_name', 'gender', 'profile_pic', 'bio', ] What I have to do If I want to keep the existing picture when API client sends no Image? -
Accessing model function via javascript in Django template
I have a Django project which displays a google map using the google javascript map api. The model includes a class called PlacePage which has a function that returns the first (primary) image in an image gallery: class PlacePage(Page): name = models.CharField(max_length=40) email = models.EmailField(max_length=254) place_type = models.CharField(max_length=40) one_line_description = models.CharField(max_length=250) latlng_address = models.CharField(max_length=255) def main_image(self): gallery_item = self.gallery_images.first() print(gallery_item) if gallery_item: return gallery_item.image else: return None The map is created by the javascript code, which receives the list of places: <script> var places; var map; function initMap() { var places = {{ places_array|safe }}; map = new google.maps.Map(document.getElementById('map'), { center: {lat: 38.608000, lng: -121.4555}, zoom: 16.5, styles: [ {elementType: 'labels.text.fill', stylers: [{color: '#746855'}]}, { featureType: 'administrative.locality', elementType: 'labels.text.fill', stylers: [{color: '#d59563'}] }, { featureType: 'road.highway', elementType: 'labels.text.fill', stylers: [{color: '#f3d19c'}] }, { featureType: 'poi.business', stylers: [{visibility: 'off'}] }, { featureType: 'transit', elementType: 'labels.icon', stylers: [{visibility: 'on'}] } ] }); for (index = 0; index < places.length; index++) { addMarker(places[index], index+1); } } There is an event listener on each marker which creates an infowindow: marker.addListener('mouseover', function() { infowindow.open(map, marker); }); function infowindow_content(place) { content = '<div id="content">'+ '<img height="100" src="' + place.main_image + ' width="160">' + '<h3 id="firstHeading" class="firstHeading">' … -
Django not load sencha index.html
I am trying to build app with extjs (Ver 7) and django (Ver 3.0) as backend. with out any change the index.html created bu sencha cms load and work as expected. But when I want to load with django as backend the probelm begin. It is does not loaded as expected and give an error (as below). my feeling that is related to csrf token. my index.html look like this : {% load static %} <!DOCTYPE HTML> <html manifest=""> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=10, user-scalable=yes"> <title>front</title> <!-- The line below must be kept intact for Sencha Cmd to build your application --> <script id="microloader" data-app="eef86001-0c1f-47f8-bad2-962464cb0916" type="text/javascript" src="{%static "bootstrap.js" %}" > </script> </head> <body> </body> </html > My error on chrome look like this : bootstrap.js:868 GET http://127.0.0.1:8000/index/bootstrap.json?_dc=1576345210630 404 (Not Found) VM52:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at new Manifest (bootstrap.js:1949) at Object.setManifest (bootstrap.js:2161) at bootstrap.js:2141 at XMLHttpRequest.readyStateChange (bootstrap.js:854) Thank you all for any help Koby Peleg Hen -
How i can to relate 2 Django ChoiceFileds
I have a problem in my project. I want to create a ChoiceField to be categories and subcategories in the models.py file. Well, it must be that I chose the first choice and the second according to the index of the place. For example, like the car and its models, according to the brand I chose in the First ChoiceField, you look at its models in the second field. İn Django. -
Adding padding to span element when an error message occurs in CSS
In my project, I have a form where users can signup. If an error occurs, I pass it through from my backend(Django) to my frontend. Here in the HTMl, I do an If statement to see if the error has been passed and if so, I want to display it below the field that caused the error. I successfully display the error below the form field the error came from. I display the error inside a span element. The only problem is that I want to add some space above and below the span element itself. I attempt this, but no space at all is added. Here is the code relating to this: <!-This is a flexbox container below-> <div class="flex-container"> <form class="signupForm" autocomplete="off" method="POST"> {% csrf_token %} {% if usernameError %} <span style="color: #E77B04; position:relative; top: 62px; font-size: 15px; padding-top: 15px;"> {{ usernameError }} </span> {% endif %} {% for field in form %} {{ field }} <br> {% endfor %} <button class="signupBtn" type="submit">Sign up</button> </form> </div> -
Expected iterable return type Django GraphQL
I have a many-to-many field in a Django model and a mutation that creates a list of objects then adds them to the object. Checking the created object in the shell seems to confirm the objects are created correctly, yet I still get an error when returning the data? My mutation is like so: class CreateService(graphene.Mutation): message = graphene.String() service = graphene.Field(ServicesType) class Arguments: service = ServiceProductInputType() def mutate(self, info, service): print("debug", info, service) if 'name' in service: name = service['name'] print("NAME================", name) if 'service_type' in service: service_type = service['service_type'] print("SERVICE TYPE================", service_type) if 'units' in service: units = service['units'] print("UNITS================", units) typeproduct, is_new_typeproduct = ServiceTypes.objects.get_or_create( id=service_type.id, name=service_type.name ) typeproduct.save() print("NEW SERVICE TYPE", typeproduct) new_serviceproduct = Services.objects.create(name=name, service_type=typeproduct, minimum_unit_price=service.minimum_unit_price) new_serviceproduct.save() unitsObjs = [] for unit_form in units: print("NEW UNIT", unit_form) unitproduct, is_new_unitproduct = ServiceUnits.objects.get_or_create( id=unit_form.id, name=unit_form.name ) unitproduct.save() print('test', unit_form, unitproduct) unitsObjs.append(unitproduct) new_serviceproduct.units.set(unitsObjs) new_serviceproduct.save() return CreateService(service=new_serviceproduct, message='service_created') The types are like this, but the resolver function for the units (which is the field that gives the error) does not seem to be being called? class ServicesType(DjangoObjectType): units = graphene.List(ServiceUnitsObjectType) service_type = graphene.Field( ServiceTypesObjectType ) def resolve_service_unit(self, info): service = Service.objects.filter(id=self.id) print("SERVICE", service) for unit in service.units: print("THIS UNIT", unit) unit.append( … -
How to get the object from PostgreSQL DB of the logged in user with a querySet in Django?
I would like to only fetch the row from the database where the pk equals to the pk of the logged in user. In my case the pk is an uuid called DID. What I tried: def getAccountInfo(request, *args, **kwargs): account_information = serializers.serialize('json', AccountInformation.objects.filter(pk=request.user.DID)) return HttpResponse(account_information) def getAccountInfo(request, *args, **kwargs): account_information = serializers.serialize('json', AccountInformation.objects.filter(pk=request.user.pk)) return HttpResponse(account_information) with both attempts returning empty objects. This is a snippet of the DB: -
Django secret key
I am new to django. I have created a test code and it has the secret key in folder app/settings.py. It mentions # SECURITY WARNING: keep the secret key used in production secret! But I also need to share the code with other developers for additional help so they are aware of the secret key now which was generated when the project was first created. Can I just change the characters in the secret key before I build for production? -
Build a web mongo shell?
Because my company will block the network between (devbox and laptops) and (database hosts), the "mongo mongodb://ip:port/dataname -u usr -p password" with "mongo shell" will no longer works for any user soon. Instead, the way is "user -> website (a Django server running on the jump server) -> (database hosts). My task is to build a web query server on our Django website to let our users do some query like Robo3T do. I have already done a "high school student" version like this: 1. Django get the query, check it. 2. Django server runs "mongo shell with --eval + query" with python subprocess to query mongodb. 3. Django return the data as HttpResponse to users. However this method has so many limits. I wandered is there any way to hold the "mongo shell session" on the Django server. So the process become the follows: 1. A user send a query to Django. The query is just a string, and the query can return many data, so the "it" (cursor) has to be used to return more following data. 2. Django open a mongo shell session and query with the string, and send back the first batch of data to …