Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Is this Hack to work around PASSWORD_RESET_TIMEOUT_DAYS cannot be set to less than one day safe?
Django does not allow the variable PASSWORD_RESET_TIMEOUT_DAYS to be set to less than one day. As a workaround, I am thinking of sending the timestamp in the password reset activation URL, using this format: path('activate/<uidb64>/<timestamp>/<token>/', views.activate, name='activate') Using the timestamp, I could then manually check whether the timestamp is within a period of time that is less than one day. Was wondering if doing this is unsafe from a security point of view? -
Form not registering photo Django 3.0
I'm trying to get a photo to upload and the form is not seeing the file and in the form.errors, it says 'this field is required'. I've tried using picture = request.FILES['picture'] to no avail and have also tried picture = form.FILES['picture'] as well as picture = request.POST.FILES['picture'] and picture = form.cleaned_data.get('picture') What am I missing? Let me know if you need anymore information template {% block content %} <h1>Create {{post_type.title}} Post</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type='submit'>Submit</button> </form> {% endblock %} forms.py class PicturePostForm(forms.ModelForm): class Meta: model = PicturePost fields = ('description', 'privacy', 'picture', 'categories') views.py @login_required() def picture_post(request): """ Creates new picture post """ if request.method == "POST": form = PicturePostForm(request.POST) print("is post") if form.is_valid(): print("is valid") # this never gets printed because of the 'this field is required' error author = request.user content = form.cleaned_data['description'] category = form.cleaned_data['categories'] picture = form.cleaned_data['picture'] privacy = form.cleaned_data['privacy'] p_post = PicturePost(author=author, description=content, categories=category, picture=picture,privacy=privacy ) p_post.save() #redirect to last page return redirect('home') else: l = [] for i in form.errors.keys(): l.append(form.errors[i]) return HttpResponse(l) else: post_type = 'picture' form = PicturePostForm() return render(request, 'create_post.html', {'form': form, 'post_type': post_type}) The corresponding model field picture = models.ImageField(upload_to=f'profiles/{User}_gallery', max_length=255) -
How can I add animations to my images in my Django app?
I´m trying to add a kind of animation to some images in my Django app, what I want to do is that when the user moves the mouse around the image it gets bigger. I tried adding some code in my CSS but the image won't change Thank you for your help. My index.html {%block contenido %} <div id="container" class="foto_pelicula"> {% for p in peliculas %} {% if p.genero.id == 1 %} <a href="{% url 'detallesPelicula' p.id %}"><img src={{p.urlPortada}} width="289" height="289"/></a></li> {% endif %} {% endfor %} </div> <div id="container" class="foto_pelicula"> {% for p in peliculas %} {% if p.genero.id == 2 %} <a href="{% url 'detallesPelicula' p.id %}"><img src={{p.urlPortada}} width="289" height="289"/></a></li> {% endif %} {% endfor %} </div> <div id="container" class="foto_pelicula"> {% for p in peliculas %} {% if p.genero.id == 3 %} <a href="{% url 'detallesPelicula' p.id %}"><img src={{p.urlPortada}} width="289" height="289"/></a></li> {% endif %} {% endfor %} </div> {% endblock %} The Images SRCs are urls that I take from the internet, I guess it does not really matter whether they are taken from the internet or stored in your proyect. my CSS #container{ width: 290px; overflow: hidden; margin: 5px 4px 0 auto; padding: 0; background: #222; /* … -
Django Category Service Catalog URL Slug
I am trying to create a home page where categories will be displayed and on choosing the category should redirect to another page and pass the variable of the category so I can create service catalogue from where the service is chosen based on what category was chosen. I was able to create the pattern for category but I am not able to do home>category>category sidebar with products>product view and I am currently at the moment able home>category> after that I am lost and also how to filter or pass variable to it category_list_sidebared.html to previously chosen category. from home.html Models: class Category(models.Model): CATEGORY_CHOICES = ( ("PT", "Painting"), ("Pb", "Plumbing"), ("HM", "One Hour Husband"), ("EL","Electronic Wiring") ) category = models.CharField(max_length=2,choices=CATEGORY_CHOICES) photo = models.FileField(upload_to='category',null=True) category_slug = models.SlugField(blank=True) def __str__(self): return self.category def save(self, *args, **kwargs): self.category_slug = slugify(self.category) super(Category, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('category_list', args=[self.category_slug]) class Gig(models.Model): title = models.CharField(max_length=500) category = models.ForeignKey('Category',on_delete=models.PROTECT) description = models.CharField(max_length=1000) price = models.IntegerField(default=6) photo = models.FileField(upload_to='gigs') status = models.BooleanField(default=True) user = models.ForeignKey('User',on_delete=models.PROTECT) create_time = models.DateTimeField(default=timezone.now) product_slug = models.SlugField(blank=True) def __str__(self): return self.title def save(self, *args, **kwargs): self.product_slug = slugify(self.title) super(Gig, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('gig_view', args=[self.product_slug]) Views: def home_authenticated(request,category_slug=None): categories = Category.objects.filter() return … -
Best way to create a SPA using Django
I'm trying to develop a SPA using Django, what is the best way to do that? -
Deploying Django Application to Elastic Beanstalk with Django Cities Light
I am deploying a django application to elastic beanstalk and it uses the django-cities-light package. Right now I have the following elasticbeanstalk config: container_commands: 01_add_cities_light: command: "source /opt/python/run/venv/bin/activate && python manage.py cities_light" leader_only: true But this causes every deployment to run the full cities light package, resulting in deployment times in excess of 10 minutes. When this line is removed, deployment takes less than half the same amount of time with far less RDS utilization. Is there a better way to implement this package to allow for more efficient deployments and scaling? -
create Separate row For every book volume in django
Hello friends in my django web app I have a model called book Contains volume_number field, As you know Some books have More than one volume now I want With any post request, create Separate row For every book volume in database, How can I do this? -
What is the optimal way to write function-based views in Django?
What is the recommended way to write views (as functions) in Django? I am asking in terms of readability, etc. For example: define the template first, then do the translations, then define models and lastly define context. Here is some example code: def index(request): # Landing page, translated to the browser's language (default is english) template = loader.get_template("koncerti/index.html") # Translators: This is the text on the homepage buttons concerts = gettext("Koncerti") band = gettext("Band") # Translators: This is the option in the language-switch box foreignLanguage = gettext("eng") koncertiUrl = '/koncerti/international' # The URL slug leading to 'koncerti' page bandUrl = '/band/international' # The URL slug leading to 'band' page translationMode = '' # The URL slug that is leading to slovenian translation mode context = { 'Concerts' : concerts, 'Band' : band, 'foreignLanguage' : foreignLanguage, 'koncertiUrl' : koncertiUrl, 'bandUrl' : bandUrl, 'translationMode' : translationMode } return HttpResponse(template.render(context, request)) -
Errors after running EB deploy - Your requirements.txt is invalid
The error message I get after running "EB deploy": 2019-12-14 15:37:55 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2019-12-14 15:37:57 ERROR [Instance: i-05ca9242185a849e6] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2019-12-14 15:37:58 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2019-12-14 15:37:58 ERROR Unsuccessful command execution on instance id(s) 'i-05ca9242185a849e6'. Aborting the operation. 2019-12-14 15:37:58 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. Requirements.txt file awsebcli==3.16.0 botocore==1.13.39 cement==2.8.2 certifi==2019.6.16 chardet==3.0.4 colorama==0.3.9 Django==2.1.11 django-appconf==1.0.3 django-classy-tags==0.9.0 django-cms==3.6.0 django-crum==0.7.4 django-dajaxice==0.7 django-debug-toolbar==2.1 django-filer==1.5.0 django-formtools==2.1 django-js-asset==1.2.2 django-mptt==0.10.0 django-polymorphic==2.0.3 django-sekizai==1.0.0 django-treebeard==4.3 djangocms-admin-style==1.4.0 djangocms-attributes-field==1.1.0 djangocms-bootstrap4==1.5.0 djangocms-column==1.9.0 djangocms-file==2.3.0 djangocms-googlemap==1.3.0 djangocms-icon==1.4.1 djangocms-link==2.5.0 djangocms-listyle==0.1.7 djangocms-owl==0.1.11 djangocms-picture==2.3.0 djangocms-snippet==2.2.0 djangocms-style==2.2.0 djangocms-text-ckeditor==3.8.0 djangocms-video==2.1.1 docutils==0.15.2 easy-thumbnails==2.6 future==0.16.0 html5lib==1.0.1 idna==2.7 jmespath==0.9.4 jsonfield==2.0.2 mysqlclient==1.4.2 nano==0.9.4 pathspec==0.5.9 Pillow==6.1.0 psycopg2==2.8.4 pypiwin32==223 python-dateutil==2.8.0 pytz==2019.2 pywin32==227 PyYAML==3.13 requests==2.20.1 semantic-version==2.5.0 six==1.11.0 sqlparse==0.3.0 stripe==2.33.2 termcolor==1.1.0 Unidecode==1.0.23 urllib3==1.24.3 wcwidth==0.1.7 webencodings==0.5.1 There are a ton of log files to peruse through, and I haven't the slightest where to start looking, but I did find this - which makes … -
Python xmltodict with multiple OrderedDictkeys
Is there any way to create xml output that given a multiple OrderedDict like this data = OrderedDict([ ... ('addresses', OrderedDict([ ('address', OrderedDict([ ('city', 'Washington') ])), ('address', OrderedDict([ ('city', 'Boston') ])) ])) ]) When i try this xmltodict covers last address not both.