Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you add html meta-description to django blog post model?
I'm wondering if it's possible/google allows to add a meta_description CharField to Post model to dynamically change meta description on html page? My current meta description is <meta name="description" content="{{ post.title }} blog post from the {{ post.category }} category."> Which obviously isn't ideal as it doesn't give a great description of the individual blog post. Then I got to thinking of whether I can just add a field to set in the same manor. This way I would be able to set the CharField to max length so I know all meta descriptions are proper length, and I would be able to set a proper description for each blog post. class Post(models.Model): title = models.CharField(max_length =250) body = RichTextField(blank=True, null=True) meta_description = models.CharField(max_length=150) <meta name="description" content="{{ post.meta_description }}" Does anyone see any issues with this before I attempt to implement it? Does anyone know if this is allowed by Google? Thanks in advance. I would have attempted this first to see if it would work but I'm still quite new, and last time I attempted to add a field to an existing model with existing objects I screwed it up and all existing objects would cause an error, so … -
Replacing Bootstap svg placeholder image
https://getbootstrap.com/docs/4.0/examples/carousel/ I'm following along with this and implementing this in Django. HTML: <!DOCTYPE html> {% load static %} <!-- saved from url=(0052)https://getbootstrap.com/docs/5.0/examples/carousel/ --> <html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Hugo 0.82.0"> <title>Carousel Template · Bootstrap v5.0</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/carousel/"> <!-- Bootstrap core CSS --> <link href="{% static 'home/css/bootstrap.min.css' %}" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!-- Favicons --> <link rel="apple-touch-icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png"> <link rel="manifest" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/manifest.json"> <link rel="mask-icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon.ico"> <meta name="theme-color" content="#7952b3"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style> <!-- Custom styles for this template --><link href="{% static 'home/css/carousel.css' %}" rel="stylesheet"> <script data-dapp-detection="">!function(){let e=!1;function n(){if(!e){const n=document.createElement("meta");n.name="dapp-detected",document.head.appendChild(n),e=!0}}if(window.hasOwnProperty("ethereum")){if(window.__disableDappDetectionInsertion=!0,void 0===window.ethereum)return;n()}else{var t=window.ethereum;Object.defineProperty(window,"ethereum",{configurable:!0,enumerable:!1,set:function(e){window.__disableDappDetectionInsertion||n(),t=e},get:function(){if(!window.__disableDappDetectionInsertion){const e=arguments.callee;e&&e.caller&&e.caller.toString&&-1!==e.caller.toString().indexOf("getOwnPropertyNames")||n()}return t}})}}();</script></head> <body data-new-gr-c-s-check-loaded="14.1002.0" data-gr-ext-installed=""> <header> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="https://getbootstrap.com/docs/5.0/examples/carousel/#">Carousel</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="https://getbootstrap.com/docs/5.0/examples/carousel/#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="https://getbootstrap.com/docs/5.0/examples/carousel/#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" … -
ManyToManyField value is None
Im trying to use ManytoManyField for my Book , but it is showing None in web page and administration.Here is my code class Category (models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=40) author = models.CharField(max_length=30) description = models.TextField() category = models.ManyToManyField(Category) publish_year = models.CharField(max_length=5) language = LanguageField(max_length=40, default=False) age_group = models.CharField(max_length=5, choices=GROUP_CHOICES) downloaded_times = models.IntegerField() rate = models.FloatField() rate_times = models.IntegerField() rate_total = models.FloatField() book_image = models.ImageField(upload_to='book_cover_image', default="image.png") pdf_file = models.FileField(default=True, upload_to='media') def __str__(self): return f"{self.title}|-|{self.category}|-|{self.author}" In views.py I have def get_queryset(self): query = self.request.GET.get('q') object_list = Book.objects.filter( Q(title__icontains=query) ) print(Book.category) return object_list The Category looks like this: -
Post matching query does not exist. - Django error while trying to access URL of other pages
Everything was okay till I created a blog app in my Django projects, now when I try to access the other apps(pages) on the website, it gives me this error. I can't access the URLs under the other apps, I can only access the URLs under the blog blog/views.py from django.shortcuts import render, redirect from .models import Post from .forms import commentform def blog(request): posts = Post.objects.all(pk=id) return render(request, 'blog.html', {'posts': posts}) def howtouse(request): return render(request, 'howtouse.html') def full_post(request, slug): post = Post.objects.get(slug=slug) if request.method == 'POST': form = commentform(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('full_post', slug=post.slug) else: form = commentform() return render(request, 'full_post.html', {'post': post, 'form': form}) blog/models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() intro = models.TextField() body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_added'] class Comments(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField() body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['date_added'] -
How to limit the IO for postgres for a particular python script?
I have a server with nginx, gunicorn, django and postgres, which serves a website. In the background I need to have a script that is continuously consuming an external API and writing to the database. Currently I'm hitting the IO limit of my SSD (looking at nmon data) and as a result the website is very slow when the script is running. I read something about ionice that it can set an IO priority for a PID, but putting that on the python script doesn't help, because it's the postgres process that's doing the work. Is there a way to have a separate postgres process dedicated to that particular python script with limited IO? -
Write to an existing excel file using django and openpyxl,without deleting workbook or creating a new workbook
def xlsx(request): os.chdir('C:\\Users\\HP\\Desktop') workbook = openpyxl.load_workbook('example.xlsx') sheet = workbook['Sheet1'] Table = Usernames.objects.all() row = 2 col = 1 for items in Table: sheet.cell(row, col, items.ID) sheet.cell(row, col + 1, items.First) sheet.cell(row, col + 2, items.Last) row += 1 sheet['A1'] = 'ID' sheet['B1'] = 'First' sheet['C1'] = 'Last' response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=example.xlsx' workbook.save(response) return response Right now i am having trouble writing to the existing excel file 'example.xlsx'. When I run this request it creates a new workbook with the name 'example (1).xlsx'. Is there a way of writing to the exact same excel file without deleting or creating a new excel Workbook or Worksheet. -
Value of 'list_display[2]' refers to 'first_name', which is not a callable, an attribute of 'UserAdmin', or an attribute on 'authentication.User'
I am trying to add following code to admin.py to make sure that user's password created from django admin will be hashed. from django.contrib import admin from .models import * from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin class UserAdmin(DjangoUserAdmin): pass # Register your models here. admin.site.register(User, UserAdmin) But when i try i got following: <class 'authentication.admin.UserAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'first_name', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'authentication.User'. The User model looks like this class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) balance = models.FloatField(default=0.0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): """" Метод получения токена """ refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } def has_delete_permission(self, *args, **kwargs): return True if self.is_staff is True else False -
Django Bootstrap 4.0 Carousel Slider Not Working
https://getbootstrap.com/docs/4.0/examples/carousel/ I'm following along with this and implementing it in Django. There are no errors in the output console, so the static files (Bootstrap CSS + js) seem to be loading fine. HTML: <!DOCTYPE html> {% load static %} <!-- saved from url=(0052)https://getbootstrap.com/docs/5.0/examples/carousel/ --> <html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Hugo 0.82.0"> <title>Carousel Template · Bootstrap v5.0</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/carousel/"> <!-- Bootstrap core CSS --> <link href="{% static 'home/css/bootstrap.min.css' %}" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!-- Favicons --> <link rel="apple-touch-icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/apple-touch-icon.png" sizes="180x180"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png"> <link rel="manifest" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/manifest.json"> <link rel="mask-icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3"> <link rel="icon" href="https://getbootstrap.com/docs/5.0/assets/img/favicons/favicon.ico"> <meta name="theme-color" content="#7952b3"> <style> .bd-placeholder-img { font-size: 1.125rem; text-anchor: middle; -webkit-user-select: none; -moz-user-select: none; user-select: none; } @media (min-width: 768px) { .bd-placeholder-img-lg { font-size: 3.5rem; } } </style> <!-- Custom styles for this template --><link href="{% static 'home/css/carousel.css' %}" rel="stylesheet"> <script data-dapp-detection="">!function(){let e=!1;function n(){if(!e){const n=document.createElement("meta");n.name="dapp-detected",document.head.appendChild(n),e=!0}}if(window.hasOwnProperty("ethereum")){if(window.__disableDappDetectionInsertion=!0,void 0===window.ethereum)return;n()}else{var t=window.ethereum;Object.defineProperty(window,"ethereum",{configurable:!0,enumerable:!1,set:function(e){window.__disableDappDetectionInsertion||n(),t=e},get:function(){if(!window.__disableDappDetectionInsertion){const e=arguments.callee;e&&e.caller&&e.caller.toString&&-1!==e.caller.toString().indexOf("getOwnPropertyNames")||n()}return t}})}}();</script></head> <body data-new-gr-c-s-check-loaded="14.1002.0" data-gr-ext-installed=""> <header> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="https://getbootstrap.com/docs/5.0/examples/carousel/#">Carousel</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto … -
Why is my navbar comepletely on the left side?
So I wanted to paste a navbar straight from the bootstrap website and when I opened it on my browser, it was completely on the left side, and I can't figure it how to fix it. I am using Django. Thanks in advance. {% extends 'base.html' %} {% block content %} <nav class="navbar navbar-expand-lg navbar-light bg-danger"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> {% endblock %} -
Django Allauth asking for password 3 times in signup page
I'm trying to implement a signup form with django-allauth and everything works as it should. However I've implemented a CustomUserCreationForm that displays the fields listed below and since then its been asking for the password 3 times. I only want to ask for the password once but it seems to add the password and password confirmation fields automatically now (see image below). Even if I remove all fields the two password fields still remain. In my settings I've already set the ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False but still shows the password field three times. Any help would be appreciated! Forms.py from django.contrib.auth import get_user_model from .models import CustomUser from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ("first_name", "last_name", "mobile", "email", "password") Models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): first_name = models.CharField(max_length=55, default="") last_name = models.CharField(max_length=55, default="") mobile = models.CharField(max_length=12, default="") Allauth settings AUTH_USER_MODEL = "accounts.CustomUser" SITE_ID = 1 AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" LOGIN_REDIRECT_URL = "home" ACCOUNT_LOGOUT_REDIRECT = "home" ACCOUNT_SESSION_REMEMBER = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_FORMS = {"signup": "accounts.forms.CustomUserCreationForm"} HTML Output -
problem with django form (list and form in 1 view)
My problem is that after submitting the form. It looks like this, submit the form and then reload the page after submission, I can see the title movie in the list, but under the form it says "this title is in the database". I will be extremely grateful for any hint :) class MovieListWithForm(ListView, ModelFormMixin): model = Movie form_class = MovieForm template_name = 'pages/movie_list.html' def get(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) return ListView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): # When the form is submitted, it will enter here self.object = None self.form = self.get_form(self.form_class) if self.form.is_valid(): self.object = self.form.save() self.form = MovieForm() return self.get(request, *args, **kwargs) def get_context_data(self, *args, **kwargs): # Just include the form context = super(MovieListWithForm, self).get_context_data(*args, **kwargs) context['form'] = self.form context['list'] = Movie.objects.all().order_by('votes') return context class MovieForm(ModelForm): class Meta: model = Movie fields = ['title'] def __init__(self, *args, **kwargs): super(MovieForm, self).__init__(*args, **kwargs) self.fields['title'].label = "Movie title" def clean_title(self): data = self.cleaned_data['title'] if Movie.objects.filter(title=data).exists(): raise ValidationError("this title is in base") if data == None: raise ValidationError("Add title") return data -
Django nginx 413 Request Entity Too Large
After logining the admin page it is returning 413 error (Request Entity Too Large). Than I added client_max_body_size to my /etc/nginx/nginx.conf and restarted nginx, but it didnt helped :( I know that this error is a common one, but I had to ask this question because there is no more information that about client_max_body_size. user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; client_max_body_size 100; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } #mail { # # See sample authentication script at: # # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript # # # auth_http localhost/auth.php; # # pop3_capabilities "TOP" "USER"; # # imap_capabilities "IMAP4rev1" "UIDPLUS"; # # server { # … -
Change the default for a model on a form
how in forms.py class, overwrite the default value of the model category, without adding it to the html form? forms.py class FastForm(forms.ModelForm): class Meta: model = Orders fields = ['device'] models.py class Orders(models.Model): device = models.CharField(max_length=150) category = models.ForeignKey('Category', default=1, on_delete=models.PROTECT) class Category(models.Model): category = models.CharField(max_length=150, db_index=True) -
Is it possible to assign jinja variable to id of an anchor tag without using javascript only in html?
HTML {%with pid='a1' %} {%endwith%} <a href="https://www.google.com/" id="{{pid}}" >Google</a> -
django.db.utils.ProgrammingError: can't adapt type 'set'
I'm using Django lookup has_key but I get the error of django.db.utils.ProgrammingError: can't adapt type 'set'. This is the part of my code where I use has_key: programs = Program.objects.values('title', 'details', 'date_added').order_by('date_added') if program.duration: programs = programs.filter(details__duration__has_key=program.duration) paginator = Paginator(programs, 10) page_obj = paginator.get_page(program.page) list(page_obj) data={ 'results': page_obj.object_list, 'total_records': paginator.count, 'page': page_obj.number, 'has_next': page_obj.has_next(), 'has_prev': page_obj.has_previous(), } return data Part of data where I use has_key query: "details": { "duration": { "full_time": { "quantity": 24, "period": "months", "description": "" } }, } How can I solve it? -
Django multiple slug urls
I have two kind of slugs: path('<slug:category_slug>/', butik_views.category_page_view), path('<slug:shop_page_slug>/', butik_views.shop_page_view), Category slugs are working fine, but if I open a shop_page URL, it looks in category view and not in the shop_page_view. Is there something i missed? regards -
how to write for action when programing with django
i want to write form action to call newpost function from viwes.py , newpost function has 2 arguments which are newpost(request,myid), but when i tried to write action="{%url 'newpost' %}" an error appears like this : TypeError at /newpost newpost() missing 1 required positional argument: 'myid' how can i send this argument in form action ? please tell me def newpost (request,myid): blockedperson=[1] assert isinstance(request, HttpRequest) print("if1") print (request.POST.get('postcontent')) print (type(request.POST.get('postcontent'))) while request.POST.get('postcontent'): print ("if2") if myid not in blockedperson : savepost=post() savepost.person_id= 437819147 savepost.content=request.POST.get('postcontent') savepost.p_date=dt.datetime.now() savepost.save() else : blocked="sorry, you are blocked, you can not share a post, for more information contact with IT on 437819147@kku.edu.sa" return render (request,'home.html',{'block':blocked}) allpost=post.objects.all() allperson=person.objects.all() allstudent=student.objects.all() allteacher=teacher.objects.all() allcomp=company_rep.objects.all() return render (request,'home.html',{'posts':allpost , 'person':allperson,'student':allstudent,'teacher':allteacher,'comp':allcomp,'id':myid}) <form name="postbox" action="{%url 'newpost' %}" method="POST" align="center"> {% csrf_token %} <label>shear your ideas, information, and experience...</label> <br /> <textarea id="post" name="postcontent" rows="4" cols="50"> </textarea> <br /> <input style="width: 31%;" type="submit" value="post" name="postsubmit"> </form> -
django.db.utils.OperationalError: no such column: home_post.assign_to_id
I want to assign a task to one of the users who commented on the post. But when I try to go on post_detail.html an error occurs, and i.e. OperationalError at /home/ no such column: home_post.assign_to_id So, here is the code snippet. I can give more information if needed. Thanks in advance! views.py def SaveAssigned(request): if request.method == "POST": if request.POST.get('assigned'): savevalue = Post() savevalue.assign_to = request.POST.get('assigned') savevalue.save() return render(request, 'post_detail.html') else: return render(request, 'post_detail.html') models.py class Post(models.Model): title = models.CharField(max_length = 100) snippet = models.CharField(max_length= 200) content = RichTextField(blank=True, null=True) date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete= models.CASCADE) category = models.CharField(max_length=255, default='Coding') assign_to = models.ForeignKey(User,related_name='assign_to', on_delete=models.CASCADE, null=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('home') post_detail.html {% extends 'users/base.html' %} {% block body %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ object.author }}</a> <small class="text-muted">{{ object.category }}</small> <small class="text-muted" style="float: right;">{{ object.date_posted|date:"F d, Y" }}</small> </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content|safe }}</p> </div> </article> {% if object.author == user %} <div> <a class="btn btn-outline-secondary bt-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-outline-danger bt-sm mt-1 mb-1" href="{% url … -
Django user created from admin panel can't authenticate
I have custom User model class User(AbstractBaseUser, PermissionsMixin): """ Модель User - пользователь сайта """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) balance = models.FloatField(default=0.0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokens(self): """" Метод получения токена """ refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } The admin.py file looks like this from django.contrib import admin from .models import * # Register your models here. admin.site.register(User) The login serializer looks lie this class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255, min_length=3) password = serializers.CharField(max_length=68, min_length=6, write_only=True) username = serializers.CharField(max_length=255, min_length=3, read_only=True) tokens = serializers.SerializerMethodField() def get_tokens(self, obj): user = User.objects.get(email=obj['email']) return { 'refresh': user.tokens()['refresh'], 'access': user.tokens()['access'] } class Meta: model = User fields = ['email', 'password', 'username', 'tokens', 'id'] def validate(self, attrs): """ Валидация email и password """ email = attrs.get('email', '') password = attrs.get('password', '') user = auth.authenticate(email=email, password=password) if not user: raise AuthenticationFailed('Invalid credentials, try again') if not user.is_active: raise AuthenticationFailed('Account disabled, contact admin') if not user.is_verified: raise AuthenticationFailed('Email is not verified') return { 'email': user.email, 'username': user.username, 'tokens': … -
how to show data through input tag
I am working on a Django project .In front-end I want to add user data through input tags but I do not know how to save data through input tags A part of my register.html file is: <div class="card-body"> <h2 class="title">Registration Form</h2> <form method="POST">{% csrf_token %} <div class="row row-space"> <div class="col-2"> <div class="input-group"> <label class="label">Full name</label> <input class="input--style-4" type="text" name="first_name"{{form.full_name}}> </div> </div> <div class="col-2"> <div class="input-group"> <label class="label">Sur name</label> <input class="input--style-4" type="text" name="last_name"{{form.sur_name}}> </div> </div> </div> I just want the Django model field to be working in input tags -
How to get interconnected records in django?
I have a django model called Person and PersonRelation class Person(model.Models) person_name = models.charfield(max_length=255, blank=False) person_address = models.charfield(max_length=255, blank = False) class PersonRelation(model.Models): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='sibling_of') person_relation = models.ForeignKey(Person, on_delete=models.CASCADE) Now Lets say: SAM is Related to JOHN SMITH is Related to JOHN TOM is related to SMITH How can I get all the related siblings from the database? Required output of related siblings: SAM - JOHN - SMITH - TOM -
Why is fetch always returning undefined here?
I am working on a Unit Conversion API, and I am having a lot of issues with fetch(). My backend API is working, for example, when I call curl "http://localhost:8000/unitconv/convert?to=lb&from=kg&value=10" I get the correct response: {"units": "lb", "value": 22.04623}. Yet when I do the exact same thing with fetch(), this is what I get: I have tried both localhost and 127.0.0.1 and I still cannot get past this "undefined". What's wrong here? -
model condition in admin panel
I created several tables in models.py and in these tables I have a table named "Asset" that I added assets. my Asset table features are name, description, point geometry and line geometry. For this table, when I enter the django admin panel and add assets with "+ Add", I want an option to appear first. A or B will be selected as an option. If I press A, let only name, description and point geometry come from properties of Asset table for asset record. If I press B, the name, description and line geometry come up. How do I do this conditional choice? -
How to display Model in each HTML template?
But create a request in each functions inside views.py I do not want. Is it possible to output the model in each template using only one request? I tried to use templateetags but that so @register.simple_tag(takes_context=True) def header_categories(context): return Categorie.objects.all().order_by('id') what is like that @register.simple_tag(takes_context=True) def header_categories(context): categories = Categorie.objects.all().order_by('id') args = {} for cat in categories: args[cat.text] = { 'id':cat.id, } if cat.parent: args[cat.text]['parent_id'] = cat.parent.id args[cat.text]['parent_text'] = cat.parent.text return args Nothing works correctly {% for cat in header_categories %} cat.text {% endfor %} I tried through js var arr = {%header_categories%} but django changes everything {&#x27;dresses&#x27;: {&#x27;id&#x27;: 19}, -
FileField not populated after validation error
In my form I have several FileFields. If I provide a file with a wrong extension I get a Validation Error. When the form is reloaded the validation errors are shown. But the other FileFields with the correct filse are not populated anymore and I have to upload those file again. In other words: all the textfiels etc. are filled after reloading. I would like to have the FileFields also filled. Any ideas? Thanks in advance! views.py def artist_application(request): if request.method == 'POST': form = Form(request.POST, request.FILES) if form.is_valid(): genre = form.cleaned_data.pop('genre') instance = Artist(**form.cleaned_data) tag = Tag.objects.filter(id__exact=1).first() # add tag Artist Application instance.save() instance.tag.add(tag) for g in genre: instance.genre.add(g) return render(request, 'application_form.html', {'form': form, 'artist': instance}) else: form = ApplicationForm() return render(request, 'application_form.html', {'form': form}) application_form.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2>Artist Application</h2> {% if form.errors or form.non_field_errors%} <div class="errors"> <p>Please adjust the following fields:</p> {{ form.errors }} {{ form.non_field_errors }} </div> {% endif %} {% crispy form %} {% endif %} {% endblock %} forms.py from django.forms import ModelForm, BooleanField from artist_application.models import Artist, Genre from dal import autocomplete from crispy_forms.helper import FormHelper from crispy_forms.bootstrap import AppendedText from crispy_forms.layout import Layout, …