Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
No MyUser matches the given query
I am having an error No MyUser matches the given query, and I am not sure why there is no a match since the URL is properly set. In my app I have two kind of users: Employees and candidates that are both part of the model MyUser and are differentiated by a boolean is_candidate or is_employee. My issue is when creating the user detail view. I started with the EmployeeDetailView : class EmployeeDetailView(LoginRequiredMixin, generic.DetailView): #import pdb; pdb.set_trace() model = MyUser template_name = 'employee_details.html' def get_object(self, queryset=None): return get_object_or_404(MyUser, pk=self.kwargs['pk2'], members__project=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(EmployeeDetailView, self).get_context_data(**kwargs) employee_name = MyUser.objects.get(id=self.kwargs['pk2']) team_list = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all() team_list_pop = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all().exclude(id=self.kwargs['pk2']) context={ 'employee_name' : employee_name, 'team_list' : team_list, 'team_list_pop' : team_list_pop, } return context on URL : url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'), That work properly and I am able to access my user detail So I wanted to do the same for CandidateDetailView with the code : class CandidateDetailView(LoginRequiredMixin, generic.DetailView): #import pdb; pdb.set_trace() model = MyUser template_name = 'employee_details.html' def get_object(self, queryset=None): print(self.kwargs['pk2']) return get_object_or_404(MyUser, pk=self.kwargs['pk2'], applicant__project=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(CandidateDetailView, self).get_context_data(**kwargs) context={ } return context On URL : url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.CandidateDetailView.as_view(), name='CandidateDetails'), But this time I get the error that there is no matching Raised by: … -
Easy Django REST Framework Websocket Usage
I have a an application that uses Angular for the frontend and communicates with an API running Django RF. Now, let me try and outline what I'm trying to achieve in hopes of finding an easy solution. When a user runs a report, a worker version of the API generates the report to prevent the main API from bogging down. The report runs for a couple seconds/minutes. The user refreshes the page and voila, their report is there. What I'm trying to achieve is the elimination of the whole "user refreshes the page" portion of this process. My goal is to do this via websockets. I literally want something as simple as: WEB: "Hey API, I want this report. I'll wait." API: "Yo dog, you're reports done." WEB: "Cool, let me refresh my report list. Thanks bud." Now, we start to venture into an area I'm unfamiliar with. Websockets can do this, right? I just need to create a connection and wait for the all-clear to be sent by the worker. Now, here's where it gets hairy. I've spent the better part of the day going through libraries and just can't find what I need. The closest I've come is … -
django form ManyToMany Initial queryset value
This has oficially driven me crazy. I have a very basic form with 1 many to many field: models.py class ProtectionProfile(models.Model): Optional_SFR = models.ManyToManyField(SFR, related_name='Optional') Then my forms.py class OptForm(forms.Form): selecopt_sfr = forms.ModelMultipleChoiceField(queryset=MYProtectionProfile.Optional_SFR.all()) During my page render I get a number of protectionprofiles for a given user. for each protectionprofile I need to generate a form with those various Optional_SFR field. So how can I pass the relevant ProtectionProfile to the form for the correct query set? I feel like this should be really easy but I can't find it any where! Any help is greatly appreciated. -
adding a custom method to Meta class in django
I have an AbstractBase model class that gets inherited by several models in their respective apps. I want the user to be able to set a name that will be used in the verbose_name field in the Meta class. If a user provides a name in one of the fields in the AbstractBase model, then that field will be used as the verbose name this is what I have tried so far class AbstractBase(models.Model): ...... custom_name = models.CharField(blank=True) class Meta(object): abstract = True def update_verbose_name(self, custom_name): if self.project_setting is not None: return verbose_name == self.custom_name when I run this it gives me TypeError: 'class Meta' got invalid attribute(s): update_verbose_name is there another way that I solve this? -
Struggling with trans in a input placeholder
Here is the HTML part <div class="col-md-4 col-sm-4"> <input type="text" class="form-control" placeholder={% trans "First Name" %} id="cf-fn" name="cf-fn" required=""> </div> Instead of getting 'First Name', I got just 'First'. Here is a photo How could I fix it? -
Django ORM - a model object from using .get or indexing a QuerySet
my_model = MyModel.objects.get(pk=5) So 'my_model' is not a queryset object, neither would it be if I indexed it from a queryset. Is there something special about a QuerySet other than it is a list of objects from the table(s)? Also I was wondering, I know that simply creating a QuerySet does not involve a database lookup, but what about getting just one object like in 'my_model'? -
Django docker error table not exist
I had a existing Django Rest project with an existing MySQL database (named libraries) which I wanted to Dockerize. My dockerfile: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt My docker-compose: version: '3' services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: libraries MYSQL_USER: root MYSQL_PASSWORD: root web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" Steps: I ran: docker-compose build - build was successful I ran: docker-compose up - had to run this command twice and then I could access my API by hitting localhost:8000 However, whenever I hit any API endpoint I get an error Table "XYZ" does not exist. All the tables are already present. Why this happens?