Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django templating: extend a block in same template?
So here is the set up (simplified for here): In my template file I have two sections I would like to add content too by looping of a list of dictionaries, e.g.: <div class="stuff-a"></div> <div class="stuff-b"></div> {% for thing in list %} <!-- goes into div a --> <!-- goes into div b --> {% endfor %} I thought this would work: <div class="stuff-a"> {% block diva %}{% endblock %} </div> <div class="stuff-b"> {% block divb %}{% endblock %} </div> {% for thing in list %} {% block diva %} thing.stuff_for_div_a {% endblock %} {% block divb %} thing.stuff_for_div_b {% endblock %} {% endfor %} and then django complains about me using each block more than once - shame on me. Now the solution to this (keeping the same schema) is to make an intermediate template file and then extend it. My question is, is there a way to append to different specific areas in a django template without having to loop through a list twice or an intermediate template file? This matters if the loop is somewhat complicated and you dont want to have to update two loops whenever you make a change. When might this occur in practice … -
PIL - saving image as .jpg not working
I'm trying to overwrite save() method of the model to resize images. Every format works, except when saving a .jpg image. It's not saving images with .jpg extension. I read the Pillow documentation and there's no JPG format. class Business(models.Model): photo = models.ImageField(_('photo'), storage=OverwriteStorage(), upload_to=image_upload_to, blank=True, null=True) def save(self, **kwargs): """ Changing dimensions of images if they are to big. Set max height or width to 800px depending on the image is portrait or landscape. """ # Opening the uploaded image im = Image.open(self.photo) print(im) output = BytesIO() # set the max width or height im.thumbnail((800, 800)) # find the ext of the file ext = self.photo.name.split('.')[1].upper() if ext in {'JPEG', 'PNG', 'GIF', 'TIFF'}: # after modifications, save it to the output im.save(output, format=ext, quality=100) output.seek(0) # change the imagefield value to be the newley modifed image value self.photo = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.photo.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(User, self).save() I don't know what I am missing here. And what's the best way to do this on a custom User model. Using a signal, overwriting ImageField or ... Any help is appreciated :) -
django haysteck FacetedSearchView returning empty results?
I'm using Django haystack FacetedSearchView my views.py: from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView class FacetedSearchView(BaseFacetedSearchView): template_name = 'test.html' facet_fields = ['source'] and in urls.py: url(r'^search', FacetedSearchView.as_view(), name='haystack_search') and in test.html I'm printing the facets. when I issue request as follow: 127.0.0.1:8000:/search the content of the factes context object is empty dict. but I think it should return all the I specified facets in facets_fields, and when I append q parameter to the request's querystring (with any value) it returns result but with zero document. is it neccessary to provide the q parameter? and with which value? -
Django Get None After User Authentication
def login_page(request): form = LoginForm(request.POST or None) context = { "form" : form } print("User logged in") print(request.user.is_authenticated()) if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username = 'username', password = 'password') print(user) if user is not None: print(request.user.is_authenticated()) login(request, user) # Recirect to a success page. # context['form'] = LoginForm() return redirect("/contact") else: # Return an 'invalid login' error message. print("Error") return render(request, "auth/login.html", context) I try to create a login page but I get value of 'user' None so I took error everytime. I use Django 1.11. -
Django - Raise form error without cleaning data
Is there any way in django to raise a form validation error without cleaning the data? I am fetching the data through form['field'].value(), and I want to show the error in the template if it is beyond a certain value. -
how to display information entered by a user into a django model in the User profile
i'm kinda new to django, i'm working on a project currently. its a website where people can look for houses to rent. users will be able to create accounts, search for houses to rent and create listings about the houses they want to rent out. i created a model to save all the information about houses that users want to rent out. i need to filter this information and display each users listing on their profile. ive searched online but no solution yet. Really need help. models.py from django.db import models from django.contrib.auth.models import User class Myhouses(models.Model): Available = 'A' Not_Available = 'NA' Availability = ( (Available, 'Available'), (Not_Available, 'Not_Available'), ) name_of_accomodation = models.CharField(max_length=200) type_of_room = models.CharField(max_length=200) house_rent = models.IntegerField() availability = models.CharField(max_length=2, choices=Availability, default=Available,) location = models.CharField(max_length=200) nearest_institution = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to='profile_image') author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='author') def __str__(self): return self.name_of_accomodation view.py class ListingByUser(LoginRequiredMixin, generic.ListView): def get( self): model = Myhouses template_name ='houses/ListingByUser.html' paginate_by = 10 def get_queryset(self): return Myhouses.objects.filter(author=self.request.user) urls.py from django.conf.urls import url, include from . import views from django.contrib.auth.models import User urlpatterns = [ url(r'^addlisting/$', views.addlisting, name='addlisting'), url(r'^mylisting/', views.ListingByUser.as_view(), name='ListingByUser') ] template {% for houses in myhouses_list %} {{ houses.name_of_accomodation … -
Django: how to display ProductImage from Product model
class Product(models.Model): company = models.ForeignKey('Company', on_delete=models.SET_NULL, null=True) class ProductImage(models.Model): product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) image_path = models.ImageField(max_length=255,null=True,blank=True,upload_to='images/%Y/%m/%d') in my views.py class HomeView(ListView): template_name = "catalog/product_list.html" context_object_name = 'product_list' model = Product in product_list.html {% if product_list %} {% for product in product_list %} <!-- the problem is here --> if there is an image show <img src="default" /> else <img src="product.ProductImage.image_path here" /> {% endfor %} {% endif %} the problem is in the iteration of the product_list i tried, productImage = product.[productImage or product_image or is it productimage].first() but it doesn't work i also tried {% img = '' try: productImage = product.productimage_set.first() img = productImage.image_path except ProductImage.DoesNotExist: img = '' %} <img class="card-img-top" style="height: 225px; width: 100%; display: block;" src="{{product_image.image_path}}" data-holder-rendered="true"> {% %} but it just outputs the code block -
Can't display database data in Django
I am working on library website in which I want to display data from database which is Book name and description. But i'm not ale to do that here is my code views.py from django.shortcuts import render from .models import * def index(request): book_list = Book.objects.all() return render(request,template_name='index.html', context={'book_list':book_list}) index.html {% extends "base_generic.html" %} {% block new_books %} {% for b in book_list %} <div class="card"> <img class="card-img-top" src=".." alt="Image"> <div class="card-body"> <h5 class="card-title">{{ book_list }} </h5> <p class="card-text">Hello this is card text</p> <a class="btn btn-primary">View this book</a> </div> </div> {% endfor %} {% endblock %} -
Django: How do I return data from db along with the foreign key entities to the user as JSON?
I have two models as such, class Foo(models.Model): name = models.CharField(max_length=100, unique=True) city = models.CharField(max_length= 50) .... and class Bar(models.Model): Foo = models.ManyToManyField(Foo) name = models.CharField(max_length=20, unique=True) I have a view that returns Foo objects as JSON, def list_by_city(request, city): foo_list = Foo.objects.filter(city=city).values() return JsonResponse({"Foo": list(foo_list)}) But this returns only the attributes from Foo. I want to add the attributes from Bar as well, which are related to Foo. How do I do that? -
Saving model Formset
This is a quicky. I have a formset based on a model. I am trying to save it on a POST request as follows: . . . if request.method=='POST': FormsetItem=ItemFormSet(request.POST,queryset=Item.objects.filter(budgetcatagory__user_id=U.id)) FormsetCat=CatFormset(request.POST) if FormsetItem.is_valid(): FormsetItem.save() . . . Since this isn't working, i.e. my database remains unchanged after save, I'm assuming this is not the way to go about it. Do I have to individually save each form in the set? Thanks -
Takes very long for an image/video to be uploaded to my Amazon S3 media directory
So I'm using Amazon S3 storage to store user-uploaded files. When a user makes a post on my Django website, it comes with some text and an image/video - that image/video gets uploaded to the media directory on my S3 bucket. However this takes very long, e.g. including a 6mb image in the post will take the post over a minute to submit. If the image is small e.g. 150kb it will only take about 3 seconds for the post to submit. How can I improve this performance? The Post is simply a form with the following fields (image is either an image or a video): class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=95) date = models.DateTimeField(auto_now_add=True) content = models.TextField(null=True, blank=True) image = models.FileField(null=True, blank=True) and the views: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect('/home/') else: form_post = PostForm() context = { 'form_post': form_post, } return render(request, 'post/post.html', context) else: return HttpResponseRedirect("/accounts/signup/") Any idea? -
Using array elements as relative URLs in a django template
I am totally new to django, and have been struggling with the following issue for a while. I am sending a sorted list of lists to a template from views.py to a template, in which each sublist (containing two elements) should be displayed. I would like the first element to be a link, in such a way that the String content should be the relative URL to be displayed. So I used the following syntax: <a href="{% url {{user.0}} %}">{{user.0}}</a> but it gives me the following error: TemplateSyntaxError at /app/best_travelled/ Could not parse the remainder: '{{user.0}}' from '{{user.0}}' Please find below the relevant code snippets: views.py: def best_travelled(request): trips = Trip.objects.all() user_trips={} for trip in trips: user_trips[trip.owner] = user_trips.get(trip.owner,0)+1 user_list = [] for key, value in sorted(user_trips.items(), key = itemgetter(1), reverse = True): user_list.append([key, value]) context_dict = {'user_list':user_list} return render(request,'best_travelled.html',context_dict) Template: <html lang="en"> <head> <meta charset="UTF-8"> <title>Most Recent Trips - Travelmate</title> </head> <body> <h1>Best-Travelled</h1> <div> {% if user_list %} <ol> {% for user in user_list %} <a href="{% url {{user.0}} %}">{{user.0}}</a> <li>{{user.0}}, Number of trips: {{user.1}}</li> {% endfor %} </ol> {% else %} There are no travellers yet! This is your chance to become the very first one! <br /> … -
How can I put a ForeignKey field in alphabetical order?
this is my code. models.py class Preventivo(models.Model): prestazione1 = models.ForeignKey('Prestazione',on_delete=models.CASCADE, related_name="prestazione1") form.py class PreventivoForm(forms.ModelForm): class Meta: model = Preventivo fields = ['cliente','prestazione1'] -
Django Model field validation vs DRF Serializer validation
The validation process can happen in 'Django Model level field declaration' or in 'Deserialization of data on DRF serialization section'. I have following concerns regarding this validation process: What is the separation of concerns? Which validation section should be placed where? Do we still need Model validation while we have validation on DRF serialization section? If yes, why? How the DRF serialization section restrict manual database entry with the validation? -
Django Admin UI becomes smaller
I'm sure I did not do any changes to the admin html codes. The recent actions is no longer at the left position. Any idea what I might have changed to cause this problem? -
Error connecting Python with MySQL
I received a python project and I'm having trouble running its requirements, particularly anything to do with MySQL. Whenever I run pip install mysqlclient, I get 13 warnings and this error in red. Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-eBsQYy/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-sxHiel-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-eBsQYy/mysqlclient/ When I run pip install mysql-python I get 14 warning with a similar error in red. Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-build-qW79lT/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-13maVa-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-build-qW79lT/mysql-python/ Any ideas? -
Django - how to best integrate matplotlib
I am trying to display a graph using matplotlib and django. I've read quite a lot of questions on stack but still don't understand what the best way is to use matplotlib in Django. SITUATION: I have a model that has a bunch of data in. In views.py I then have a simple form that captures some data and queries the model and returns a subset of the data. Here is the relevant views.py section: def getinput(request): if request.method == 'POST': form = get_data(request.POST) if form.is_valid(): down = form.cleaned_data['get_down'] ytg = form.cleaned_data['get_ytg'] yfog = form.cleaned_data['get_yfog'] map_data = next_play.objects.filter(last_dwn__exact=down, last_yfog__exact=yfog, last_ytg__exact=ytg) context = {'form': form, 'query_data': map_data} return render(request, 'play_outcomes/output.html', context) else: form = get_data() return render(request, 'play_outcomes/getinput.html', {'form': form}) When I got to play_outcomes/getinput and enter dwn ytg yfog the template then outputs a whole ton of data. It is this data I want to plot i.e., the data in map_data. QUESTION: How do I integrate matplotlib into this? Do I integrate the matplotlib code in views.py, should I set it up in a separate python module? Presumably I need to create a png file and then show that? -
How I make a Calender app in Django using models?
I am working on my very first own project in Django and Backend Development in general. I am trying to build a Calendar app which show a weekly timetable for each room. The code below is my database models. Is there anything I need to change or any different way to buid a Calendar as I described? Thank you! from django.db import models # Create your models here. class Block(models.Model): block_id = models.CharField(max_length=10) class Room(models.Model): block = models.ForeignKey(Block, on_delete=models.CASCADE) room_id = models.CharField(max_length=10) class Lesson(models.Model): number = models.IntergerField() room = models.OneToOneField(Room, on_delete=models.CASCADE) start = models.DateTimeField("Start Time") end = models.DateTimeField("End time") occupied = models.BooleanField(default=False) -
Error Creating Multiple Containers with multiple Django projects
How to run multiple Django Projects as individual containers. docker-compose.yml web1: build: ./test1 expose: - "8000" links: - postgres:postgres volumes: - /usr/src/app - /usr/src/app/static command: python manage.py runserver 0.0.0.0:8000 web2: build: ./test2 expose: - "3000" links: - postgres:postgres volumes: - /usr/src/app - /usr/src/app/static command: python manage.py runserver 0.0.0.0:3000 postgres: image: postgres:latest ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ My Project Structure looks like this. ├── docker-compose.yml └── test1 | ├── Dockerfile | ├── test1 | ├── manage.py | ├── requirements.txt └── test2 | ├── Dockerfile | ├── test2 | ├── manage.py | ├── requirements.txt This structure throws errors that file manage.py does not exist. Basically, the command is not looking for the file inside the folder. I started from this Link - Dockerizing Django. -
ModuleNotFoundError: No module named 'yoursite'
I'm relatively new to both Python and Django, and I've had an app developed by someone else. I'm trying to write a script which automatically opens an SSH Tunnel and runs a command from my local machine to my remote postgres database so that I can do a parse locally - this is normally done from the terminal by typing python manage.py parse. This has worked previously when I have run a manual SSH tunnel but now want to set it up to run in a script and close the connection automatically. My script is currently set as below: import psycopg2 import sshtunnel from django.core.management import execute_from_command_line sshtunnel.SSH_TIMEOUT = 5.0 sshtunnel.TUNNEL_TIMEOUT = 5.0 with sshtunnel.SSHTunnelForwarder( ('ssh.pythonanywhere.com'), ssh_username='ssh_username', ssh_password='ssh_password', remote_bind_address=('username2.postgres.pythonanywhere-services.com', port) ) as tunnel: params = { "dbname": 'dbname', "user": 'user', "password": 'password', "host": 'host', "port": tunnel.local_bind_port, } connection = psycopg2.connect(**params) cursor = connection.cursor() execute_from_command_line(["manage.py", "parse"]) cursor.close connection.close() I'm now getting the error below when I run the script (which is located in the root file of my app): /home/user/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most … -
Is it suitable to delete my log.django file?
My log.django file is over 100,000 lines now. If I delete it, will it be re-generated again? It exists because I have LOGGING in my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.django', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } -
Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?
I have my main home template, that I would like to extend one of two sets of headers from but I am getting an error that seems to indicate the else does not work in this statement. I also tried changing to an elif for when user is not logged in and the elif was shown as undefined. These are the first lines of code in the file so there aren't other things loaded prior to these either. The problem code: {% if user.is_authenticated %} {% extends "main/header.html" %} {% else %} {% extends "landing/header.html" %} {% endif %} Is the extend not allowed to be conditionally added? If so is there a correct way of doing it? -
In ModelAdmin, how do I get the object's previous values when overriding `save_model()`
When overriding ModelAdmin.save_model(), I want to be able to run some calculations between the object's new values vs its old ones. Is there any way that I can get the "old object" with all its previous data before the change? For example, if I have an Object with obj.name = "foo" that I update via the Django admin app to now be obj.name = "bar", upon saving the following code should print out accordingly: from django.contrib import admin class ObjectAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): old_object = self.get_old_object() print(old_object.name) # Should print out "foo" print(obj.name) # Should print out "bar" -
Exception Value: 'many' is an invalid keyword argument for this function
, Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function, Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function,Exception Value: 'many' is an invalid keyword argument for this function views.py from django.shortcuts import render from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from student.models import Student from student.serializers import StudentSerializer @api_view(['GET', 'POST']) def Student_list(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': snippets = Student.objects.all() serializer = Student(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = Student(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'PUT', 'DELETE']) def Student_detail(request, pk): """ Retrieve, … -
What is the namespace and app name for django auth urls?
I am using the Django built-in auth function. path('account/', include('django.contrib.auth.urls')), When I try to reference it using {% url 'password_reset' %} as seen in the Django code. I get an error. How do I reference it? There doesn't seem to be any namespace or app_name in the Django source. The answers on stack overflow are either outdated or require you to manually rebuild the URL one by one and reference it.