Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
An operational error when making django AJAX likes
This is the error that I got. django.db.utils.OperationalError: no such table: photos_post_likes I was following this video to create a like button. https://youtu.be/pkPRtQf6oQ8 By then I had already created the model (Post). Just when I added a new line (likes) in models.py and ran makemigrations, it migrated without any problem. But, when I ran migrate this error appeared. Here is the models.py file from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from PIL import Image class Post(models.Model): date_shared = models.DateTimeField(default=timezone.now) caption = models.TextField(max_length=50) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') # this line made the error occur image = models.ImageField(upload_to='post_images') def __str__(self): return self.caption def save(self): super().save() img = Image.open(self.image.path) if img.height > 800 or img.width > 800: output_size = (800, 800) img.thumbnail(output_size) img.save(self.image.path) def get_absolute_url(self): return reverse('home') -
Django setdefault, NoMouduleError
(first of all, sorry for my bad English) import os import django import csv import sys os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bangolaf.settings') django.setup() from product.models import Category, Subcategory, Product CSV_PATH_PRODUCTS = './category.csv' with open(CSV_PATH_PRODUCTS) as in_file: data_reader = csv.reader(in_file) next(data_reader, None) for row in data_reader: if row[0]: print(row) ModuleNotFoundError: No module named 'bangolaf' I'm trying to make csv reader which connect my django project and csv file. The csv file is in out of django project, so I made 'setdefault' of my django, and same virtual env is also activated. but I got ModuleNotFoundError message when I checked manage.py of django project, the setdefualt is exactly same like csv reader's one I made. def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bangoraf.settings') looking for someone to help -
How can I create persistent server-side objects in Django?
I am creating a website in Django to display the results of a calculation on a large csv file. I have this function in my views.py: def results(request, input=""): from calculations import calculate from calculations import datamanager data = datamanager(); return render(request, template, {"res":calculate(data.data, data.cov_table, input)} Unfortunately, because the input varies quite a bit I run calculate every time and caching will not decrease loading times that much. However, datamanger's init() method takes a long time because it has to read two large csv files, so only running it once will save time. Is there a way to only load datamanager when the server starts up and just access it from within the view? I have tried creating an app out of the object but then I read that "There’s no such thing as an Application object" on the Django webpage. I would also like to avoid creating a Database. The csvs definitely could be a database, but the datamanager class does a reasonable amount of processing on init. This is for finance, so the datamanager class loads a list of securities: [ISIN, Return, STD, Volume, dict(key: time, value: price)] and a table of correlations. -
Django: align models to a configuration (e.g. a text file, or API)
The specific problem I face is that I have an API interface which defines tables in a kind of domain specific language (the target is Zoho Analytics). The django code prepares data and sends it to Zoho. Now I want to add an additional backend: I want to write this data to postgres. It would be nice to have the full use of the Django ORM. However, when I change the tables for the Zoho implementation, I want the "associated" Django models to update to, taking advantage of schema migration and all the other good things. The Django models are not really "dynamic", the schema won't change during runtime, the schema only needs to be discovered at start up (or when manage.py makemigrations is run) but it seems that attempts to do dynamic models are the closest fit. Discussions like this are typical: Django dynamic model fields They are typically quite old and seem like there is no solution which is not hackish. It's almost like I would be better off generating a .py file :) -
In Django, how do I generate a welcome message for the user?
Something like: Welcome {user that is logged in}! It should appear when the user logs in. Thank you! -
Unable to create the django-migrations table
I am very new at this and am trying to connect my django project with my mongodb using djongo. I've set up mongo atlas and give myself the admin role. to create a new project: django-admin startproject mysite I've created a database with nothing in it called demo_db that has no data written Then I change the settings.py database session into: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'demo_db', 'HOST': 'mongodb+srv://louisa:<password>@cluster0.ya1jd.mongodb.net/demo_db?retryWrites=true&w=majority', 'USER': 'louisa', 'PASSWORD': '<password>', } } I am running atlas version 4.2. When I save the settings.py and run python manage.py migrate I run into this giant error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Traceback (most recent call last): File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 856, in parse return handler(self, statement) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 897, in _create query = CreateQuery(self.db, self.connection_properties, sm, self._params) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 645, in __init__ super().__init__(*args) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 729, in parse self._create_table(statement) File "/opt/anaconda3/lib/python3.7/site-packages/djongo/sql2mongo/query.py", line 649, in _create_table self.db.create_collection('__schema__') File "/opt/anaconda3/lib/python3.7/site-packages/pymongo/database.py", line 418, in create_collection read_concern, session=s, **kwargs) File "/opt/anaconda3/lib/python3.7/site-packages/pymongo/collection.py", line 187, in __init__ self.__create(kwargs, collation, session) File "/opt/anaconda3/lib/python3.7/site-packages/pymongo/collection.py", line 267, in __create collation=collation, session=session) File … -
Restricting Drop Downs populated by a query to the active user's inventory
I have nearly completed a collectables inventory system for users to populate their own/inventories and filter through them. I have been able to restrict the user to only viewing their records, but the drop downs for filtering records are based on the full user population e.g. A user can only see their book titles but the drop down will show all book titles populated in the database for all users. I have tried some functions in Forms.py in the choice filters to initialize them with restrictions by the user id, similar to how I have restricted the users to see their own records but this has not worked. Models.py class ComicInput(models.Model): Publisher = models.CharField(max_length=20, default='Marvel', choices=Publisher_Choices, null=True, blank=True ) Title = models.CharField(max_length=50,default='', blank=False) Series = models.CharField(max_length=8,default='1st', choices=Series_Choices, null=True, blank=True) Type = models.CharField(max_length=30, choices=Type_Choices, null=True, blank=True ) #default='Reg' Number = models.IntegerField(default='', blank=False) Category = models.CharField( max_length=12,default="Hold",choices=Category_Choices,blank=True, null=True) uid = models.ForeignKey(User,on_delete=models.CASCADE, editable=False) #default=False, null=True) def __unicode__(self): return '%s %s %s' % (self.uid,self.Title, self.Number, self.Grade, self.Series, self.CoverPic, self.Category) class Meta: ordering = ('Title', 'Series', 'Number') Forms.py ##############Comic Input Forms############### class ComicInputForm(forms.ModelForm): class Meta: model = ComicInput fields = '__all__' ###################### Collection View Filters ####################### # ***** I THINK THE PROBLEM CAN BE FIXED … -
GET /static/bootstrap.min.css HTTP/1.1" 404 68
Im getting this error "GET /static/bootstrap.min.css.css HTTP/1.1" 404 68 in my terminal whenever I update my page with prod.py I build. I think it's my code in my settings.py that is wrong and with the static files also. there are my codes 1. B_F1 #project name 2-1. B_F1 3. settings 4-1. base.py 4-2. dev.py 4-3. prod.py # i use it when i publish 2-2. B_F_user # app name 2-3. static 3. bootstap.min.css this is base.py code from pathlib import Path import os import json from django.core.exceptions import ImproperlyConfigured BASE_DIR = Path(__file__).resolve().parent.parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'B_F_user', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'B_F1.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and this is prod.py code from .base import * DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') and it my base.html <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <meta name = "viewport" content = "width=device-width, initial-scale=1"> <link rel="stylesheet" href="/static/bootstrap.min.css"/> i used manage.py collectstaic but … -
How to handle datetimes for users in different locations django?
I have an application that is being built with Django and Django REST Framework. Users can add certain objects to the database and set expiry dates on them. Other users will retrieve those added items from the database and it will be displayed client-side. Both the users creating the objects and the users retrieving them could be in different places of the world. I plan to store the datetimes in UTC format. How do I make sure that the datetime is in UTC format before storing and when a user tries to retrieve one of these items, it is correctly displayed in their Timezone? What I am thinking I am thinking that I should convert it to UTC (client-side) and save that to the database and then when a user retrieves that object I will return it in UTC (from the database) and change the time to the user's local time client-side. Is this a good approach? -
Django: How to properly use two forms in one template for two models that are connected by a foreign key
I have 2 models: Applicant and Application. Application is connected by foreign key to Applicant. For any applicant there can be many applications. models.py class Applicant(models.Model): first_name = models.CharField(max_length=150, null=False, blank=False) last_name = models.CharField(max_length=150, null=False, blank=False) email = models.EmailField(blank=False, null=True) ... class Application(models.Model): applicant = models.ForeignKey(Applicant, null=False, blank=False, on_delete=models.CASCADE) ... I cannot figure out how to have 2 forms, for the 2 models, display in 1 template such that upon submission both Applicant and Application can be completely populated and saved. I've tried inlineformsets but I kept on getting errors that essentially Application must have an applicant instance. I then tried just having two separate forms and saving them separately, but I got the same error. How can I correct this? forms.py class ApplicantForm(ModelForm): veterinaryContactPermission = forms.BooleanField(widget=forms.CheckboxInput) class Meta: model= Applicant fields = '__all__' class ApplicationForm(ModelForm): class Meta: model = Application exclude = ['applicant'] <!-- Excluding so that applicant drop down showing all possible applicants is not displayed in the template. I don't want other applicants to be visible to current applicant. ApplicantFormset = inlineformset_factory( Applicant, Application, form=ApplicationForm, fields=['applicant'], can_delete=False ) views.py class ApplicantApplication(CreateView): model = Applicant # form1 = ApplicantForm # form2 = ApplicationForm form_class = ApplicantForm template_name = … -
How to create a Django model function that returns the read time of a blog Post, if the body has html tags in it?
I'm creating a Django Blog, and I saw the feature of average read time in blogs like medium or dev.to and I ask myself how can implement it. blog/models.py: class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) header_image = models.ImageField(blank=True, null=True, upload_to="images/post_header/") date = models.DateField(auto_now_add=True) description = models.TextField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) # body = models.TextField() body = RichTextField() upvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_votes") def total_likes(self): """ Returns total likes in the page """ return self.upvotes.count() def __str__(self): """ Show the title and the author in the admin Page """ return self.title + " by " + str(self.author) def get_time_read(self): return "Some tricky code to get the body of the post and return the words stripping the tags" def get_absolute_url(self): return reverse("blog:article_page", kwargs={"pk": self.pk}) I think that the easiest way is to implement a function in the Post model, that returns the read time of an average adult person, by counting the total words and dividing it by the average words per minute (aprox 200 w/m), and after that pass the function to the html template and render the time read. That would be easy of implement, If there weren't html tags in the blog Post body, since I … -
How to change Signup form in Django Rest Framework and Django allauth?
I'm building an API with Django Rest framework, where Django Allauth is responsible for my signup registration. After implementing everything works fine: On this Signup Form, I want to remove the Username field and replace it for an Age field. I know that, to achieve that, I need to config ACCOUNT_FORMS, But how should I create this form? # settings.py ACCOUNT_FORMS = { "signup": "user.forms.MyCustomSignupForm", } # models.py class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) age = models.IntegerField() is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email # forms.py from django import forms from allauth.account.forms import SignupForm class MyCustomSignupForm(SignupForm): -
Get single_object from prefetch_related without additional queries. Django
Say I have a model B which is related to model A via ForeignKey. class A(models.Model): ... class B(models.Model): a = models.ForeignKey( A, related_name = 'b' ) active = models.BooleanField() ... I query A objects and prefetch related B objects: A.objects.prefetch_related('b')... But then I need to get only those B objects which are active. I could use Prefetch to filter B objects: A.objects.prefetch_related(Prefetch('b', queryset=B.objects.filter(active=True)))... and then: object.b.all()[0] while iterating queryset. But I just wander if there is more elegant solution for this. Thanks. -
I'm getting a NoReverseMatch error in my home page
I'm getting a NoReverseMatch error in my home page. It is from the html that I injected from my announcement app. It says that the reverse of the link is cannot be found. When I removed that line It shows the card but the text with template tag. _announcement_home.html: <div class="container"> <div class="card announcement-card" style="width: 18rem;"> <h5 class="card-header">Announcement</h5> <div class="card-body"> <h5 class="card-title">{{announcement.title}}</h5> <p class="card-text">{{announcement.text}}</p> <span class="announcement-date">{{announcement.date}}</span> {% if user.is_authenticated %} <a href="{% url 'announcement:single' pk=self.pk %}" class="btn btn-info">Change</a> {% endif %} </div> </div> <br> </div> index.html: {% extends 'base.html' %} {% block content %} <div class="w3-container w3-teal"> <h1>BANNER HERE</h1> <p>Dito yung banner</p> </div> {% include 'announcement/_announcement_home.html' %} {% endblock %} -
Deploying Django project on Heroku with Docker
Hello to everyone and thanks for attention! I am stack with deploying django project to heroku. I have several images, which works well on localhost with docker-compose.yml, but it is really problematic for me to deploy this on Heroku. Here is my images: news_board_api_beat latest 90b5c3661dfb 10 hours ago 947MB news_board_api_celery latest 90b5c3661dfb 10 hours ago 947MB news_board_api_web latest 90b5c3661dfb 10 hours ago 947MB redis alpine 933c79ea2511 4 days ago 31.6MB python 3 da24d18bf4bf 5 days ago 885MB postgres Thanks you! -
Django Error: "The view auctions.views.new_bid didn't return an HttpResponse object. It returned None instead."
I'm getting the error: "The view auctions.views.new_bid didn't return an HttpResponse object. It returned None instead." Does anyone know why it is returning None? Any help is appreciated. This view will allow a user to bid on an item on a site, similar to ebay. new_bid allows them to bid and listingpage is to show the actual item's page. The listing page loads fine, I just get the error when I place a number in the bid form, and save. In the /admin section of the site I can see the number is not saving. views.py: def new_bid(request, listingid): if request.method == 'POST': auction_to_add = Listings.objects.get(id=listingid) total_bid = request.POST.get("total_bid") bid = Bid.objects.create(user=request.user, listingid=auction_to_add, bid=total_bid) auction_to_add.bids.add(bid) auction_to_add.last_bid = bid auction_to_add.save() return HttpResponse('success') def listingpage(request, listingid): comments = Comments.objects.filter(listingid=listingid) item = Listings.objects.get(id=listingid) return render(request, "auctions/listing.html", { "listingid": listingid, "comments": comments, "product": item, }) Part of html for the listingpage that allows a user to place a bid: <form id="addBid" data-startingbid="{{product.starting_bid}}" data-lastbid=" {{product.last_bid.bid}}" data-auction="{{product.id}}" action="{% url 'new_bid' product.id %}"> {% csrf_token %} <input type="number" name="totalBid" id="newBid" placeholder="Total bid"> <button class="button-auction" type="submit">Send</button> </form> urls.py urlpatterns = [ path("listings/<int:listingid>", views.listingpage, name="listingpage"), path("new_bid/<int:listingid>", views.new_bid, name="new_bid"), ] models.py class Bid(models.Model): user = models.CharField(max_length=64) title = models.CharField(max_length=64) bid … -
Vue.js component specific delimiters with Django and Vue-loader
I am creating a Django + Vue.js v3 app, and found it very useful to use vue3-sfc-loader, as I can use Django to render .vue files easily, and get the best of both worlds. This setup works and Django successfully renders the .vue file, which are then picked up by vue3-sfc-loader, but the issue is that I cannot change the Vue delimiters, neither on Component level, nor on global level. One solution that works, but is quite inconvenient, is to use the Django {% verbatim %}. I also tried to use Vue global mixins to set delimiters, with no success, although I am not sure if I used then correctly in my context. Any way to set the Vue delimiters, either globally or on component level, in this context? index.html: <!DOCTYPE html> <html> <body> <div id="app"></div> <script src="https://unpkg.com/vue@next"></script> <script src="https://cdn.jsdelivr.net/npm/vue3-sfc-loader"></script> <script> const options = { moduleCache: { vue: Vue, }, getFile(url) { return fetch(url).then(response => { if (response.ok) { return response.text() } else {Promise.reject(response)} } ); }, addStyle(styleStr) { const style = document.createElement('style'); style.textContent = styleStr; const ref = document.head.getElementsByTagName('style')[0] || null; document.head.insertBefore(style, ref); }, log(type, ...args) { console.log(type, ...args); } } const { loadModule, version } = window["vue3-sfc-loader"]; const … -
How to set default value of foreign key pointing to self?
models.py class Person(models.Model): (...) leader = models.ForeignKey("self", on_delete=models.RESTRICT, related_name ='leader_set') And when I create object: Person.object.create() the value of leader is NULL, which is wrong. What should I set in default to the same Person object (at start Person is own leader) I know, that I can add Null=True, and after create set leader to fresh created object, but wonder if there's better solution? new_person = Person.object.create() new_person.leader = new_person -
How to filter foreignkey pointing to self
models.py: class Person(models.Model): (...) leader = models.ForeignKey("self", on_delete=models.RESTRICT, related_name ='leader_set') And now I'd like to find People, who are leaders to themselves. sth like this: own_leaders = Person.objects.filter(leader__isself=True) -
Django, why is request.GET.get not working?
I want to have a like/dislike system, so I created a variable, and I want to add 1 to it when a button is clicked. This is what I have on my html: <form method='get' action='#'> <input type="submit" value="Next" name="Next"/> </form> In views.py: if request.GET.get('Next') == 'Next': print('user clicked summary') I'm getting: NameError: name 'request' is not defined So what am I doing wrong? I got this code from Django - How to do an if statement if button is clicked, and I don't know what I'm doing wrong. Is there something I need to import? -
Django asking me to migrate pending migrations on server again and again?
Hello everyone my project is too small , I have only one app with name accounts with custom user model and i'm trying to deploy that on heroku server. But django showing me some weird behavior on server. I dont know how to describe my problem because its quite strange behavior i have never seen it before. im making migrations heroku run python manage.py makemigrations No changes detected then i'm migrating it. heroku run python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK Then i try to create a user by heroku run python manage.py createsuperuser **You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them.** Username: Where you can see migrations are still unapplied....What is this problem ? -
Exact ManyToMany match in Django 3.1.5
I have recently upgraded to Django 3.1.5 and the code that I was using to find exact ManyToMany matches has stopped working. The code follows the tips of the answer to this SO question: How to return exact matches for ManyToMany queries I have just created an additional virtual environment with Django 2.2 to confirm that it was the upgrade that stopped things from working, and indeed this code works on Django 2.2. Has anyone experienced this issue? Thank you for your help. -
Which django-wiki models should I override to add django-taulous tagging?
Which django-wiki models should I override to add django-tagulous tagging without breaking django-wiki? -
List of latest actions per group
I have following models in Django: class Action(models.Model): target_object_id = models.CharField(max_length=255, blank=True, null=True, db_index=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) # TODO: Rename to happened_at class Notification(models.Model): action = models.ForeignKey(Action, on_delete=models.CASCADE, related_name='notifications') recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Can you help me with building notification feed for a user? A query should return the latest actions for the particular user, but do not duplicate actions for the same target_object_id. -
I'm getting a NoReverseMatch error with my delete view
I'm getting a NoReverseMatch error with my delete view. I think it is with my success url in my views.py but I don't know what to do I even put a kwargs with a pk key in the reverse lazy but still won't work. I need urgent help. Thank you in advance! Views.py: from django.shortcuts import render from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.contrib import messages from . import forms from . import models # Create your views here. class AnnouncementListView(LoginRequiredMixin, generic.ListView): model = models.Announcement class AnnouncementDetailView(LoginRequiredMixin, generic.DetailView ): model = models.Announcement class AnnouncementUpdateView(LoginRequiredMixin, generic.UpdateView): model = models.Announcement form_class = forms.AnnouncementForm class AnnouncementCreateView(LoginRequiredMixin, generic.CreateView ): model = models.Announcement form_class = forms.AnnouncementForm class AnnouncementDeleteView(LoginRequiredMixin, generic.DeleteView ): model = models.Announcement success_url = reverse_lazy('announcement:single') def delete(self, *args, **kwargs): messages.success(self.request, "Post Deleted") return super().delete(*args, **kwargs) announcement_confirm_delete.html: {% extends 'base.html' %} {% block content %} <div class="container"> <form method="post" action="{% url 'announcement:destroy' announcement.pk %}"> {% csrf_token %} <h3>Are you sure you want to delete this?</h3> <div class="row"> <input class='btn btn-danger' type="submit" value="Delete" /> <a href="{% url 'home' %}" class="btn btn-light btn-large">Cancel</a> </div> </form> </div> {% endblock %}