Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultiValueDictKeyError at /api/users/ - Django
So I'm trying to create a backend API using django and django rest framework, I'm trying to implement a login system using custom tokens, So I'm trying to make it so that when you put your login information in get request then it is supposed to take that information and return you a token but I'm running into some errors, When I first load up the page by typing http://localhost:8000/api/users/?username=admin?password=12345 I get MultiValueDictKeyError at /api/users/ error. Here is my code: class UserTokenHandler(APIView): def get(self, request, format=None): username = request.GET['username'] password = request.GET['password'] user = User.objects.filter(username=username) if user.exists(): if user.password == password: chosen_token = '' for i in range(20): lower_case = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'] upper_case = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] random_choice = random.randint(1,3) if random_choice == 1: chosen_token += lower_case[random.randint(0, len(list) -1)] elif random_choice == 2: chosen_token += numbers[random.randint(0, len(list) -1)] elif random_choice == … -
mibian library version check in python
I am developing django project How can I check mibian version in run time of code import mibian print mibian.__version__ the bug result AttributeError: module 'mibian' has no attribute '__version__' -
include looged used in utils.py django
I have created an HTML calendar in the utils.py, where it created the events I would like to make it so that it uses the events of the user logged. There is a session created with the username. utils.py from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Event from myProject.helper import get_current_user class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal Does anyone have a solution on how I can achive that? -
Favicon not appearing
For some reason my favicon is not appearing on chrome. I am using django. And I have a file named favicon.ico in my static folder. {% load static %} <link rel="icon" href="{% static 'favicon.ico' %}"/> -
How do i get rid of value error, the view xxx didn't return an HttpResponse Object. It returned none instead
so im doing cs50x web development and the assignment is creating a wikipedia page. I created a views function where I can click on edit page to edit the content. However I keep running into this problem.enter image description here This is my code from views.py class EditForm(forms.Form): body = forms.CharField(label= "Body") def edit_page(request): title = request.POST.get("edit") body = util.get_entry(title) form = EditForm(initial={'body': body}) if request.method == "POST": form = EditForm(request.POST) if form.is_valid(): content = form.cleaned_data["body"] util.save_entry(title, content) return render(request, "encyclopedia/title.html", { "title": title, "content": util.get_entry(title) }) else: return render(request, "encyclopedia/edit.html", { "form": EditForm() }) urls.py: urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.title, name="title"), path("search", views.search, name="search"), path("new_page", views.new_page, name="new_page"), path("random", views.randomizer, name="random"), path("edit", views.edit_page, name="edit") ] title.html: <form action= "{% url 'edit' %}", method= "POST"> {% csrf_token %} <button type="submit" name="edit" value="{{title}}" id="edit">Edit Page</button> </form> and finally edit.html <form action="{% url 'edit' %}" method="POST"> {% csrf_token %} {{form}} <input type="submit"> </form> Someone please help me to solve this issue thanks! -
how to install proj4 in ubuntu , make: *** No targets specified and no makefile found. Stop. geodjango
i'm following the geodjango docs proj4 section , i have installed proj-7.0.1.tar.gz and proj-datumgrid-1.8.tar.gz , and untar them as in the docs mentioned , but when i try to run make command after directory ./configure it returns make: *** No targets specified and no makefile found. Stop. it there something i have missed ! or maybe i have used a wrong version thank you -
Django: Iterate through static files in HTML
I followed this answer. Iterate through a static image folder in django So I have {% with 'images/'|file as image_static %} <img src="{% static image_static %}" alt=""> <a class="gallery-one__link img-popup" href="{% static image_static %}"><i class="tripo-icon-plus-symbol"></i></a> {% endwith %} I did pass the context dict correctly in views, I think, because I saw this in my traceback: context_dict = {} files = os.listdir(os.path.join(settings.STATIC_ROOT, "blog/images/gallery")) context_dict['files'] = files But I'm not sure why it's giving me the following error django.template.exceptions.TemplateSyntaxError: Invalid filter: 'file' I also tried {% load crispy_forms_filters %} at the start of the HTML but it's not making a difference. I'm quite new to this, so I'm probably doing something stupid, and I cannot find any docs referring to this specific instance -
Django Rest Framework append object to many to many field without deleting the previous one
I am new to DRF and could not figure it out how to append an object to the many to many field without deleting the previous one. I am using PATCH to update the field MONITORS however the previous value gets substituted by the actual one. I want to append it. API GET is: ''' { "id": 1, "created": "2018-05-02T23:43:07.605000Z", "modified": "2021-04-03T10:25:12.280896Z", "companies_house_id": "", "name": "Ellison PLC", "description": "", "date_founded": "2018-04-28", "country": 4, "creator": 7, "monitors": [ 3 ] } ''' after PATCH {"monitors":[11]} I get: ''' { "id": 1, "created": "2018-05-02T23:43:07.605000Z", "modified": "2021-04-03T10:25:12.280896Z", "companies_house_id": "", "name": "Ellison PLC", "description": "", "date_founded": "2018-04-28", "country": 4, "creator": 7, "monitors": [ 11 ] } ''' I want the final GET API to be "monitors": [3 , 11] models.py ''' class Company(TimeStampedModel): companies_house_id = models.CharField(max_length=8, blank=True) name = models.CharField(max_length=200, blank=True) description = models.TextField(blank=True) date_founded = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.PROTECT, blank=True) creator = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='companies_created' ) monitors = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='companies_monitored', help_text='Users who want to be notified of updates to this company' ) def __unicode__(self): return u'{0}'.format(self.name) ''' serializers.py ''' from rest_framework import serializers from .models import Company from django.contrib.auth import get_user_model class CompanySerializer(serializers.ModelSerializer): class Meta: model = … -
Why is custom user password not getting set and authenticated?
I thought it would be a breeze to swap the User model's username with its email. So I am using a CustomUser. from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ from .managers import UserManager class CustomUser(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() Since CustomUser is inherited from AbstractUser model, I thought I was done, but I guess I am still far from it. Here's my django shell interaction: >> from django.contrib.auth import get_user_model >> User = get_user_model() >> User.objects.get(email='dave@gmail.com').password '123' # wutt? why is this plaintext? >> User.objects.get(email='dave@gmail.com').set_password('abc') >> User.objects.get(email='dave@gmail.com').password '123' # still same! So functionally, this is completely useless. Since django.contrib.auth.authenticate for the users always returns None. What am I doing wrong? How can I achieve the minimal functionality that my CustomUser is only different from default django User model in that my CustomUser should use email as the username? I have already checked out the SO hits: Django User password not getting hashed for custom users django custom user model password is not being hashed EDIT: I'm using the following as my UserManager from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): … -
Hi there !, I'm learning django as my first framework for backend, i face this error and not yet find way to fix it? hope someone will help me
File "C:\Users\tumatijr\Desktop\portfolio-project\portfolio\urls.py", line 24, in Path('/', views.home, name='home'), NameError: name 'Path' is not defined and this is the urls from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), Path('', jobs.views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
add_to_cart() missing 2 required positional arguments: 'product_id' and 'quantity'
i am beginner I don't know what to do sorry please help me Traceback Traceback (most recent call last): File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\daghe\Dev\ecommerce - Backup\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /cart/add/ Exception Value: add_to_cart() missing 2 required positional arguments: 'product_id' and 'quantity' urls.py from django.urls import path from .views import ( cart_home, add_to_cart, remove_from_cart, checkout_home, checkout_done_view ) app_name = 'carts' urlpatterns = [ path('', cart_home, name='home'), path('checkout/success', checkout_done_view, name='success'), path('checkout/', checkout_home, name='checkout'), path('add/', add_to_cart, name='add-item'), path('remove/<product_id>/', add_to_cart, name='remove-item'), ] views.py def add_to_cart(request, product_id, quantity): product = Product.objects.get(id=product_id) cart = Cart(request) cart.add(product, product.unit_price, quantity) def remove_from_cart(request, product_id): product = Product.objects.get(id=product_id) cart = Cart(request) cart.remove(product) def cart_home(request): cart = Cart(request) return render(request, 'carts/home.html', {"cart":cart}) -
django wsgi with apache2 configuration gives page not found 404
For assumption here testsite.com which is my php application and testsite.com/project is python-django application I have following settings in my apache site config file /etc/apache2/sites-available/site.conf <VirtualHost *:443> ServerAdmin webmaster@testsite.com ServerName testsite.com DocumentRoot /var/www/html WSGIDaemonProcess test python-path=/var/www/html/projectenv/test-project python-home=/var/www/html/projectenv WSGIProcessGroup test WSGIScriptAlias /project /var/www/html/projectenv/test-project/test-project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> NOTE: I have to keep WSGIScriptAlias as /project since only for this url my django project should work. But when I hit testsite.com/project its giving following error Page not found (404) Using the URLconf defined in test-project.urls, Django tried these URL patterns, in this order: admin/ project/ The empty path didn't match any of these. Here is my project url structure urlpatterns = [ path('admin/', admin.site.urls), path('', include('projectapp.urls')) ] projectapp/urls.py from django.urls import path from . import views urlpatterns = [ path('project/', views.home, name='project'), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'projectapp', ] Please suggest solution that when I hit this url testsite.com/project it should go through my defined django app and render the page which is linked to this view, Its observed that wsgi is not able to pass through the django project structure and due to which its not identifying the url given in app. … -
How to use the file path of a .csv file in Django project(Web app)
I have a Django project that can get the .csv file from the user. Now I want to do analyze the .csv file on my Django project. How can I get the path of the file from my Django project to do this? Here is my Django settings: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'files') I would like to analyze the data saved in the media and then try to show the result like a table in the web application. If you any sample code that helps me in that case please share it. I hope you understand the problem. Thanks in advance -
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 { # …