Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR: ERROR: Could not find a version that matches djangomysqlrestframework
I am trying to install djangomysqlrest framework in my django project which is created inside pipenv. i tried the following command: pipenv install djangorestframework pipenv install djangomysqlrestframework but in both cases it is giving following error: x Locking Failed! .... .... ERROR: ERROR: Could not find a version that matches djangomysqlrestframework -
How do I set a ForeignKey based on the user account when I save a new element with the extra field of modelformset_factory?
I have two problems: 1) I would like to add a new player in extra field of the Formset but when I save it I have an IntegrityError because team = models.ForeignKey(Team, on_delete=models.CASCADE is not set. I need that the value of team is team=request.user.team but I don't know where to put this in my views.py or if I need to override some existing function. 2) When I render the site at the end of each form appear the string "Human ptr:"... how can I delete it? I have a form made with formset_factory rendered like this: team_area.html {% extends 'base_layout.html' %} {% block content %} <h1>Area Squadra</h1> <form method="post" action=""> {% csrf_token %} {{ player_formset.management_form }} {% for player_form in player_formset %} {% for field in player_form %} {{ field.label_tag }} {{ field }} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiorna"> </form> {% endblock %} And the view is managed by: views.py from django.shortcuts import render, redirect from skeleton.models import Player from django.contrib.auth.decorators import login_required from .forms import PlayerForm from django.forms import modelformset_factory # Create your views here. @login_required(login_url="/accounts/login/") def team_area(request): PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1) if request.method == "POST": player_formset = PlayerFormSet( request.POST, request.FILES, … -
Bitnami Django stack deploying an existing project issue
I am bit new to Bitnami django stack which I found is really useful to deploy a django project with much hassles. I have a project which is build in django so for deploying the project I tried to install the stack by downloading the bitnami django stack even though the installation went without error and was able to start the apache server the deployment of existing project seems to be throwing error. I tried the exact steps from https://docs.bitnami.com/oci/infrastructure/django/get-started/deploy-django-project/ but seems like it doesnot have full documentation for deploying existing project . It shows how to create a new project and run it. so I tried by replacing the demo project with the new project which i had created earlier that to went wrong by not working. So my question here is : How to deploy exactly in django stack for existing project ? How to install requirements to the python path(for that I found use_django_stack script but bit confused with the usage) ? How to migrate models ? How to activate virtualenv ? -
Django REST Framework, save to extra field on custom user model
Using Django REST Framework (DRF) I added a custom user model with one extra field. I have posted my code at the bottom. Now, when registering a new user ('/rest-auth/registration/') using DRF's graphical interface, I do get an extra input for the new model field. When I enter a value into this form input and hit POST, a new user is indeed created, but the extra field stays empty. I have been looking into how to get this to work, and found another SO question with a good example and answers, but the problem with this SO post is that the poster uses AbstractBaseUser as the class that his custom user models inherits from, and I want to use AbstractUser instead. (Why? Since I read that this is recommended, unless you truly understand what you are doing.) Because the poster in the other SO answer uses AbstractBaseUser, his solution seems to involve much more code and compliation than I need. So, can anyone tell advice me on how I can have the extra field also be filled during registration, when POSTing the correct data? users.models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): preferred_locale = models.CharField(max_length=2, blank=True, null=True) … -
Django REST-Auth Password Reset Tokengenerator (Generates b36 uid on request, wants b64 uid on confirm)
I am completely confused by the django middleware available: I simply want to get password-reset (and later password-change) functionality running, using django with rest_auth on the backend and Vue on the frontend. Step 1: Requesting the Reset-Link via Mail Views So far I have made a CustomPasswordResetView: # project/accounts/views.py from rest_auth.views import PasswordResetView class CustomPasswordResetView(PasswordResetView): pass Serializers and a CustomPasswordResetSerializer: # project/accounts/serializers.py from rest_auth.serializers import PasswordResetSerializer class CustomPasswordResetSerializer(PasswordResetSerializer): email = serializers.EmailField() password_reset_form_class = ResetPasswordForm def validate_email(self, value): # Create PasswordResetForm with the serializer self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(self.reset_form.errors) ###### FILTER YOUR USER MODEL ###### if not get_user_model().objects.filter(email=value).exists(): raise serializers.ValidationError(_('Invalid e-mail address')) return value def save(self): request = self.context.get('request') # Set some values to trigger the send_email method. opts = { 'use_https': request.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, } opts.update(self.get_email_options()) self.reset_form.save(**opts) Settings.py In the settings.py I have these fields, which seem relevant to me for my problem: # project/vuedj/settings.py REST_AUTH_SERIALIZERS = { "USER_DETAILS_SERIALIZER": "accounts.serializers.CustomUserDetailsSerializer", "LOGIN_SERIALIZER": "accounts.serializers.CustomUserLoginSerializer", "PASSWORD_RESET_SERIALIZER": "accounts.serializers.CustomPasswordResetSerializer" } (The complete settings.py is attached at the bottom) URL patterns My urls already catch my API request in order to send the Password-Reset Email: # project/vuedj/settings.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('api.urls')), path('accounts/', include('allauth.urls')), path('', api_views.index, name='home') ] … -
How to Access Data of Models of OneToOneFiled Django ORM
I am using User in-built model. Now i am query in UserListView to exclude all users who is Super Admin where Role is stored in Roles Model. I dont know how to query queryset = User.objects.exclude(user_user_role_id=1) This is problem please help me to Query class UserListView(LoginRequiredMixin, generic.ListView): model = User template_name = 'users/users.html' context_object_name = 'users' queryset = User.objects.exclude(user_user_role_id=1) UserProfile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) user_role = models.ForeignKey(Roles, on_delete=models.CASCADE) class Roles(models.Model): role_title = models.CharField(max_length=30) role_description = models.CharField(max_length=100) -
Bulk create items in Django CreateView
I would like to try add rows in template and then save it. In template, click "add rows" button will generate a new row and "submit" is save this form. What I want to do is user can add number of row and save it. But in CreateView, it's always only got the first row. I have try lots of ways but still have no idea. Here is my template: <form method="post" class="uniForm" action=""> {% csrf_token %} <table class="table table-striped table-condensed" id="dyeing"> <thead> <tr> <th>choice</th> <th>number</th> <th>ticket</th> </tr> </thead> <tbody> <tr> <th><input type="checkbox" name="record"></th> <th><p id="counter"> 1 </p></th> <th>...</th> </tr> </tbody> </table> <div class="col-sm-12"> <input type="button" id="btn" value="add"/> </div> <div class="col-sm-12"> <input type="submit" value=" save" class=""> </div> </form> and jQuery part is: <script> $("#btn").click(function () { //var markup = "<tr><td><input type='checkbox' name=' addrow($('#dyeing > tbody:last-child')) }); function addrow(selector) { new_row = selector.clone(true) counter = parseInt(new_row.find('#counter').text(), 10) + 1 new_row.find(":input").each(function () { var name = $(this).attr('name'); if (counter == 2) { name = name + '-' + counter } else { name.replace('-' + (counter - 1), '-' + counter) } var id = 'id_' + name; $(this).attr({'name': name, 'id': id}) }) new_row.find('#counter').text(counter) selector.after(new_row) counter++ } my views.py: class CreateTicketForm(generic.CreateView): ... def … -
How do I override the .update() method inside a custom manager class
How can I override the update() method of a django model inside a custom manager? I would like to modify the behavior of some methods(all(), update(), filter()) of a django model and I have tried to override using what my code down here suggests but nothing is happening. I have tried using QuerySet instead of inheriting from Manager but I am failing to override it properly as I am getting empty results all over the system. class undeletedObjectManager(models.Manager): def get_queryset(self): return super(undeletedObjectManager, self).get_queryset().filter(deleted=False) def update(self, *args, **kwargs): if "deleted" in args: # some logic here super().update(*args, **kwargs) the update() method isn't reached and I am guessing it is because I am not overriding the correct member. Is there a specific method name? in both Manager and QuerySet classes? How should I override them? -
How to Exclude Specific Content by Tag in Django RSS Feed
I'd like to exclude specific articles from my feed based on their tag. In the following case I'd like to exclude all articles that are tagged Exclude Article. model.py tags = models.ManyToManyField(Tag, blank=True, related_name='tagged') feed.py def items(self, item): return Article.published().all().exclude(tags__name=["Exclude Article"])[:5] -
Problem using ArrayReferenceField with djongo and django
I'am trying to create an application with django using djongo to communicate with mongodb. I have the following model: from djongo import models from django import forms class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: abstract = True class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ( '__all__' ) class MetaData(models.Model): # pub_date = models.DateField() # mod_date = models.DateField() n_pingbacks = models.CharField(max_length=255) rating = models.CharField(max_length=255) class Meta: abstract = True class MetaDataForm(forms.ModelForm): class Meta: model = MetaData fields = ( '__all__' ) class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ( 'name', 'email' ) class Entry(models.Model): blog = models.EmbeddedModelField( model_container=Blog, model_form_class=BlogForm ) meta_data = models.EmbeddedModelField( model_container=MetaData, model_form_class=MetaDataForm ) headline = models.CharField(max_length=255) body_text = models.TextField() authors = models.ArrayReferenceField( to=Author, on_delete=models.CASCADE, ) n_comments = models.CharField(max_length=255) def __str__(self): return self.headline But when I use django admin to create a new entry here is the error that I get: TypeError at /admin/app/entry/add/ int() argument must be a string, a bytes-like object or a number, not 'set' Request Method: POST Request URL: http://localhost:8000/admin/app/entry/add/ Django Version: 2.1.3 Exception Type: TypeError Exception Value: int() argument must be a string, a bytes-like … -
QuerySet.values('field_name') only returns id
I have a model named Comment that has another model Post as a foreign key. It also has a many to many relation with the user model. In [136]: user = User.get(pk=1) In [137]: all_comments = Comment.objects.all() In [138]: seen_comments = user.seen_comments.all() In [139]: unseen_comments = all_comments.difference(seen_comments) Here is the structure of the QuerySets: In [140]: all_comments Out[140]: <QuerySet [<Comment: Test comment>, <Comment: Test comment 2>, <Comment: Test comment 3>]> In [141]: all_comments.values() Out[141]: <QuerySet [{'id': 17, 'post_id': 44, 'text': 'Test comment', 'created_date': datetime.datetime(2018, 12, 18, 7, 0, tzinfo=<UTC>), 'user_id': 1}, {'id': 19, 'post_id': 44, 'text': 'Test comment 2', 'created_date': datetime.datetime(2018, 12, 19, 9, 0, tzinfo=<UTC>), 'user_id': 20}, {'id': 20, 'post_id': 44, 'text': 'Test comment 3', 'created_date': datetime.datetime(2018, 12, 27, 8, 12, 27, 338467, tzinfo=<UTC>), 'user_id': 1}]> The unseen_comments is a QuerySet of Comment objects. In [142]: unseen_comments Out[142]: <QuerySet [<Comment: Test comment>, <Comment: Test comment 3>]> In [143]: unseen_comments.values() Out[143]: <QuerySet [{'id': 17, 'post_id': 44, 'text': 'Test comment', 'created_date': datetime.datetime(2018, 12, 18, 7, 0, tzinfo=<UTC>), 'user_id': 1}, {'id': 20, 'post_id': 44, 'text': 'Test comment 2', 'created_date': datetime.datetime(2018, 12, 27, 8, 12, 27, 338467, tzinfo=<UTC>), 'user_id': 1}]> Now, if I try to get the id of all posts that are … -
Is there any way to create a web crawler using Python and Django (No Scrapy)
I need to create a web crawler using Python and Django where crawler should return all images where it crawled -
how to use yml files in python ChatterbotCorpusTrainer for a django application
I am building a chatbot using python chatterbot and want to host it using django. I have some yml files which are used to train the chatbot. In views.py, I can't link them. `chatbot = ChatBot( 'Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) chatbot.train("conversation") ` Here "conversation" is the yml file I want to use for training. It is also in the same folder. But Error is given as "NO such directory or file found". How to fix this issue? -
image: ["No file was submitted."] angular 6 ? tried DRF image and file field both
Here are my code for file uploading to s3. for now i am saving it in local class UploadedImage(models.Model): image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename) thumbnail = models.ImageField("Thumbnail of uploaded image", blank=True) title = models.CharField("Title of the uploaded image", max_length=255, default="Unknown Picture") description = models.TextField("Description of the uploaded image", default="") def __str__(self): return self.title def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.thumbnail = create_thumbnail(self.image) super(UploadedImage, self).save(force_update=force_update) below is my serializers class UploadedImageSerializer(serializers.ModelSerializer): class Meta: model = UploadedImage fields = ('pk', 'image', 'thumbnail', 'title', 'description', ) read_only_fields = ('thumbnail',) and views class UploadedImagesViewSet(viewsets.ModelViewSet): queryset = UploadedImage.objects.all() serializer_class = UploadedImageSerializer this is working fine but i am getting error while integration api in angular 6. below code for angular 6 ts and html import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders} from '@angular/common/http'; import { Router } from '@angular/router'; import { ViewChild } from '@angular/core'; @Component({ selector: 'app-photo-upload', templateUrl: './photo-upload.component.html', styleUrls: ['./photo-upload.component.css'] }) export class PhotoUploadComponent implements OnInit { @ViewChild("fileInput") fileInput; constructor(private http: HttpClient ,private router: Router) { } ngOnInit() { } url: string | ArrayBuffer; onSelectFile(event) { // called each time file input changes if (event.target.files && event.target.files.length>0) { console.log(event.target.files[0]); var reader = new FileReader(); reader.readAsDataURL(event.target.files[0]); // read file as … -
Graphql searches by foreign object name but not by foreign object id
This is filtering by id of topic. Graphql doesn't error, but it just do not filter by topic_id: class ArticleNode(DjangoObjectType): class Meta: model = Article filter_fields = ['topic__id'] interfaces = (relay.Node, ) oid = graphene.Field(graphene.Int) def resolve_oid(self, info, **kwargs): return self.id But when I filter by name of topics: class ArticleNode(DjangoObjectType): class Meta: model = Article filter_fields = ['topic__name'] interfaces = (relay.Node, ) oid = graphene.Field(graphene.Int) def resolve_oid(self, info, **kwargs): return self.id It works perfectly with name. However, I need to filter by id. Graphql query: { allArticles(topic_Name: "topic1") { edges { node { title topic { name } } } } } GraphQl query that doesn't error, but not works properly: { allArticles(topic_Id: 1) { edges { node { title topic { name } } } } } -
Solution needed to a scenario
I am trying to make use of a column's value as a radio button's choice using below code Forms.py #retreiving data from database and assigning it to diction list diction = polls_datum.objects.values_list('poll_choices', flat=True) #initializing list and dictionary OPTIONS1 = {} OPTIONS = [] #creating the dictionary with 0 to no of options given in list for i in range(len(diction)): OPTIONS1[i] = diction[i] #creating tuples from the dictionary above #OPTIONS = zip(OPTIONS1.keys(), OPTIONS1.values()) for i in OPTIONS1: k = (i,OPTIONS1[i]) OPTIONS.append(k) class polls_form(forms.ModelForm): #retreiving data from database and assigning it to diction list options = forms.ChoiceField(choices=OPTIONS, widget = forms.RadioSelect()) class Meta: model = polls_model fields = ['options'] Using a form I am saving the data or choices in a field (poll_choices), when trying to display it on the index page, it is not reflecting until a server restart. Can someone help on this please -
Password Field does not Exclude - Django
I want to remove password1 field from my form. But it not excludeing. Even i don't want to delete password field just want to disable from form. Forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() password2 = None class Meta: model = User fields = ['first_name','last_name', 'email'] exclude = ['password1',] -
Centos + apache Error client denied by server configuration: Call to fopen() failed for to my wsgi.py
I have simple django application running in centos. It runs fine with built-in django server (python manage.py runserver). The error comes when I try to run with apache. [Thu Dec 27 09:41:42.484517 2018] [:error] [pid 6104] (13)Permission denied: [remote 10.0.2.2:0] mod_wsgi (pid=6104, process='myproject', application='localhost.localdomain:8017|'): Call to fopen() failed for '/home/vagrant/myproject/myproject/wsgi.py'. have changed ownership and 777 permission to be apache user from /home till /home/vagrant/myproject/myproject/wsgi.py below is my apache configuration <Directory /home/vagrant/myproject/static> Require all granted AllowOverride None </Directory> <Directory /home/vagrant/myproject/myproject> Order allow,deny Allow from all # New directive needed in Apache 2.4.3: Require all granted <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/vagrant/myproject:/home/vagrant/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/vagrant/myproject/myproject/wsgi.py and this is my wsgi.py file import os import sys # Add the site-packages of the chosen virtualenv to work with site.addsitedir('/home/vagrant/myprojectenv/local/lib/python2.7/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('/home/vagrant/myproject') sys.path.append('/home/vagrant/myproject/myproject') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") # Activate your virtual env activate_env="/home/vagrant/myprojectenv/bin/activate_this.py" execfile(activate_env, dict(__file__=activate_env)) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() between I tried many solutions suggested by similar other stackoverflow suggestions. But no luck. Thanks in advance. -
Can I define classes in Django settings, and how can I override such settings in tests?
We are using Django for Speedy Net and Speedy Match (currently Django 1.11.17, we can't upgrade to a newer version of Django because of one of our requirements, django-modeltranslation). I want to define some of our settings as classes. For example: class UserSettings(object): MIN_USERNAME_LENGTH = 6 MAX_USERNAME_LENGTH = 40 MIN_SLUG_LENGTH = 6 MAX_SLUG_LENGTH = 200 # Users can register from age 0 to 180, but can't be kept on the site after age 250. MIN_AGE_ALLOWED_IN_MODEL = 0 # In years. MAX_AGE_ALLOWED_IN_MODEL = 250 # In years. MIN_AGE_ALLOWED_IN_FORMS = 0 # In years. MAX_AGE_ALLOWED_IN_FORMS = 180 # In years. MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 120 PASSWORD_VALIDATORS = [ { 'NAME': 'speedy.core.accounts.validators.PasswordMinLengthValidator', }, { 'NAME': 'speedy.core.accounts.validators.PasswordMaxLengthValidator', }, ] (which is defined in https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/net/settings/global_settings.py). And then in the models, I tried to use: from django.conf import settings as django_settings class User(ValidateUserPasswordMixin, PermissionsMixin, Entity, AbstractBaseUser): settings = django_settings.UserSettings (and then use attributes of settings, such as settings.MIN_USERNAME_LENGTH, in the class). But it throws an exception AttributeError: 'Settings' object has no attribute 'UserSettings' (but it doesn't throw an exception if I use there a constant which is not a class). This is the first problem. In the meantime, I defined instead: from speedy.net.settings import global_settings … -
Django ORM annotation with tree traversal
I'm using the django-mptt library to make categories for my project. The model is pretty simple: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField('Name', max_length=100, unique=True) color = models.CharField( 'Color', max_length=100, blank=True, null=True ) parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) class MPTTMeta: order_insertion_by = ['name'] Category color is optional and should be inherited from parent. So just to illustrate: Main Category 1 (red) -> Subcategory 1 -> Subcategory 2 (blue) -> Subcategory 3 (yellow) -> Subcategory 4 Subcategory 4 has no color defined and it inherits subcategory 3 color (yellow). Subcategory 1 inherits color from Main Category 1 (blue), etc. In my view i have the root category and then build a tree using get_descendants(include_self=True). How can i annotate color for each category of <TreeQuerySet>? For one model i have the following method: @property def inherited_color(self): if self.color: return self.color return (self .get_ancestors(ascending=True, include_self=True) .filter(color__isnull=False) .values_list('color', flat=True) .first()) But when this method is called for a list of categories it results in a lot of database queries! This is an example from django shell: >>> category <Category: 3> >>> category.color is None True >>> category.get_family().values_list('name', 'color') <TreeQuerySet [('1', '#51DCFF'), ('2', None), … -
How can I write my own permissions in django
I want to write my own permissions in Django, I mean I want to define exactly what a user can or cannot do, I have read this enter link description here but it seems change_task_status is sth predefined in Django. for example, I want to define exactly users can have access to just get method of a view and just from row 1 to 8 of the database table, and sth like this. How can I do this? -
Django | SuspiciousFileOperation error when creating a new profile object
I have an error when creating a new profile: SuspiciousFileOperation at /create_profil The joined path C:\Users\user\PycharmProjects\project\media\photo\2018\12\27\jhg.png) is located outside of the base path component (C:\Users\user\PycharmProjects\project\media\) These are my settings: STATIC_URL = '/static/' LOGIN_REDIRECT_URL = '/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' print("---------------------------" + MEDIA_ROOT) STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") This is my model: class Profil(models.Model): nom = models.CharField(max_length=120) image = models.ImageField(default='defaut.png', upload_to='image/%Y/%m/%d', blank=False, null=True) How can I get rid of this error? -
Django : Why POST urls are not working in Django AJAX?
I am creating a Like Button in Django using AJAX calls for my home page(where I have List of Posts which user can Like), For testing Logic of Like Button I had used normal(with page refresh) way to submit the form, and it works properly where I give URL as action='{% url "like_post" %}'. But when I went for AJAX based form submit I am Getting Error as POST http://127.0.0.1:8000/like/ 404 (Not Found). template.py: {% for post in all_posts %} <div class="posts" id="post-{{ post.id }}"> <h2 class="thought-title">{{ post.title }}</h2> <p class="content" id="{{ post.id }}" onclick="showWholeContent({{ post.id }})"> {{ post.content }} </p> <div class="post-footer"> <form id="like-form{{ post.id }}"> {% csrf_token %} <button type="submit" id="{{ post.id }}btn" name="like" value="{{ post.id }}" class="btn upvote">Like</button> <script type="text/javascript"> {% for like in post.likes.all %} {% if like != user %} {% else %} likingPost("{{ post.id }}btn"); {% endif %} {% endfor %} // Adding AJAX for Like button $(document).ready(function(event){ $(document).on('click', '#{{ post.id }}btn', function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: '{% url "like_post" %}', data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function(response){ } }); }); }); </script> </form> </div> </div> {% endfor %} urls.py: urlpatterns = [ path('like/', views.like_post, name="like_post") . . . ] views.py: def … -
In Django, how to count the number of data in model and output in admin?
I am building a model by Django, similar to the below one. I will import the food data one by one like {supermarket_id, Fruit, apple}. At the end, I want to count how many food are in Fruit category and show it in the admin page. How can I achieve this? Besides, should I separate the category into a new class and make it as a ForeignKey? Many Thank. models.py class Food(BaseModel): CATEGORY_TYPE = ['Vegetable', 'Meat', 'Fruit'] #supermarket foreignkey contain the id supermarket = models.ForeignKey(SuperMarket, on_delete=models.CASCADE, verbose_name='supermarket', help_text='supermarket') category = models.CharField(max_length=64, choices=CATEGORY_TYPE, default=CATEGORY_TYPE[0][0], verbose_name="Food_Cetagory", help_text="Food_Category" ) food = models.CharField(max_length=128, default="NULL", verbose_name="Name", help_text="Name" ) class Meta: verbose_name = 'Food_Pyramid' verbose_name_plural = 'Food_Pyramid' def __str__(self): return '%s:%s' % (self.category, self.food) admin.py class FoodAdmin(admin.ModelAdmin): list_display = ("supermarket", "category", "food", "number") -
How to add resend interval to django activation emails?
I have set up my django backend to send the activation email (with activation link) to the user's email address provided at registration. But recently, I have been getting spam attacks where the user (or bot or whatever) requests the activation link continuously and increases the load on my email server. To counter this, how can I add a time delay/interval between successive requests for an activation email to the same email address? Should I create a custom view for this? if so, what view should I look at modifying and how can I add a time interval that say restricts the user from requesting 1 an activation link every 5 or 10 mins?