Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SearchForm is not shown in category.html
SearchForm is not shown in detail.html. I wrote in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] form = SearchForm() return render(request,'top.html',{'content':content,'form':form}) class DetailView(generic.DetailView): model = Detail template_name = 'detail.html' form = SearchForm() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context in category.html <div class="search_box"> <form action='/app/search/' method="POST"> <table> {{ form.as_table }} </table> <button class="btn btn-secondary search" type="submit">SEARCH</button> {% csrf_token %} </form> </div> div> <h2>{{ object.title }}</h2> <a href="{% url 'detail' content.pk %}">SHOW DETAIL</a> </div> I think if I wrote DetailView class like top method which is return render(request,'top.html',{'content':content,'form':form}),I can show SearchForm() in detail.html.But DetailView class is generic view, so i cannot understand how I can read SearchForm() in DetailView class.I wrote context['search_form'] = SearchForm() but form is not shown.How should I fix this?What is wrong in my codes? -
Django - How to save files to STATIC_ROOT from views?
I have made a Django app that takes arguments from the form and makes an image using Pillow. views.py: file_name = "{}.png".format(random.randint(1, 255)) image1.save(file_name) pretty simple stuff, right? Now when I try to render that image with HttpResponse as: return HttpResponse("<img src='" +file_name + "' alt='image here'>") apparently, it will throw an error. Can you please tell me what to do in order to save it properly and show in HttpResponse? Django==1.11.8 Pillow==5.0.0 Python 3.6.2 Thank you! -
OSError: [Errno 22] Invalid argument: "C:\\xxxx\\xxx\\xxx\\{'query'
I am working on a Django project from my laptop that runs Windows 10. I've set the environment with pip install and everything seems to work fine, since, for example, python manage.py migrate working properly. The server starts fine with python manage.py runserver, however, when I open the URL http://127.0.0.1:8000/restaurants in my browser I get the following error: OSError at / [Errno 22] Invalid argument: "C:\\xxxxx\\xxxxx\\templates\\{'query': <QuerySet [<RestaurantModels: BIS>, <RestaurantModels: Sangam>, <RestaurantModels: IBIS>, <RestaurantModels: CCR>]>}" Request Method: GET Request URL: http://127.0.0.1/ Django Version: 1.11.7 Exception Type: OSError Exception Value: [Errno 22] Invalid argument: "C:\\xxxxx\\xxxxx\\templates\\{'query': <QuerySet [<RestaurantModels: BIS>, <RestaurantModels: Sangam>, <RestaurantModels: IBIS>, <RestaurantModels: CCR>]>}" Exception Location: C:\Users\fly\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loaders\filesystem.py in get_contents, line 28 Python Executable: C:\Users\fly\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.4 Python Path: ['C:\\xxxxx\\xxxxx', 'C:\\xxxxx\\xxxxx', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2017.3.1\\helpers\\pycharm_matplotlib_backend'] Here is the View, Model, Template of my project view.py template.py Kindly let me know what is causing this? I am sure it's not the code. -
What is the proper process for validating and saving data with with Django/Django Rest Framework regardless the data source?
I have a particular model that I'd like to perform custom validations on. I'd like to gaurantee that at least one identifier field is always present when creating a new instance such that its impossible to create an instance without one of these fields, though no field in particular is individually required. from django.db import models class Security(models.Model): symbol = models.CharField(unique=True, blank=True) sedol = models.CharField(unique=True, blank=True) tradingitemid = models.Charfield(unique=True, blank=True) I'd like a clean, reliable way to do this no matter where the original data is coming from (e.g., an API post or internal functions that get this data from other sources like a .csv file). I understand that I could overwrite the models .save() method and perform validation, but best practice stated here suggests that raising validation errors in the .save() method is a bad idea because views will simply return a 500 response instead of returning a validation error to a post request. I know that I can define a custom serializer with a validator using Django Rest Framework for this model that validates the data (this would be a great solution for a ModelViewSet where the objects are created and I can guarantee this serializer is used … -
Django model fields not appearing in admin
I have a relatively simple model in my Django project (I should note that the wording is weird in that the app itself is called 'games' and within it the model is Game but I'll change this later): from django.db import models class Game(models.Model): player_turn = models.IntegerField(), game_state = models.BooleanField(), rolled = models.BooleanField(), rolled_double = models.BooleanField(), last_roll = models.IntegerField(), test_text = models.CharField(max_length = 200), with a settings.py file in the main folder of the project showing INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'games.apps.GamesConfig', ] and games/admin.py looks like this from django.contrib import admin from .models import Game admin.site.register(Game) When I try to run 'python3 manage.py makemigrations' it shows that no changes are detected (even if I arbitrarily change the Game model to test the effect) and when I go into the admin site to add a new game there are no fields available to edit like there are for the User and Group models. The model itself shows up in the admin site but without any fields. Right now I'm following along the MDN Django tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Models) and it seems like I'm following all of the necessary steps so can someone let me know what I might … -
Selenium on Chrome drive running on server as a part of website is in-excessable to clients on there windows PC
I am unable to understand this technicality. Or how to go about it. During development of a Django website on my local machine, I included selenium(with chromedriver) for a functionality. Where the user enters a data on the website and clicks a button which triggers selenium method to open a page, then the user makes his choice which causes the selenium to scrap off the data and quit the driver. And take the scrapped up data as one of the semi-auto-filled form entries on the website. All this worked fine with Chrome drivers path present on my local machine. But when I shifted the website to production on the server and uploaded the chrome drive along with the website as well, giving drivers proper path name on the server machine. I am unable to get the driver working on remote client window machines when I access the website. How can I get the same functionality as in during development in local machine for remote clients as well? -
How am I supposed to render timezone-aware model field with local time setting in django
Let's say I had the following code # settings.py in a proper location ... TIME_ZONE = 'Asia/Seoul' USE_TZ = True # models.py in a proper location class Post(models.Model): created = models.DateTimeField(auto_now_add=True) def created_formatted(self): return self.created.strftime("%Y/%m/%d %H:%M") Then, I rendered the following django template to html before formatting: {{ a_post.created }} # localtime after formatting: {{ a_post.created_formatted }} # not localtime I expected both {{ a_post.created }} and {{ a_post.created_formatted }} have the same timezone, but they don't. I tried to find out how {{ a_post.created }} is rendered to localtime but I'm not sure which part of the django code is the right place to look for yet. (It will be really helpful if you let me know the right part of the django source code to look for). I want to apply the same idea to my created_formatted after I find how the rendering of datetime works. -
Django orm. Nested tables
I need to create table like this: Event Table id Event 1 event A -> Time Param 1 Param 2 .. 44 12.5 145 45 14.5 148 46 13.5 138 2 event B -> Time Param 1 Param 2 .. 44 12.5 145 45 14.5 148 46 13.5 138 3 event C - > And so on... .. How can I do this with Django ORM? (Use SQLite) -
How can i combine Djagno with parcel in a django project?
I have been able to use webpack in a django,but now I want to use parcel in a django project, the question is how to use parcel in a django project like webpack ? -
Django- template loop but exclude repeats
Say I have this data and I'm passing to my template: apps = [ {category: 'one'}, {category: 'one'}, {category: 'two'}, {category: 'two'}, {category: 'three'} ] Then in my template I want to add one div withe the id 'category' but not repeat any divs if they've been added before with the id. So something similar to: {% for app in apps %} <div id="{{app.category}}"></div> {% endfor %} But I only want these to be rendered: <div id="one"></div> <div id="two"></div> <div id="three"></div> -
Django urls pattern ordering
Does anyone know of a better way to randomly order models instances when showing them? I'm going to have a lot of instances returned and I'm not trying to kill my server with order_by('?') -
Unable to upload image files to S3 bucket from Heroku hosted Django project with boto3
I have a Django project where entertainers register and part of the process is to upload a profile image as well as up to 5 gallery images. My project is hosted on Heroku and static and media files are stored in an S3 bucket. This is my first time using s3 buckets so I have granted as much access as possible to try to get it to work I am trying to dynamically generate the location of the images based on the title of the entertainer so my entertainer/models.py is set up as follows: def profile_image_path(instance,filename): upload_dir = os.path.join('profile/', instance.title) if not os.path.exists(upload_dir): os.makedirs(upload_dir) return os.path.join(upload_dir, filename) def img1_image_path(instance,filename): upload_dir = os.path.join('img1/', instance.title) if not os.path.exists(upload_dir): os.makedirs(upload_dir) return os.path.join(upload_dir, filename) title = models.CharField( max_length = 15 ) profile_image = models.ImageField( upload_to = profile_image_path, default = 'no_image.png' ) image1 = models.ImageField( upload_to = img1_image_path, default = 'no_image.png' ) etc The idea is that images will get stored in the S3 bucket as follows: media/profile//profile.jpg media/img1//img1.jpg media/img2//img2.jpg etc However when I register an entertainer I can see on the heroku database as well as the interface of my app that the default image is being used instead of what I upload. The … -
Using a python file as a database
I'm an intermediate python developer with quite a bit of experience working with t-sql/mysql in data analytics. I'm trying my hand at some web programming using python to build certain components of the back-end of my site. In one of my applications, instead of querying a database, I've placed some dictionary-based data structures directly in a list in a python file, and I import it into the script that holds the application logic. Important to note that this data is static and around 5k dictionaries at this point. The data itself contains key-value pairs where the values is frequently a list of a tuple, so I find the flexibility of the python data structure to be easier to work with than a traditional RDBMS table. I've scoured the internet and I can't seem to find any reference to developers actually using a .py file to store data for use in their programs, which leads me to believe this method shouldn't be used in a production site. I'm hoping for some clarity around why this might be the case (and potential alternatives) Will my .py solution scale poorly vs a RDBMS solution? Either as the number of users using my application … -
Forms correctly outputs TreeNodeMultipleChoiceField queryset, but raises ValidationError: Select a valid choice
I’m trying to implement dynamic forms based on django formtools WizardView. In one of the steps the user can choose multiple choices from MPTT models. In the subsequent steps, for every user’s choice there is a form to choose description (simple TextField model with MPTT model as parent) using RadioSelect widget. The forms, which I’ve written, correctly finds and outputs models relating to relevant parent MPTT objects in each choice, but raises ValidationError and forces to use default Textarea widget. Please help. form.errors.as_data() prints: {'description': [ValidationError([u'Select a valid choice. That choice is not one of the available choices.'])]} My code: Models class FunctionalAnalysis(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) title = models.CharField( max_length=200, default="") contribution_type = models.IntegerField( choices=CONTRIBUTION_TYPES, # set of tuples blank=True, null=True) @property def root(self): return self.get_root().title class ContributionDescription(models.Model): functionalanalysis = TreeForeignKey( FunctionalAnalysis, verbose_name='Choose function to describe:') description = models.TextField( max_length=500, default="", verbose_name='Description') # other fields Form #1 - form for choosing parent model, working fine class ChooseFunctionForm(forms.ModelForm): funct_title = TreeNodeMultipleChoiceField( queryset=FunctionalAnalysis.objects.filter( level=2, contribution_type=1, ), level_indicator=u'', label="Choose function:", required=False, widget=forms.CheckboxSelectMultiple() ) class Meta: model = FunctionalAnalysis fields = ['funct_title'] Form #2 - the problem class ChooseFunctionDescriptionForm(GetChoicesFromKwargsMixin, GetObjectOrNoneMixin, forms.ModelForm): class Meta: model = ContributionDescription fields = ['description'] def … -
How to make a large variable global in Django?
I am working on a simple web application that utilizes a moderately large NLP model, which is the same for all users and ideally I hope to re-load the model from a new model file generated daily. Is there a way to make the variable storing this model to be global? Loading it from a file every time a user uses it would be quite slow and it seems to be too large (~1GB) to be put into sessions. Thank you! -
What gets deleted when I delete a model in django (postgress)?
Lets say I have a model Books: class Books(models.Model): name = models.Charfield() author = models.Charfield() and later I set up another model called BookReviews which links to Books: class BookReviews(models.Model): book = models.ForeignKey(Books) content = models.TextField() But I messed up and I want to delete model BookReviews completely. When I run python manage.py migrate I get a warning message: Any objects related to these content types by a foreign key will also be deleted. Are you sure you want to delete these content types? Does that mean any entries linked to in Books will also be deleted even if those entries existed before BookReviews? -
Django Model ManyToMany Reverse Filter
Here's excerpts from (something analogous to) my models: class Person(models.Model): name = models.CharField(max_length=20) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to', ) def __str__(self): return self.name class Relationship(models.Model): from_person = models.ForeignKey(Person, related_name='from_people', on_delete=models.CASCADE, ) to_person = models.ForeignKey(Person, related_name='to_people', on_delete=models.CASCADE, ) status = models.CharField(max_length=20) def __str__(self): return "{} is {} {}".format( self.from_person.name, self.status, self.to_person.name) Here's the contents of my database: >>> Person.objects.all() <QuerySet [<Person: A>, <Person: B>, <Person: C>]> >>> Relationship.objects.all() <QuerySet [<Relationship: B is Following C>]> If I want to see who a given person is following, I can build a new method into the Person class: def get_following(self): return self.relationships.filter( to_people__status='Following', to_people__from_person=self) This works: >>> p2.get_following() <QuerySet [<Person: C>]> I want to do the REVERSE of this. Instead of asking "Who does this person follow?", I want to ask "Who follows this person?". I can do that like this (although it returns Relationship objects, not Person objects): >>> Relationship.objects.filter(to_person=p3, status='Following') <QuerySet [<Relationship: B is Following to C>]> My attempt is this (which returns an empty QuerySet): def get_following(self): return self.relationships.filter( from_people__status='Following', from_people__to_person=self) Your help is appreciated! -
what version to learn for django
I am beginning Django, I am stuck in what version to learn, version 2.0 does not use regular expressions but a lot of the books out there teach version 1.8 which was the old LTS. Any advice would be appreciated. Thanks -
Excel files not showing on Heroku web app
I have a django backed website on Heroku and every time I try to view/download the upload excel files after uploading them on the Heroku website I get this error: Not Found: The requested URL /excel_files/<file> was not found on this server. Here is my views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from .forms import UploadForm from django.conf import settings import os import openpyxl, re def index(request): """The home page which generates the donor list html page""" if request.method != 'POST': form = UploadForm() else: form = UploadForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() file = request.FILES['fileobj'].name file_corrected = file.replace(" ", "_") path = os.path.join(settings.MEDIA_ROOT, file_corrected) wb = openpyxl.load_workbook(path) sheet = wb.get_sheet_by_name('Sheet1') text_file = open('upload/templates/upload/donor_list.html', 'w') html1 = "{% extends 'upload/base.html' %}" + "\n" + "{% block header %}" + "\n" + " <h1>Donor List</h1>" + "\n" + "{% endblock header %}" + "\n" + "{% block content %}" + "\n" html2 = "{% endblock content %}" text_file.write(html1) for rowNum in range(1, sheet.max_row + 1): firstName = str(sheet.cell(row=rowNum, column=1).value) if firstName == "None": firstName = "\n" lastName = str(sheet.cell(row=rowNum, column=2).value) addNum = re.compile(r'\d(\d)*') addressNumber1 = addNum.search(str(sheet.cell(row=rowNum, column=3).value)) if addressNumber1 is None: addressNumber … -
why the data injected in template is only available if user is login? want all public
I am working on a portfolio web, with an about page, the models are created on the DB, and the template tagging is working, but just if user is authenticated in the admin page, I´ve extended the user model to a userprofile one, to show the portfolio data stored on the DB, obviously I want this to be public for everyone but I cant get it; also I want to manage all the models related to the app just with the superuser, as I have no need to create more users because is a simple portfolio for one single user. CODE: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User) bio = models.TextField(max_length=1000, blank=True) location = models.CharField(max_length=30, blank=True) avatar = models.ImageField(upload_to='profile/', null=True, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "{} Portfolio ".format(self.user) def create_user_profile(sender, instance, created, **kwargs): """Create the UserProfile when a new User is saved""" if created: profile = UserProfile() profile.user = instance profile.save() post_save.connect(create_user_profile, sender=User) # ######################################################################################## from coltapp.models import Post, Comment, UserProfile from django.views.generic import (TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView) class AboutView(ListView): model = UserProfile template_name = 'coltapp/about.html' select_related = ('userprofile') # ######################################################################################## from coltapp import views from … -
display data from a text file using django
I have a text file with lot of columns, these columns are separated by /t (tab). I want to write a view that display the first ,the second and the third column into a table. This is my view def displayfile(request): file = open("mytestapp/LinkBooster_20171002.txt","r") #alorithme of dispaly i don't know how context = { 'first_column' : src, 'first_column' : dst, 'first_column' : title, } return render(request,'myapp/display.html',context ) so in this view i want to get the colomnus -
How to modify field/TextField size in Django admin panel?
I am trying to update my inline class to modify the size of the character and text fields. This code formfield_overrides works fine in non inline classes, but it does not seem to do anything within the inline class. Am I approaching this the wrong way? See below for the code: class MyModelInLine(admin.TabularInline): formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '20'})}, models.TextField: {'widget': Textarea(attrs={'rows': 4, 'cols': 80})}, } model = custom_models.MyModel extra = 0 -
Django ORM: get queryset of one field type
I have a model ProblemVote which contains user (ForeignKey), problem (ForeignKey) and status field. I need all the problems (which has been voted) with status 'AC' and 'R'. I am able to fetch all the required problems in a Python list. However, i want to know if there is a better way using queryset methods. Part of my code: all_votes = ProblemVote.objects.filter( user=user).select_related("problem").filter(problem__stage='PV') all_votes_problems = [vote.problem for vote in all_votes] accepted_problems = [vote.problem for vote in all_votes if vote.status == 'AC'] rejected_problems = [vote.problem for vote in all_votes if vote.status == 'R'] Getting the problem as a queryset will help me in finding the count as queryset.count() and in finding queryset differences like queryset.difference(another_queryset). -
Returning child properties in JSON from Django Models
I have a database model setup in Django to track portfolios and am trying to develop a API to return a portfolio along with each coin in it, and each transaction associated with the coin. However using the api i only see the name field of my model being returned. Some code for clarification: model.py: class Portfolio(models.Model): name = models.CharField(max_length=250) @property def coins(self): return Coin.objects.filter(portfolio=self) def transactions(self): return Transaction.objects.filter(portfolio=self) def __str__(self): return self.name class Coin(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.PROTECT) name = models.CharField(max_length=100) symbol = models.CharField(max_length=5) price = models.DecimalField(max_digits=20, decimal_places=9) info = models.TextField() website = models.TextField() rank = models.IntegerField() def __str__(self): return self.name + " - " + self.symbol class Transaction(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE) coin = models.ForeignKey(Coin, on_delete=models.PROTECT) purchaseDate = models.DateTimeField() soldDate = models.DateTimeField(default=None, null=True, blank=True) amount = models.DecimalField(max_digits=20, decimal_places=3) price = models.DecimalField(max_digits=20, decimal_places=9) def __str__(self): return self.coin.name + " - " + str(self.amount) + " At $" + str(self.price) My json serializer: class PortfolioSerializer(serializers.ModelSerializer): class Meta: model = Portfolio fields = '__all__' How data comes back: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 3, "name": "Binance" } ] What I want is in the data set, under binance it should show … -
What is the preferred way to avoid duplication in validation in Django forms / serializers?
Where should the validation logic live so that it can be shared? What provides validation logic the easiest, least friction handling of relations in django models (model relationships, many-to-many and querysets) This is a related SO question, but the answer doesn't go into any detail and is only for the most basic use cases: How to avoid code duplication in Django Forms and Django Rest Framework Serializers?