Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Include choices with no records in grouped queryset
I'm trying to make a query in django grouping by a field with choices. I wanna get all choices values, algo choices with no records in the database. My model: CHOICES = ( ('new', 'New'), ('in_process', 'In process'), ('finished', 'Finished') ) class Task(models.Model): ... status = models.CharField(max_length=10, choices=CHOICES) My current query is: qs = Task.objects\ .values('status')\ .annotate(total=models.Count('status')) At this moment, I only have finished task in db, but I wanna get all choices values, with zero if it doesn't have records. Any idea? -
Django model shows up twice in all queries
I have three models like so: class Profile(models.Model): id = ShortUUIDField(primary_key=True, unique=True) class Bounty(models.Model): id = ShortUUIDField(primary_key=True, unique=True) creator = models.ForeignKey('Profile', related_name="bounties", on_delete=models.PROTECT) class BountyCompletion(models.Model): id = ShortUUIDField(primary_key=True, unique=True) profile = models.ForeignKey(Profile, related_name="bounty_completions", on_delete=models.CASCADE) bounty = models.ForeignKey(Bounty, related_name="bounty_completions", on_delete=models.CASCADE) url = models.URLField() So the idea is to have Profiles and Bounties, and the Profiles can create a bounty, then Complete as many bounties as they want, however many times as they want, each time they provide a different url. The problem is when I have two or more BountyCompletions with the same profile and bounty, and then I call either Bounty.objects.all() or profile_instance.bounties.all(), that bounty shows up twice (same id, same everything but it appears twice). I've tried setting it up like this as well as making the BountyCompletion table a through table for a manytomany from Profile to Bounty, but both have the same result. -
how can i call OneToOneField values in admin using list_display=[]
my model class user_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField() profile_created = models.DateTimeField(auto_now_add=True, auto_now=False) timestamp = models.DateTimeField(auto_now=True, auto_now_add=False) admin.py class UserProfileAdmin(admin.ModelAdmin): list_display = ['user','user.username','profile_created', 'timestamp'] admin.site.register(user_profile, UserProfileAdmin) it show the error: ERRORS: : (admin.E108) The value of 'list_display[1]' refers to 'user.username', which is not a call able, an attribute of 'UserProfileAdmin', or an attribute or method on 'testapp.user_profile'. how can i fetch another table values in Admin.py. -
how to server dynamic files in django?
I know there are many answer already, but unfortunately I failed to find a solution on them. Basically I am trying to serve image files stored at server|/srv/post/users/folder/PIMAGES/ACTIVE/image.jpg to client, but with the configuration I have in my settings.py file, I am getting an http 404 file not found error. my settings.py file: STATIC_URL = '/static/' MEDIA_ROOT = '/srv/post/' MEDIA_URL = '/post/' and then if I refer to http://127.0.0.1:8000/post/users/folder/PIMAGES/ACTIVE/image.jpg I just get 404 page not found. -
How to create chained select related in django admin list_filters
I use the great django suit as django admin dashboard. Otherwise, list filters will not be as select lists. Those select lists are strengthened with django's built-in RelatedOnlyFieldListFilter class which limits the select list elements. However, I couldn't achieve to make them chained selects, by which I mean that if one select has child selects, those children would show their list depending to parent. Continents (select list) --> Europe is selected Countries (select list) --> would show the countries within Europe and Italy is selected. Cities (select list) --> only Italian cities would show up, Rome is selected And as being the above selects are admin panel list filters, only the records related with Rome should be listed in admin edit list page. Possible? Did I tried any thing? Yes many things and I couldn't achieve so I am led to create an alternative edit page with vue. However, it has many other problems. -
When to use PyMongo vs MongoEngine in Django?
I'm working on a web app Project using Django with Mongo. But I'm Confused which one to approach. Should I use Pymongo or MongoEngine in Django. What is the purpose of both and when to use Pymongo & MongoEngine? -
Dealing GenericRelation and GenricForeignKey inside migrations
I have models with GenricForeigKey and GenericRelation fields. class Datasheet(models.Model): package1 = GenericRelation('PackageInstance') ... class PackageInstance(models.Model): content_object = GenericForeignKey() object_id = models.PositiveIntegerField(null=True) content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE) .... I am migrating from another models, inside my migration I want to create new instance. for ds in Datasheet.objects.all(): pi = PackageInstance.objects.create(content_object=ds) However this fails TypeError: DesignInstance() got an unexpected keyword argument 'content_object' Additionally, ds.package1.all() will also fail. AttributeError: 'Datasheet' object has no attribute 'package1' How do I solve this? -
Django redirecting to detail page after creating post (FBV)
I am making simple blog right now. I am trying to redirect page after creating post. models.py from django.db import models from django.db.models.signals import post_delete from django.conf import settings from django.dispatch import receiver class FreeBoardPost(models.Model): title = models.CharField(max_length=100, null=False, blank=False) content = models.TextField(max_length=5000, null=False, blank=False) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title @receiver(post_delete, sender=FreeBoardPost) def freeboard_image_delete(sender, instance, *args, **kwargs): instance.image.delete(False) urls.py from django.urls import path from .views import FreeBoardListView, FreeBoardDetailView, create_freeboard_view urlpatterns = [ path("", FreeBoardListView.as_view(), name="freeboard"), path("<int:pk>/", FreeBoardDetailView.as_view(), name="freeboard_detail"), path("create/", create_freeboard_view, name="freeboard_create"), ] views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import ListView, DetailView from .models import FreeBoardPost from .forms import CreateFreeBoardPost from users.models import CustomUser class FreeBoardListView(ListView): model = FreeBoardPost template_name = "bbs/freeboard/free_board.html" context_object_name = "free_board_list" def get_queryset(self): return FreeBoardPost.objects.order_by("-id") class FreeBoardDetailView(DetailView): model = FreeBoardPost template_name = "bbs/freeboard/free_board_detail.html" def create_freeboard_view(request, pk): post = get_object_or_404(FreeBoardPost, pk=pk) context = {} user = request.user if not user.is_authenticated: return redirect("login") form = CreateFreeBoardPost(request.POST or None) if form.is_valid(): obj = form.save(commit=False) author = CustomUser.object.filter(email=user.email).first() obj.author = author obj.save() return redirect("freeboard_detail", pk=post.pk) context["form"] = form return render(request, "bbs/freeboard/free_board_create.html", context) The views.py code gave me an error create_freeboard_view() missing 1 required positional argument: 'pk'. Is there way I can redirect … -
How can I see data from an already made mysql database on Django?
I'm new to Django and I am trying to use a mysql database created and filled with data by someone else I created a model with the same name as the table I want to get data from, my models is as follows class Study(models.Model): study_name = models.TextField(default='Unknown') description = models.TextField(default='Unknown') language = models.TextField(default='Unknown') number_of_years = models.IntegerField(default='0') database connected but when I go to admin I don't see the data there Please help me with this -
function detail view in django
For almost 5h I can't make detail view. My app name -movies My views: " def actor_view(request): actor_list = Actor.objects.all() context = {'actor_list': actor_list} return render(request,'movies/actor.html',context) def actor_detail_view(request,id): actorrr=get_object_or_404(Actor,id=id) context={ 'actorrr':actorrr, } return render(request,"movies/actor_detail_view.html",context) My model class Actor(models.Model): name = models.CharField(max_length=50) date_of_birth = models.DateField() age=models.IntegerField( null=True) net_worth = models.TextField(max_length=140, null=True) picture=models.URLField(default = '') children =models.TextField(max_length=140, null=True) marital_status=models.TextField(max_length=140, null=True) My actor html: {% load static %} {% block mainbody %} {% for actor in actor_list %} <!DOCTYPE html> <html> <head> <title>List of actors we have</title> <link rel="stylesheet" href="{% static 'css/style_actor.css' %}"> </head> <body> <div class="card" > <div class="card-image"> <img src="{{ actor.picture }}" alt="No poster in datebase" width="289" height="345"> </div> <div class="card-text"> <h2> <a href="/movies/actor_detail/{{actor.id }}">{{ actor.name }}</a> </h2> <p>{{movie.pilot}}</p> </div> <div class="card-imdb-score"> <p >Age: {{ actor.age }} </p> </div> </div> </body> </html> {% endfor %} {% endblock %} My actor_detail html <h6>TEST</h6> So I have no idea how to make urls and what to place in actor.html in href url.I've made many tutorials and still couldn't do it. -
I am developing a geolocation django application but getting error in postgis. please tell me what i am doing wrong
Currently, I am trying to build an application with Django geolocation using PostGIS and PostgreSQL but getting following error. I have inserted all libraries required but whenever I try to migrate the models i get error No such file or directory django.db.utils.OperationalError: could not open extension control file "C:/Program Files/PostgreSQL/12/share/extension/postgis.control": No such file or directory My settings.py file looks something like this """ Django settings for geodjango project. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')l@*3+2b@s()dvuyhjzgb*5p(x^(qp(!-ci(doykaso*=7_z-%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition … -
How to import a django rest framework api in a pyspark udf executor?
I have a project where i'm integrating django rest framework (drf) and apache spark, so I have some endpoints and I need to execute some jobs with spark by using udf. I have the below structure of the project: core/ udf/ ├── pyspark_udf.py ├── (and the rest of the files of a django app) api/ ├── api.py ├── urls.py ├── (and the rest of the files of a django app) udf.zip So according with that structure: First, in api.py file i have the endpoint where I need to execute the job. Second, inside the pyspark_udf.py, I call to an endpoint that is in the api.py file, I do some logic there and return the response. Then, again in the api.py file, I use the value returned to create a new column in a pyspark dataframe. Finally, I return the json data response in the drf endpoint. I achieved that behavior but using requests in the pyspark_udf.py function, which I considerer that is not elegant or best practice, working with an api that is in my own project, instead of do a simple call to the class of the drf endpoint. I created the minimum code below to reproduce the error … -
How to create a django formset or form add/edit page in order to edit several records
For one of my open source projects, I need to create ONE add/edit page in order to make possible to edit several records with one save. The repo is an IMDB clone formed for learning purpose. A user can add her/his favorite genres in her/his profile. Then an edit page is formed to show the list of those favored genres and the movies within that genre. (A for loop here) User can add notes, watch list options and so on to those movies. (NOT a FORMSET) However, the code doesn't work as expected. The page cannot be saved and only the first checkbox of the list can be changed. There is no error. NOTE: You can install repo with dummy data. (https://github.com/pydatageek/imdb-clone) Then after logging in, select your favorite genres. (http://localhost:8000/users/profile/) Then (I wish it can be solved here) you can see the movies with your selected genres. Add notes, to watch list... (http://localhost:8080/users/profile/movies2/) # users/templates/user-movies-with_loop.html {% extends 'base.html' %}{% load crispy_forms_tags %} <!-- Title --> {% block htitle %}Your movies from favorite genres{% endblock %} {% block title %}Your movies from favorite genres{% endblock %} {% block content %} <div class="card card-signin"> {% include 'users/profile-menu.html' %} <h3 class="card-title text-center … -
Django One-to-one structure
I am trying to create a One-to-one relationship between Table1 and Table2, I have migrated these successfully and it looks alright. I have populated Table1 with data, but when I try to populate Table2 with some data I receive an error message: Field 'table1_id' doesn't have a default value. My understanding was that the table_id that is being created for Table2 by using OneToOne should be self-populated. For every row in Table1 there will be a row in Table2 with some additional data, I would like to print these out in my template. I assume something is wrong in my structure. Any feedback would be highly appreciated! My models.py from django.db import models class Table1(models.Model): created = models.DateTimeField(default=None) published = models.CharField(max_length=50, default=None) code = models.CharField(max_length=25, null=True, unique=True) class Meta: db_table = 'Table1' unique_together = (("created", "published"),) def __str__(self): return self.created class Table2(models.Model): table1 = models.OneToOneField(Table1, on_delete=models.CASCADE, primary_key=True, default=None) code = models.CharField(max_length=50, default=None, null=True) url = models.CharField(max_length=100, default=None, null=True) more = models.CharField(max_length=100, default=None, null=True) class Meta: managed = True def __str__(self): return self.code -
Storing factory-boy RelatedFactory Object on Parent Factory
I have two Django models (Customer and CustomerAddress) that both contain ForeignKeys to each other. I am using factory-boy to manage creation of these models, and cannot save a child factory instance onto the parent factory (using relationships defined using the RelatedFactory class). My two models: class ExampleCustomerAddress(models.Model): # Every customer mailing address is assigned to a single Customer, # though Customers may have multiple addresses. customer = models.ForeignKey('ExampleCustomer', on_delete=models.CASCADE) class ExampleCustomer(models.Model): # Each customer has a single (optional) default billing address: default_billto = models.ForeignKey( 'ExampleCustomerAddress', on_delete=models.SET_NULL, blank=True, null=True, related_name='+') I have two factories, one for each model: class ExampleCustomerAddressFactory(factory.django.DjangoModelFactory): class Meta: model = ExampleCustomerAddress customer = factory.SubFactory( 'ExampleCustomerFactory', default_billto=None) # Set to None to prevent recursive address creation. class ExampleCustomerFactory(factory.django.DjangoModelFactory): class Meta: model = ExampleCustomer default_billto = factory.RelatedFactory(ExampleCustomerAddressFactory, 'customer') When creating a ExampleCustomerFactory, default_billto is None, even though a ExampleCustomerAddress has been created: In [14]: ec = ExampleCustomerFactory.build() In [15]: ec.default_billto is None Out[15]: True (When using create(), a new ExampleCustomerAddress exists in the database. I am using build() here to simplify the example). Creating an ExampleCustomerAddress works as expected, with the Customer being automatically created: In [22]: eca = ExampleCustomerAddressFactory.build() In [23]: eca.customer Out[23]: <ExampleCustomer: ExampleCustomer object> In … -
Run RQ jobs from other machine
I have a django app which pushes jobs on a Redis Queue by means of django-rq. I want to deploy the app on some host like Heroku. Can I pull and process those jobs from another machine, say a raspberry pi from home? -
''Error in formatting: AttributeError: 'UUID' object has no attribute 'int'
PLEASE SUGGEST HOW TO SOLVE THIS !!! Details : python website from github , using in local host (ubuntu) , database sqlite3 Getting error AttributeError: 'UUID' object has no attribute 'int' in line: raise ValueError('badly formed hexadecimal UUID string') Variable Value connection expression Col(accounts_customuser, accounts.CustomUser.id) self value '1' -
Submit button does not work after bootstrap styling in DJANGO
After I apply mdbootstrap, submit button function is broken. Nothing happens when i clicked. my view.py code: def scanDetail(request,scan_pk): context = { bla bla bla } if request.method == 'GET': return render(request, 'test/scanDetail.html',context) else: selected_values = request.POST.getlist('falsePositive') **if request.POST.get("save"):** for scan in scanResults: if request.POST.get("a"+str(scan.id)) == "clicked": scan.falsePositive = True else: scan.falsePositive = False scan.save() return redirect('scAppv2:currentSc') here is my template: {% for scan in xxxx %} <form method="POST"> {% csrf_token %} <tr> <td> {% if scan.falsePositive == True %} <input type="checkbox" name="c{{ scan.id }}" value="clicked" checked /> {% else %} <input type="checkbox" name="c{{ scan.id }}" value="clicked" /> {% endif %} </td> <td>{{ scan.a }}</td> <td>{{ scan.b }}</td> <td>{{ scan.c }}</td> <td>{{ scan.d }}</td> </tr> {% endfor %} </tbody> </table> <br> **<button type="submit" class="btn btn-default" name= "save" value="save" />SAVE</button>** </form> If i delete below code, everything goes to nice, and submit works. But i did not understand rootcause. <script type="text/javascript"> $(document).ready(function () { $('#scanDetailMainTable').DataTable({ "paging": false // false to disable pagination (or any other option) }); $('.dataTables_length').addClass('bs-select'); }); </script> Please help me anyone? Thanks. -
How to compare fields of same instance of related model in queryset
I have a model of Product. A product can be rented and each rental is an object made of a date_start and date_end class Product(model.Model): field1= model.Charfield(...) field2= model.Charfield(...) class Rental(model.Mode): product = model.ForeignKey(Product, related_query_name='rental') date_start = model.DateField() date_end = model.DateField() I am doing a form that returns all the Products available based on a period given by the user (user_date_start and user_date_end).. There is an equation that works for that, it tells you if there is an overlap in your dates: source (StartA <= EndB) and (EndA >= StartB) I start my queryset as follow: qs= Product.objects.exclude(rental__date_start__lt = user_date_end, rental__date_end__gt = user_date_start) I works well when I have only one reservation of the product. BUT when I have multiple reservations already done, it fails due to the fact that it combines all "date_start" together and all "date_end" together. Let's say for my product I have the dates 14-16/04/2020 and 20-25/04 in the database, the queryset will exclude the dates in-between, (eg. 17-19/04). Because (17 < 25) and (19 > 14). I would like to tell my queryset to compare date_start and date_end of the same Rental object, and not all 'date_start' and all 'date_end' without their respective bindings but … -
Download Video in Users Device Python Django
I'm making a Django app where users can paste link and download videos but there's a problem. I've tried to run it on my local server and then on WAN but both times results are same. Video is downloaded in my directory rather than users. I'm using youtube-dl for this. I'll be really thankful if someone help me out with this. I'll add the views.py file so you get a better understanding. Thanks! from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect from download.models import urlinput from download.forms import Input import youtube_dl import subprocess import os # Create your views here. def index(request): form=Input() if request.method=='POST': form=Input(request.POST) if form.is_valid(): link=form['url'].value() #downloadaudio(link) #video1080(link) #homedir = os.path.expanduser("~") #dirs=homedir +'/Downloads' video720(link) #download4k(link) form.save(commit=True) return render(request,'index.html',{'form':form}) else: print("Invalid Input") return render(request,'index.html',{'form':form}) def downloadaudio(link): options={'format':'bestaudio/best','extractaudio':True,'audioformat':'mp3'} with youtube_dl.YoutubeDL(options) as ydl: ydl.download([link]) def video1080(link): options={'format':'bestvideo+bestaudio/best'} with youtube_dl.YoutubeDL(options) as ydl: ydl.download([link]) def video720(link): options={'format':'best'} with youtube_dl.YoutubeDL(options) as ydl: ydl.download([link]) def download4k(link): subprocess.call("youtube-dl -f 299+140 {}".format(link)) -
Decoding User Data to String in Django
I have a model in Django titled Account class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) I am trying to print out the email as a string in views.py. def fill_view(request): # ... authentication ... email = Account.objects.filter(email=user.email).first() # ... setting up forms .... can.drawString(10, 100, email) I get the following error: Exception Type: AttributeError at /fill/ Exception Value: 'Account' object has no attribute 'decode' How can I decode the email into a string in Django when transferring the data from models.py to views.py? -
Managing multiple PostgreSQL instances on Heroku (Django project)
I’m taking John Elder’s Udemy course titled: “How To Push Django Python Apps To Heroku for Web Hosting”. The title explains what I am trying to do. When I initially set everything up 2 weeks ago, it appears I created three PostgreSQL database instances. See here for a screenshot on imgur. My question: In that screenshot of my Heroku dashboard, what are the second and third configuration entries for? I’ve already got some non-critical data in production on my live demo site. I’d like to delete the two of the three duplicate PostreSQL instances that I am not using but I’m curious and would first like to establish which one is the active one and which two are not. What is a potential use case for even having multiple duplicate databases? Rolling back a database to a given state (like by using PostreSQL’s Continuous Archiving and Point-in-Time Recovery (PITR) feature) and importing/exporting instances are ways of backing up and restoring data which have been corrupted. But how are those features different or similar from configuring more than one db URL in the Heroku dashboard, as depicted in my imgur screenshot above? I’ve Googled around using search terms such as ‘config … -
Invalid syntax error in Django form translate
I try translate my forms.py (placeholder, choices, etc) but i take syntax error. my code is here; from django import forms from django.utils.translation import ugettext_lazy as _ class CreatePollForm(forms.Form): title = forms.CharField(max_length = 300, label="", widget=forms.Textarea(attrs={'rows':'1','cols':'20', 'placeholder': (_'Type your question here'),'class': 'createpoll_s'})) polls = forms.CharField(max_length = 160, required=False, label="", widget=forms.TextInput(attrs={ 'placeholder': (_'Enter poll option'), 'class': 'votes firstopt','id':'id_polls1','data-id':'1'})) ... if i use like this, i take syntax error. how can i translate "Type your question here" and "Enter poll option" ? -
django.setup() not finding my Django Project
I am trying to write a faker script to populate my Django 3.0.4 project with some dummy data, but am getting stuck at the very beginning of the script. If I run this: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings') import django django.setup() I get this error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'MyProject' The script is in the same folder as my settings.py, urls.py, etc... and it's being executed within the venv for the django project. Why can't if find my project when django.setup() is executed? -
Problems with Google Api - Django
In my project I used GoogleOAuth2 to log in through Google account. It works fine for the first time. I mean, I chose two accounts and it works perfectly, but when I try to log in once again to these account I have an error: 'TypeError at /social-auth/complete/google-oauth2/ from_db_value() missing 1 required positional argument: 'context'' Django cannot process users who have already connected to the server in the past. Maybe someone know why it happens? In addition, when I want to delete these type os users in my django admin page I cannot do it, because I get the same error.