Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reuse website templates (layout/theme) in Python Django?
I'm new to web-dev, but among those simple apps I wrote in Django, there's a simple base_generic.html as the website page template, like this <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Local Library</title>{% endblock %} </head> <body> {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %} {% block content %}<!-- default content text (typically empty) -->{% endblock %} </body> </html> inside which we have a few blocks, so that we could extends from there to add new page content. This html template is really simple and poor-looking, and I need some good-looking page templates, so I wonder 1) could it be possible to download website page templates of, say WordPress (they have many beautiful ones), and use in Django? 2) or what's the typical we to resolve my issue in Django world? -
Will I be able to get optimal speed out of a Django web application?
I've been told that if I am to develop a web application (which I intend to do), I'll best use Python together with the Django framework. Yet since I am somewhat of a perfectionist (and since I intend to release my project on open source, so that others may use it as well), I intend to do a good job and minimise the number of computer operations for each task my web application is going to fulfill. Hence, I'd like to ask the following question: Is it possible to minimise the total number of computer operations using Python together with the Django framework? If not, to which extent is it possible? If the answer to the above question is very negative, I'd be interested in a way of programming that allows the desired minimisation. -
TemplateSyntaxError at /rango/category/other-frameworks/
Newbie on django. Following Tango-with-django book . Getting Error "TemplateSyntaxError at /rango/category/other-frameworks/ Could not parse the remainder: 'category.slug' from ''add_page'category.slug'" Here is the link to my code on github Tango-with-django-vikas-baghel Please Help me out as I have tried my best but still not able to find the mistake. -
Run django management command on elastic beanstalk worker instance using crontab
I have written few django management commands that I want to run hourly, daily and weekly basis. I'm using Elastic Beanstalk and created a worker instance where the code is deployed. Can someone help me how to run the django management command with crontab using elastic beanstalk. Thanks Here is my management command: python manage.py command_name Please help me write the container_command in .ebextensions/django.config file for crontab that will schedule the command on hourly basis. Thanks -
Django rest framework listfield valid integer is required formdata
I am trying to make a post request on model with many to many field class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() categories = models.ManyToManyField(Category) quantity = models.IntegerField() price = models.FloatField() attribute_values = models.ManyToManyField(Value) image = models.ImageField(blank=True) My serializer class: class ProductSerializer(serializers.ModelSerializer): categories = serializers.ListField(child=serializers.IntegerField()) attribute_values = serializers.ListField(child=serializers.IntegerField()) def create(self, validated_data): categories = validated_data.pop('categories') attribute_values = validated_data.pop('attribute_values') product = Product.objects.create(**validated_data) for cat_id in categories: category = Category.objects.get(pk=cat_id) product.categories.add(category) for value_id in attribute_values: value = Value.objects.get(pk=value_id) product.attribute_values.add(value) product.save() return product class Meta: model = Product fields = ('id', 'name', 'description', 'price', 'quantity', 'categories', 'image', 'attribute_values') I am making post request with form data, as it contains image: var formData = new FormData() let cats = Object.keys(selectedCategories).map(id => Number(id)) formData.append('image', blob) formData.append('categories', cats) formData.append('attribute_values', attributes) formData.append('name', name) formData.append('description', description) formData.append('quantity', quantity) formData.append('price', 100) However, the server responds with this error: {"categories":{"0":["A valid integer is required."]},"attribute_values":{"0":["A valid integer is required."]}} How do i make the server accept the array of integers with the form data, as it seems for me that on the client side everything is correct. Thanks in advance. -
Django template multiple for loop
I have a tuple which holds multiple color and their codes: color_list = ( ('#CD5C5C', 'Indian Red'), ('#F08080', 'Light Coral'), ('#FA8072', 'Salmon'), ................ ) and this is the model: class ColorList(models.Model): color = models.CharField(choices=color_list, max_length=10) class Product(models.Model): color_list = models.ManyToManyField(ColorList) view: def product_details(request, pk): product = get_object_or_404(Product.objects.prefetch_related('color_list'), pk=pk) context = {'product': product,'color_list': dict(color_list)} return render(request, 'admin/product/product_details.html', context) Now I want to edit previously saved data in template using a form: <div class="form-group"> <label><strong>Color List</strong></label> <select name="color_list" class="form-control selectpicker" multiple data-live-search="true" > {% for key, value in color_list %} {% for pro_color in product.color_list.all %} <option value="{{ key }}" {% if pro_color.color == key %} selected {% endif %}> {{ value }} </option> {% endfor %} {% endfor %} </select> </div> I want to show previously selected color with other color options, but using this template code, it generating multiple duplicate <options>. So the problem is how can I use multiple for loop in template with preselected color <options> ? -
Django File Upload With Veritication Doesn't Work
I am creating a website where user can upload music files and it will be saved in a directory. So i added the following html form: <form action='upload/' method='POST' enctype="multipart/form-data">{% csrf_token %} <input type="file" name="file"> <input type="submit" name=""> </form> I've successfully configured the urls to handle this request. Here's the view that this url points to: def uploadMusic(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponse('Success') else: return HttpResponse('Could not verify') else: form = UploadFileForm() return HttpResponse('Failed') Plus, i want this music file to be validated before saving it to the directory. I want the file size to be lesser than 4mb. In my forms.py file, i have added the following codes: from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() def clean(self): file = self.cleaned_data.get('file', False) if file: if file._size > 4*1024*1024: return 'Error' else: return file else: raise forms.ValidationError('Wrong') Ok so the problem is, i cannot get this working. I get no errors but the file is successfully uploaded despite its file size. -
Is it better to use GenericAPIView or basic APIView while writing class based views (CBV) with Django Rest Framework (DRF)
I have been coding using django for the past year or so and most of my work was writing API's to connect to the React-based frontend. In most of my tutorials I see people using GenericAPIViews for the basics, but I don't find anything substantial for complicated code in APIs. So to deliver my code in time, I chose the easier solution that is to use APIView where I use less abstraction, have more control over my code (by writing more code) and understand clearly the functions of my code modules. What I'm concerned is that if I've chosen a shortcut by choosing not to learn how to use GenericAPIViews so that I can use it at its full potential. Some of the problems I faced while using GenericAPIViews or DRF in general. Custom permissions (e.g. I want a user who is authenticated and also have access with specific permission level (e.g can_do_xyz, or has_access_to_abc) Using writable serializers which might need to go through complex layers of business/app logic Creating entries for multiple models in the same GenericAPIView class function. For now, the problems I have faced in my approach to use basic APIView is that the swagger documentation I've … -
django get filename from uploaded file using formset
I'm trying to get the filename of an uploaded file, using formsets. views.py ... elif request.method == 'POST': albumform = AlbumForm(request.POST) photoformset = PhotoFormSet(request.POST, request.FILES) if albumform.is_valid() and photoformset.is_valid(): album = albumform.save(commit=False) album.user = request.user album.save() for photoform in photoformset: if photoform.is_valid() and photoform.has_changed(): # here is where I'm lost forms.py ... class AlbumForm(forms.ModelForm): class Meta: model = Album fields = ('title', 'description') PhotoFormSet = modelformset_factory( Photo, fields=('photo',), extra=4 ) photoform['photo'] doesn't give me the filename directly, rather something like <input type="file" name="form-0-photo" accept="image/*" id="id_form-0-photo"> which doesn't list filename I've tried photo = photoform.save(commit=False) print(vars(photo)) {'_state': <django.db.models.base.ModelState object at 0x000001F6326132E8>, 'id': None, 'album_id': 105, 'name': '', 'photo': <ImageFieldFile: phone.png>, 'photo_width': 600, 'photo_height': 416, 'thumbnail': '', 'status': '1'} and I see the name there, but there's gotta be an easier way to get to it. -
django application is not picking by nginx ec2 every thing run properlrey but page not loaded
this is my security groupenter image description here and sucessful nginx settingsenter image description here enter image description here please help me I am new in aws -
How to render bootstrap card image in fixed size in django template
I am trying to render bootstrap card on my home page. But the result i get from this is complete different something like this expected output my code {% extends "posts/base.html" %} {% block content %} <div class="container latest_post-wrapper py-1"> <div class="latest_post-title d-flex py-5"> <div class="d-flex flex-column mr-auto"> <h3>Latest</h3> <p>Lorem ipsum dolor sit amet.</p> </div> <div class="d-flex justify-content-end "> <a href="#">See More</a> </div> <div><!--latest_Post-title--> <div class="row py-3"> {% for post in latest_posts %} <div class="col-lg-4"> <div class="card p-2 shadow" style="width: 22rem;"> <img src="{{post.image.url}}" class="card-img-top" alt="..."> <div class="card-body"> <small class="text-muted h6">{{post.category}}</small> <blockquote class="blockquote"> <p class="mb-0">{{post.title}}</p> <footer class="blockquote-footer">written By<cite title="Source Title">{{posts.author}}</cite></footer> </blockquote> <hr/> <div class="d-flex flex-row py-0"> <small class="text-muted mr-auto">{{post.date_posted}}</small> <p><i class="fas fa-share-alt"></i></p> </div> </div> </div> </div><!--col-lg-4--> {% endfor %} </div><!--row-py-3--> </div><!--container.latest_post-wrapper--> {% endblock content %}} Anyone please help me to fix this. and one more thing size of the image is different I tried to give them size using css but its not working. I don't know why. -
Use javascript variable to give static file path in Django
I want to give static image file path from JavaScript in Django static tag. For quick example: imgPath = "uploads/imgs/abc.png"; document.getElementById("imgFile").src = "{% static '" + imgPath + "' %}"; //OR with jQuery $("#imgFile").attr("src", "{% static '" + imgPath + "' %}"); When I inspect that image element, it displays: <img src="/static/%20%2B%20imgPath%20%2B%20"> How to solve this? Thank you. -
Django: USE_TZ = False is not updating Postgres database setting
So I have some confusion regarding Use_Tz in Django. When the project was first started, USE_TZ was set to True, and we also had USE_I18N set to True. However, last week it was decided to set these settings to False. According to the docs here, Postgresql should be able to switch between True and False automatically depending the settings.py file. However, the date time fields in my tables show a timezone stamp of +01 at the end. Also, when I go into the database directly, using the command \d survey_server_app_activitylog, I see the following: date_reg | timestamp with time zone | All fields with date time show the same entry. But, I believe that they should be set as timestamp without time zone So, what gives? Am I totally interpreting USE_TZ = False incorrectly? Do I need to manually set the columns in the postgres database? -
Why task duplicates in all workers in rq-scheduler?
I am trying to set running the task by scheduler.cron in django project. I have two open rq-workers and the task runs in the both in the same time, but when I run it myself (not using scheduler) - that works ok - run just one of my workers. My code: import django_rq scheduler = django_rq.get_scheduler('default') scheduler.cron( "40 * * * *", # A cron string (e.g. "0 0 * * 0") func='jobparser.tasks.parse', # Function to be queued queue_name='default', ) What's my problem? -
ModuleNotFoundError: No module named 'easy_pdfwebpack_loader'
I am trying to make django-easy-pdf work I followed the instructions here: https://django-easy-pdf.readthedocs.io/en/v0.2.0-dev1/ This error appears when I run server when I put easy_pdf in INSTALLED_APPS If I am asking questions in the wrong place, please point me somewhere? -
want to know how to upload the image file and display it
I want to know how to upload and display the image. I do have the classes in views.py. class ArticleUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Article fields = ('title', 'body', 'image', 'source_url') template_name = 'article_edit.html' def test_func(self): obj = self.get_object() return obj.author == self.request.user class ArticleCreateView(LoginRequiredMixin, CreateView): model = Article template_name = 'article_new.html' fields = ('title', 'body', 'image', 'source_url') login_url = 'login' def test_func(self): obj = self.get_object() return obj.author == self.request.user def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) And the relevant classes in the models.py are like followings. class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) image = models.ImageField( upload_to='media/', null=True, blank=True) source_url = models.URLField(blank=True, null=True, max_length=300) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments',) comment = models.CharField(max_length=140) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE), def __str__(self): return self.comment def get_absolute_url(self): return reverse('article_list') The article_list.html file is: {% extends 'base.html' %} {% load static %} {% block title %}Articles{% endblock title %} {% block content %} {% for article in object_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold">{{ article.title }}</span> &middot; <span class="text-muted">by {{ article.author }} | {{ article.date }}</span> </div> <div class="card-body"> {{ article.body|linebreaks}} {% comment %} … -
GeoDjango Postgis requirements not satisfied getting error while running migrations?
I am using Postgresql database with django and have already installed in PostGis on it using CREATE EXTENSION PostGIS The gdal, proj.4 and geos are already installed in contrib.gis django package. As the documentation says they should be installed prior installing PostGis. Does that mean they should be installed on Postgresql database or something else. 1)Do I need to install them on postgresql database aswell? So far I have included in settings.py INSTALLED_APPS = [ . . 'django.contrib.gis', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '......', 'USER' : '.........', 'PASSWORD': '........', 'HOSTNAME': 'localhost', 'PORT': '5432', }, } But when I included this in models.py from django.contrib.gis.db import models as geomodels 2) I tried to run the migrations I am getting this error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL in stalled? If it is, try setting GDAL_LIBRARY_PATH in your settings. I am not sure what should I fix to run the migrations and If this error is related to database or django 3)Do I have install the Gdal, Geos and proj on both django and postgresql? -
Upload, Process & Download using Django
I'm new with using django and I'm planning to use it to upload a file then output the result after processing. In my views.py, it's telling me that there's a problem with returning a dataframe that I'm trying to convert into .csv When attempting to upload a file from html, it's redirecting me to this error. 403 Forbidden: CSRF verification failed. Request aborted. views.py from django.shortcuts import render from .config import UPLOAD_DIR import os import pandas as pd #File extension checker def read_data(data_input, **kwargs): #dictionary of file formats read_map = {"xls": pd.read_excel, "xlsm": pd.read_excel, "xlsx": pd.read_excel, "csv": pd.read_csv} #getting the file extension extension = os.path.splitext(data_input)[1].lower()[1:] #check if file extension and document upload validation assert extension in read_map assert os.path.isfile(data_input) def upload(request): if request.method == "POST" and request.FILES["data_file"]: if "data_file" not in request.FILES: return render(request, 'qwe/form.html') data = request.FILES["data_file"] if data == "": return render(request, 'qwe/form.html') #uploads the data in the specific directory os.path.join(UPLOAD_DIR, data) # TO-DO DATA PROCESSING HERE #Error: Assigning to function call which doesn't return df = read_data(data) return df.to_csv("asd.csv") else: return render(request, 'qwe/form.html') form.html <!DOCTYPE html> <html> <body> <h1>Place holder</h1> <h4> Please upload your training data here. </h4> <h5> Note: Please wait for the algorithm to finish … -
Can't seem to deploy because of package loading problem
I am unable to deploy my app on pythonanywhere because of the following error when I try to migrate my databases. The app installs and works on local, but when I try run in pythonanywhere bash shell to build the dbs: `./manage.py migrate` I get the following error. I'm not sure how to fix it: app_config = AppConfig.create(entry) File "/home/username/.virtualenvs/new_app-virtualenv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/username/.virtualenvs/new_app-virtualenv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_tables2' Please help, any advice will be appreciated. -
How to save the information of a form so that it appears in the Admin Site Panel?
I am making a web page and there is a contact section in which I am looking for people to leave a message and then I contact them, I want the information entered in the form to be stored in the database so that later I can see it in the Django Admin Page. # models.py from django.db import models class Contact(models.Model): name = models.CharField(max_length = 100, verbose_name = "Nombre") email = models.CharField(max_length = 100, verbose_name = "Email") issue = models.CharField(max_length = 200, verbose_name = "Asunto") text = models.TextField(verbose_name = "Mensaje") # forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length = 100, label = "Nombre") email = forms.EmailField(label = "Correo electrónico") issue = forms.CharField(max_length = 200, label = "Asunto") text = forms.CharField(label = "Mensaje") # views.py from django.views.generic import TemplateView from contact.forms import ContactForm from django.shortcuts import render class Contact(TemplateView): template_name = 'contact/contact.html' def get(self, request): form = ContactForm return render(request, self.template_name, {'form': form}) def post(self, request): form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] issue = form.cleaned_data['issue'] text = form.cleaned_data['text'] form = ContactForm() args = { 'form': form, 'name': name, 'email': email, 'issue': issue, 'text': text, } return render(request, self.template_name, args) <!-- And this … -
Django how to get first 10 characters of a TextField as a string?
Please pardon my question, I am a beginner in Python and Django. I have a class Response here, which inherits from models.Model. One of the fields is response_content, a TextField. I have a function __str__ which is supposed to return a string representation of the object. The first part of this string is that object's id, then a space separator, then the field self.author_name, then a pipe separator, then after that I want to display the first 10 characters of the self.response_content as a string. I do not want to dump the whole self.response_context into the string, because this is a TextField with max_length=4000, so it can get very big! I want to have just the first 10 characters of this field to be displayed as a string, so that I can just look and immediately remember what was the rest of the response_content from these displayed characters. That is how I can tell apart individual Responses. I want to replace the ??? with the necessary expression. I do not yet know the syntax well enough, so please don't hate me for asking this question. This is my models.py file: from django.db import models # Create your models here. class … -
error saving photo in database 'NoneType' object has no attribute 'user'
I have a model with Usuario where the profile foto goes and it saves perfectly in the database, so to be able to add more images as if it were a gallery, I created another model called Gallery, I copied the same specificiation of what was already working in the model Usuario, however he is not saving the photos in the database, and I do not know where I am going wrong. I appreciate any help. and I need the Gallery model to receive the foreign Usuario key Erro: Traceback: /handlers/exception.py" in inner 34. response = get_response(request) core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) views.py" in gallery_novo 75. form.save() forms.py" in save 150. form.usario_id = self.request.user Exception Type: AttributeError at /gallery-novo/ Exception Value: 'NoneType' object has no attribute 'user' views.py def gallery(request): gallery = Gallery.objects.all() form = GalleryForm() data = {'gallery': gallery, 'form': form} return render(request, 'gallery.html', data) def gallery_novo(request): if request.method == 'POST': form = GalleryForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('sistema_perfil') else: form = GalleryForm return render(request, 'gallery.html', {'form': form}) models.py class Usuario(models.Model): nome = models.CharField(max_length=50, blank=False) sobrenome = models.CharField(max_length=50, … -
django 502 while deployment
I was trying to deploy a Django web app to Digital Ocean following this gist which is written based on a tutorial from digital ocean themselves and everything seem to be working perfectly fine until its time to setup Nginx. I follow it exactly every time and it always sends me a 502 Bad Gateway message. -
MultiValueDictKeyError Django at /student_form
I am new to Django, I have created a model and trying to post data from the front end. following is my view.py def studentForm(request): userProfile = StudentProfileForm.objects.create(FirstName=request.POST['userFirstName'] LastName=request.POST['userLastName'], GreScore= request.POST['userGreScore'], IELTSTOEFL=request.POST['userIeltsToefl'],WorkEx=request.POST['userWorkEx'],ResearchDone=request.POST['userResearch']) userProfile.save() return render(request,'register/bg-pages.html') Following is my model class StudentProfileForm(models.Model): FirstName = models.CharField(max_length=255) LastName = models.CharField(max_length=255) GreScore = models.IntegerField() IELTSTOEFL = models.IntegerField() WorkEx = models.IntegerField() ResearchDone = models.IntegerField() Error is following Request Method: GET Request URL: http://127.0.0.1:8000/student_form Django Version: 2.1.5 Exception Type: MultiValueDictKeyError Exception Value: 'userFirstName' Exception Location: C:\Users\AB\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in getitem, line 79 Python Executable: C:\Users\AB\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.1 Python Path: ['D:\AB\UOR_everything\semester_2(winter_2019)\Software_Engineering\login_registration', 'C:\Users\AB\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\AB\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\AB\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\AB\AppData\Local\Programs\Python\Python37-32', 'C:\Users\AB\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\AB\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Server time: Sun, 10 Mar 2019 00:35:51 +0000 -
Uncaught TypeError: $.ajax is not a function | While using most recent complete jQuery version
I am trying to get some AJAX functionality to work on my webpage and I am quite new to javascript. I decided to use jQuery as a framework in combination with Django. But I have encountered an error: $.ajax() is not a function. I tried to fix the bug by downloading and referencing the jQuery code in multiple ways and multiple versions, but I can't seem to fix it, can somebody help me? My reference to the JQuery script the head section of my html file, downloaded from https://code.jquery.com/jquery-3.3.1.js <!-- JQuery --> <script type="text/javascript" src="{% static 'home/jquery.js' %}"></script> The file is in my myapp/static/myapp folder, I checked console and it does find the file. My ajax call: {% block javascript %} <script type="text/javascript"> function finishedbutton(pk) { $.ajax({ url: 'task/mark/', data: { 'taskid': pk }, dataType: 'json', success: function (data) { if (data.finished) { alert("SET AS FINISHED") } else { alert("SET AS NOT FINISHED") } } }); }; </script> {% endblock %} My button in my html file calling the function: <button onclick="finishedbutton( '{{task.pk}}' )"> <div class="taskbutton text-center"> Fini </div> </button> Task.pk is the id number of a model that I am using in my html file. The idea of the …