Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
What is the best practice of unique_together & auto-populated created_by work together?
I use the below codes for a long time and nothing is wrong. Now, when I start using djagno-rest-framework, I start wondering the way I used to do. I have a model Diary like this: class Diary(models.Model): date = models.DateField(verbose_name=_('Date'), default=today) created_by = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: unique_together = (('date', 'created_by')) With this DiaryModelForm, it works fine: class DiaryModelForm(forms.ModelForm): class Meta: model = Diary exclude = ['created_by'] def full_clean(self): super().full_clean() try: self.instance.validate_unique() except forms.ValidationError: self.add_error(field='date', error=_('The diary with this date has already existed.')) In the create/update views I use them like this: def diary_create(request): instance = Diary(created_by=request.user) if request.method == 'POST': form = DiaryModelForm(request.POST, instance=instance) if form.is_valid(): instance = form.save() def diary_update(request, pk): instance = get_object_or_404(Diary, pk=pk, created_by=request.user) if request.method == 'POST': form = DiaryModelForm(request.POST, instance=instance) if form.is_valid(): instance = form.save() They work fine. By just passing a different instance, I can easily handle logic of create/update views. The processes seems consistent. When I start using django-rest-framework, I try to convert what I do with from ModelForm to ModelSerializer, but I found that hard. Some method names (like full_clean) between thses two class are a little different. And some ways I found in their doc seems convenient, but not the … -
502 bad gateway for django site
I deployed my Django app to gcloud and everything uploads with no error but when I go on the site it comes up with a 502 bad gate way. I've checked the logs and this error pops up. textPayload: "Container called exit(1)." insertId: "6067eaaf00085f11035507b0" resource: {2} timestamp: "2021-04-03T04:10:23.548428287Z" severity: "WARNING" labels: {1} Any ideas on this? I've been stuck on this all day, I have my app.yaml done properly (to my knowledge) and the database in settings.py runs fine. -
Error after changing from sqllite3 data base to PostgreSQL
I have been running into some error after changing from sqllite3 database to PostgreSQL.Here is some of the error. ValueError at /post/None/ Field 'id' expected a number but got 'None'. Request Method: GET Request URL: http://127.0.0.1:8000/post/None/ Django Version: 3.1.6 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'None'. Exception Location: /home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/lib/python3.7/site-packages/django/db/models/fields/__init__.py, line 1778, in get_prep_value Python Executable: /home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/bin/python Python Version: 3.7.5 Python Path: ['/home/mike/Web/mercy', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/mike/.local/share/virtualenvs/mercy-TKuV6FoL/lib/python3.7/site-packages'] Server time: Sat, 03 Apr 2021 06:52:29 +0300 and here is some code in the views.py file def post(request, id): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] post = get_object_or_404(Post, id=id) if request.user.is_authenticated: PostView.objects.get_or_create(user=request.user, post=post) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = post form.save() context = { 'form': form, 'post': post, 'most_recent': most_recent, 'category_count': category_count, } return render(request, 'post.html', context) -
Why is my Pillow app not working with Django
I tried to include ImageField to my models in models.py of the model Topic. When I tried to migrate the model. It is not working. It says that I need to install pillow (which I did and when I tried again it is still not working. Please refer to this video The video thats shows how this doesn't work Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): text = models.CharField(max_length = 200) date_added = models.DateTimeField(auto_now_add = True) image = models.ImageField(upload_to = 'backgroud_images', null = True, blank = True) owner = models.ForeignKey(User,on_delete = models.CASCADE) def __str__(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic,on_delete = models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = "Entries" def __str__(self): return self.text[:50] the INSTALLED_APPS list from settings.py.Is it because I didn't include pillows in here? INSTALLED_APPS = [ 'learning_logs', 'users', 'bootstrap4', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Ubuntu/Django/Postgres degrading server performance over several hours until server becomes unresponsive
I have a website running on an AWS EC2 instance with Django and Postgres. Also I have a python script constantly running and writing to the database. CPU and RAM seem fine, but after several hours the server starts slowing down and eventually becomes unresponsive. I can't even SSH into it to check what's going on. The only option is to force reboot it. What troubleshooting would you recommend? -
How can i register my new router inside urls file
I'm working on a small project using Django Rest Framework, and I create my first application successfully called (contact), now i created a second one called List, I would like to know how can I register the router again that's what I did to register my first application called ( contact ) I created a file called router.py inside my contact/api/ router.py from django.urls import path from contact.api.views import ContactView from rest_framework import routers router = routers.DefaultRouter() router.register(r'contact', ContactView, basename="contact") and I have included router.py in my urls.py by doing : from django.contrib import admin from django.urls import path, include from contact.api.router import router urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] NB : Until the moment everything is OK Now how can i register my second file router.py of my list application inside urls again