Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 %} -
Do I have to buy dynos too for my staging application on Heroku?
I'm using Heroku as a platform for my Django application, currently on a free dyno. I have created a copy of my application in order to seperate staging and production applications. Now before the application launch, I'm willing to upgrade to Standart2X dyno tier on Heroku for my production app, to use multiple process for background tasks. The things is my app really depends on background tasks (slow and high number of API calls), so I want be able to test multiple process's working in staging enviroment before pushing to production. What I don't understand is, do I have to upgrade my dynos both in staging and production enviroment? Maybe I can use hobby tier dynos in staging (which allows defining multiple process types in Procfile too) as they are cheaper than standart dynos, but this feels wrong as application sources will be different for staging and production. Maybe I'm missing something here or I don't understand these concepts enoughly. I'm kinda new to staging-production concept, so I appreaciate all kind of helpfull links and suggestions. -
How to update database automatically at a given time python
I've written a python script that takes a CSV from Github, makes it data frame with pandas, then do some preprocessing, and finally exports a SQL table for a database that is being used by Django models. Then a new CSV file is uploaded every day, and then I need the new CSV, so I manually run the script again for read CSV data frame and preprocessing delete the previous table create a new table with the same name for the Django model Is there a way to automate this? Is there a better practice than the one I'm doing? Thanks. -
Intermediary model not showing up in admin console?
I'm still relatively new to programming, Django, and creating apps so please bear with me. I'm working on a dietary app and I'm having a hard time visualizing and understanding why my specific use case of a ManyToManyField for one of my models is not showing up in the admin console. I tried reading the Django docs for the ManyToManyField relationship but I am still having troubles understanding it, so hopefully someone can explain this to me like I am a happy golden retriever. I have three models: class Product(models.Model): product_name = models.CharField(verbose_name='Product name', max_length=100) product_description = models.TextField(verbose_name='Product description', max_length=500) product_id = models.UUIDField(default=uuid.uuid4(), unique=True) def __str__(self): return self.product_name #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# class Recipe(models.Model): recipe_name = models.CharField(verbose_name='Recipe name', max_length=100) ingredients = models.ManyToManyField(Product, related_name='Ingredients', through='IngredientQuantity', through_fields=('recipe','ingredient')) class Meta: ordering = ['recipe_name'] def __str__(self): return self.recipe_name #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# class IngredientQuantity(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.DecimalField(verbose_name='Quantity', decimal_places=2, max_digits=99, null=False) What I was trying to do with this was create an Intermediary with IngredientQuantity which will give me the quantity along with a selected Product that I can then associate with Recipe. However I am not seeing the ingredients input for Recipe when I attempt to create a new entry for Recipe … -
Best way to send a mail in Django Model when a user's password has been changed?
I am new to python and django this year and am just struggling to figure out how to send a simple mail via send_mail to a user after their password has been updated? I have managed this via Signals with pre_save, however I don't want to make the user wait until the mail has been sent (which I can't work around as far as I know). With post_save, the previous state cannot be queried. What would be the best way here if I gave the following user model? class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email address", max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # Tells Django that the UserManager class defined above should manage # objects of this type objects = UserManager() def __str__(self): return self.email class Meta: db_table = "login" I had set this up with a pre_save signal, but this is not a solution for me because of the delay: @receiver(pre_save, sender=User) def on_change(sender, instance: User, **kwargs): if instance.id is None: pass else: previous = User.objects.get(id=instance.id) if previous.password != instance.password: send_mail( "Your password has changed", "......", "info@examplpe.com", [previous.email], fail_silently=False, ) Thanks in advance -
I want to change name of submenu and header in django admin
Django automatically picks the name of the model and adds s for plural, i would like to fix the code below, class PolicyAdmin(admin.ModelAdmin): class Meta: verbose_name = 'Policy' verbose_name_plural = 'Policies' list_display = ( 'policy_type', 'plate_number', 'user', 'policy_amount', 'last_renewal_date', 'next_renewal_date', 'policy_expiry', 'surrender_value', 'active', 'created_at', 'updated_at' ) name = 'Policies' ordering = ('policy_expiry', 'policy_expiry') -
I'm getting a NoReverseMatch error when I go into the DetailView
Everytime I create a post in my website I always get a NoReverseMatch error when it redirects to the detail view of the app. I can't find the answer in the internet. I need urgent help with this problem. 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 . import forms from . import models # Create your views here. class AnnouncementListView(generic.ListView,LoginRequiredMixin): model = models.Announcement class AnnouncementDetailView(generic.DetailView, LoginRequiredMixin): model = models.Announcement class AnnouncementUpdateView(generic.UpdateView, LoginRequiredMixin): model = models.Announcement form_class = forms.AnnouncementForm class AnnouncementCreateView(generic.CreateView, LoginRequiredMixin): model = models.Announcement form_class = forms.AnnouncementForm class AnnouncementDeleteView(generic.DeleteView, LoginRequiredMixin): model = models.Announcement success_url = reverse_lazy('announcement:single') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, "Post Deleted") return super().delete(*args, **kwargs) Urls.py: from django.urls import path from . import views app_name = 'announcement' urlpatterns = [ path('create/', views.AnnouncementCreateView.as_view(), name='create'), path('', views.AnnouncementListView.as_view(), name='list'), path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'), path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'), ] announcement_detail.html: {% extends 'base.html' %} {% block content %} <div class="container"> <h1>{{announcement.title}}</h1> <p>{{announcement.text}}</p> <span>{{announcement.date}}</span> <a href="{% url 'announcement:destroy' %} "><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eraser-fill" viewBox="0 0 16 16"> <path d="M8.086 2.207a2 2 0 0 1 2.828 0l3.879 3.879a2 2 0 0 1 … -
No module named 'django.core.context_processors' django template
i tried to make a template tag to get the logged in user request.user , i tried this in the settings.py 'context_processors': [ 'django.core.context_processors.request', '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 my template tag from django import template register = template.Library() @register.simple_tag def is_member(context): request = context['request'].user if request.user in request.user.model_name.admins.all: return True else: return False i have to make sure if the logged in user is one of members in admins (M2M) field but i get this error No module named 'django.core.context_processors' and while i try to remove this line 'django.core.context_processors.request' in the settings.py file i get this error 'is_member' did not receive value(s) for the argument(s): 'context' any recommendation i will appreciate thanks , art -
DJANGO - i execute_from_command_line(sys.argv)
Good afternoon, night or day, people! I'm trying to run this free project: https://github.com/mateoBa/trend These were my steps: clone; virtualenv env cd env / Scripts activate CD.. pip install -r requirements.txt bower install bower.json and finally: python manage.py migrate And, in the end, gave this error: (env) PS C: \ Users \ account \ Desktop \ PARANHOS \ trend> python manage.py migrate Traceback (most recent call last): File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ manage.py", line 22, in <module> execute_from_command_line (sys.argv) File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ env \ lib \ site-packages \ django \ core \ management \ __ init__.py", line 363, in execute_from_command_line utility.execute () File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ env \ lib \ site-packages \ django \ core \ management \ __ init__.py", line 337, in execute django.setup () File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ env \ lib \ site-packages \ django \ __ init__.py", line 27, in setup apps.populate (settings.INSTALLED_APPS) File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ env \ lib \ site-packages … -
How to make strings from my database show up in my localisation .po file in Django?
in one of my python projects, I'm looping through a list of countries which is stored in my SQLite database: {% if europe %} {% for country in europe %} <figcaption>{{ country.Name_fr }}</figcaption> {% endfor %} {% endif %} I am using localization so I have a locale folder with .po files with which I handle the different translations. However I would like to have the database strings (from {{ country.name_fr }}) show up in these .po files. This means I would have to include a translate tag but if I try it, it shows an error. This: <figcaption>{% translate {{ country.Name_fr }} %}</figcaption> leads to this: TemplateSyntaxError at / Could not parse the remainder: '{{' from '{{' Any help would be appreciated -
Set or change the DEFAULT_LANGUAGE in Django
I want the default language of my site to be Persian, not English! and DEFAULT_LANGUAGE is not working for me ! A part of my settings.py file : LANGUAGES = ( ('fa','Persian'), ('en','English'), ) DEFAULT_LANGUAGE = 1 LANGUAGE_CODE = 'fa' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True I also read these and they did not help: Set or change the default language dynamically according to the user - Django Django how to set the default language in the i18n_patterns? Django: Can't change default language Django: default language i18n Please help me. thanks!