Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not detecting new changes to models
I just added a new field to my model, but when running python manage.py makemigrations it won't detect anything and when visiting the admin interface the new field won't show up. I'm using postgresql as database. class Movies(models.Model): title = models.CharField(max_length=30, blank=True, null=True) ###(...)### director_name = models.CharField(max_length=30, blank=True, null=True) keywords = models.ManyToManyField('Keywords', through='MoviesKeywords', related_name='movies')# This is the new field class Meta: managed = False db_table = 'movies' (keywords is the new field) I already tried passing the name of the app into the command like this: python manage.py makemigrations recommendations But I also get nothing in response. -
How to use a variable or change href in HTML using javascript (Django)
So right now in my navbar I have it as the following: <a class="nav-link" href="/home/{{applicant}}">Home </a> {{applicant}} returns the applicant's id (int). For security purposes I've decided to use a basic encryption so that someone can't easily guess a persons id. The encryption is simply some math done to the id ((((((id * 3) + 5 ) * 63 ) - 1 ) * 218 ) - 5) which while obviously not secure is good enough for the project. How would I apply this in the html using either django or javascript to modify the real id so that the href points to their encrypted id? I'm looking for something like below: <a class="nav-link" href="/home/" + encrypted id>Home </a> -
How to color html table in django based on condition
class11=[10,20,30,76] class12=[23,45,23,45] <table> <tr> <th>Class11</th> {% for class1 in class11 %}<td>{{class1}} </td> {% endfor %} </tr> <tr> <th>Class12</th> {% for class2 in class12 %}<td>{{class2}} </td> {% endfor %} </tr> </table> How to color Class 11 based on conditions : if value > 20 to color to red if value > 40 to color orange if value > 50 to color green I serached web they recomedn js but i am not good with js quite new. Is there nay way to do in CSS? -
Error: Using the URLconf defined in mysite.urls, Django-3 tried these URL patterns, in this order:,
I'm doing tutorial "Blog" from "Django 3 by example" and I got error. What i'm doing wrong? Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/ amd alsp TemplateDoesNotExist at /blog/. Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current URL, blog/, didn't match any of these. BLOG ADMIN mysite/urls.py from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), ] mysite/blog/views.py from django.shortcuts import render, get_list_or_404 from .models import Post # Create your views here. def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'post': posts}) def post_detail(request, year, month, day, post): post = get_list_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) mysite/blog/admin.py from django.contrib import admin from .models import Post # Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') prepopulated_fields = {'slug':('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ('status', 'publish') mysite/mysite/urls.py from django.urls import path, include from mysite.blog import admin from . import views app_name = 'blog' urlpatterns = [ # post views path('', views.post_list, name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), ] … -
How to remove unwanted css and js from your django application?
I'm making a Fullstack application which uses Django as a backend and javascript and jquery as a frontend.The app is finished now I want to remove unwanted css,images,js which just lie there in static files but are not used in templates is there a way to remove all of this unwanted code,files.I checked on the internet and there are solutions like purgecss but they use npm for running and I don't have npm Is there any other way to it easily or if I have to do it by using purgecss.Can you guide me all the way in the answer section. Thank you -
Django - Message translation in template does not work
Translations in the same function for form.error work and messages are displayed in a different language, but for "messages" the text is still displayed in English in the template views.py from django.utils.translation import ugettext_lazy as _ form.errors['__all__'] = form.error_class([_('Bad pin')]) Works messages.add_message(self.request, messages.INFO, _('Bad pin')) Did not work, in the template after entering {{message}}, I see the English version Settings.py 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "account.middleware.LocaleMiddleware", 'django.middleware.common.CommonMiddleware', "account.middleware.TimezoneMiddleware", -
How to design an app with djano and node to make an appointment app/webapp
Where can I get proper tutorials or the steps/reference to develop an django app with node and google calendar integrated. for booking purpose. -
why flask app is not updating the browsing after reloading?
I am beginner in flask, I am facing issue in updating the template when i run the app flask run for the first time it works currently, but when I update the html or the python code and then reload the page the update does not effect in the browser i tried different browser but still doesn't work then i have to restart the IDE and run the app again this is my code from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__": app.run(debug=True) -
How to obtain multiple values from the drop down box django?
I am trying to obtain 2 values from an HTML dropdown menu as follows: <form action="POST"> <select name="season" id="season"> <option value="" selected disabled>Choose an option</option> <option value="Running">Running</option> <option value="2021">Summer 2021</option> </select> <h4>Select The Enrollment Batch:</h4> <select name="level" id="level"> <option value="" selected disabled>Choose an option</option> <option value="class-9">CAIE O Level (class 9)</option> <option value="class-10">CAIE O Level (class 10)</option> <option value="class-11">CAIE AS Level</option> <option value="class-12">CAIE A2 Level</option> </select> <button type="submit" class="btn deep-orange darken-2">Submit</button> </form> Is that even the proper way to obtain the data? Does the data come in as a tuple? What should the Django form be like and how do i save it in views? -
Django hosting for web development [closed]
How to host Django website in Google Cloud platform? -
keep getting this error{relation "profiles_user" does not exist}
I am a beginner programmer working on my own project on Django. I am trying to make a model create itself whenever a user is created. but i keep getting this error {relation "profiles_user" does not exist}. I am using PostgreSQL as my DB. from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save class User(AbstractUser): is_expert = models.BooleanField(default=False) is_student = models.BooleanField(default=False) EDUCATION=( ('Collage','Collage'), ('Post_Graduate','Post_Graduate'), ('Masters','Masters'), ('PHD','PHD'), ) class Expert(models.Model): expert = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(max_length=12, null=True, default='') last_name = models.CharField(max_length=20, null=True) discription = models.TextField(null=True) education = models.CharField(max_length=200, choices=EDUCATION, null=True) field = models.CharField(max_length=200, null=True) company = models.CharField(max_length=50,null=True) position = models.CharField(max_length=20, null=True) experience = models.TextField(null=True) charge_per_hour = models.IntegerField(default="0") def __str__(self): return (f'{self.first_name} {self.last_name}') def create_profile(sender,**kwargs ): if kwargs['created']: user_profile=Expert.objects.create(expert=kwargs['instance']) post_save.connect(create_profile,sender=User) Thank you for your help in advance -
url contains spaces in django v3
I'm trying to create my first django rest framework project and this is the scenario I'm stuck in. In project's urls.py file I have this: urlpatterns = [ path('admin/', admin.site.urls), # other paths path("api/", include("users.api.urls")), # other paths ] While in users/api/urls.py file I have this: urlpatterns = [ path("user/", CurrentUserAPIView.as_view(), name="current-user") ] What I can't understand is why If I go to localhost the list of urls look like this: admin/ ... other paths **api/ user/ [name='current-user']** ... other paths As you can see there is a space before "user" in the line between asterisks. If I go to http://localhost:8000/api/user/ I receive this error: 'str' object is not callable and I read it is related to a url configuration problem. -
PATCH method not working in Django ModelViewSet
I'm having trouble in using patch method inside a ModelViewSet for my custom User model. Here is the code: views.py @permission_classes([IsAdminUser]) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer http_method_names = ['get', 'post', 'patch', 'head', 'delete'] serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'password', 'is_active', 'is_staff', 'is_admin') extra_kwargs = {'password': {'write_only': True, 'required': True}, 'is_active': {'default': True}, 'is_staff': {'default': False}, 'is_admin': {'default': False}} def create(self, validated_data): self.is_valid(raise_exception=True) if validated_data['is_admin']: validated_data['is_staff'] = True user = User.objects.create_user(**validated_data) return user def update(self, instance, validated_data): instance.email = validated_data.get('email') instance.is_active = validated_data.get('is_active') instance.is_staff = validated_data.get('is_staff') instance.is_admin = validated_data.get('is_admin') if instance.is_admin: instance.is_staff = True instance.save() return instance I set a permission in order to allow only superuser to access this view. The problem comes when trying to perform a patch. For example, if I try to change is_staff attribute to False of a User using Postman with PATCH and "http://localhost:8000/users/USER_ID", I get the following error: django.db.utils.IntegrityError: null value in column "email" violates not-null constraint DETAIL: Failing row contains (1, pbkdf2_sha256$180000$6jePqBspO6xK$tCQ9zZk1uOdJD2F7L9BQRFFDbz1GXJ..., 2020-04-18 20:02:57.052639+00, null, t, t, t). It seems like django asks me to provide every single field fo User model (email, is_active, is_staff, is_admin), which it doesn't make sense in my … -
ValueError at /pembayaran/ ModelForm has no model class specified. django
from . import forms from django.shortcuts import render from .forms import pembayaran #Create your views here. def index(request): return render(request, 'index.html') def pembayaran_function(request): form=pembayaran() if request.method=='POST': form=pembayaran(request.POST) if form.is_valid(): form.save() context={'form':form} return render(request, 'pembayaran.html', context) what's wrong in my views? i don't know to handle this pls help me, thanks before -
Can't find module name using Django
I created a faker script but when I try to run it I get an error saying: 'ModuleNotFoundError: No module named 'new_project'' Here's my 'populating.py' code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','new_project.settings') import django django.setup() import random from homepage.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t= Topic.objects.get_or_create(top_name=random.choice(topics)) [0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake_date) [0] if __name__=='__main': print("populating script") populate(20) print('populating complete') and here's my Project Browser: Project Browser Thank you in advance for any sugestions! -
Django Signup form inside modal box
Hi everyone in my Django Website I've got a modal box that opens whenever the user click on the singup button. I'd like the form to be shown inside the box. I didn't use the forms.py file for the form but a simple function like this in the views.py. Anyway the form doesn't appear, what am I doing wrong? Thanks views.py def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'search/home.html', {'form': form}) -
Django-Graphene: No module named 'graphql_jwt'
I'm trying to implement authentication with Django and GraphQL/graphene I've run into the error No module named 'graphql_jwt'. and the solutions I've found don't seem to work Reproducing The code is available here: https://github.com/altear/hello-GraphQL.git It uses docker-compose, so you should be able to run it with just docker-compose up -d --build The error is immediately visible if you go to http://localhost:8000 What I've Tried Other posts that have this error don't seem to be applicable: one mentions having another folder named "graphql" in the python path, so my environment should be clean another mentions not having installed graphql. However, it's in my requirements.txt and it worked before I tried adding authentication -
how can i use sockets with connexion?
Is there a way to send real-time messages from a connexion backend to a django frontend ?For example send status messages every 10 seconds or the progression of a request in real time. The documentation isn't clear and I didn't find a complete example -
Set pk=pk in Django
I am trying to make a blog with Django which contains three equally looking sections, each of them displays some posts that correspond to each of those sections (One to many relationship for each section, one section contains many posts but each post can only be a part of one section). The posts also look the same in format. My template in index.html: {% for PostSection in postsections %} <section id="posts"> <a id="posts-header" href="#"> <h2>{{ PostSection.section_heading }}</h2> <img src="{% static 'main/img/icn/down-arrow.svg' %}" alt=""> </a> <h1 class="hello-posts">{{ PostSection.section_desc }}</h1> <div class="swiper-container swiper2"> <div class="swiper-wrapper"> {% for Post in posts %} <div class="swiper-slide" id="posts-slide"> <a href="posts/arch01.html"> <img src="{{ Post.post_img.url }}" alt="{{ Post.post_desc }}"> <div class="slide-posts-txt"> <h5>{{ Post.post_heading }}</h5> <div class="slide-posts-txt-desc"> <p>{{ Post.post_desc }}...</p><img src="{% static 'main/img/icn/plus-circle.svg' %}" id="read-more-plus" alt=""> </div> </div> </a> </div> {% endfor %} </div> <div class="swiper-button-next swiper-button-next2" id="next"><p>Next</p></div> <div class="swiper-button-prev swiper-button-prev2" id="prev"><p>Previous</p></div> </div> </section> {% endfor %} My models.py: class PostSection(models.Model): section_heading = models.CharField(max_length=30) section_desc = models.CharField(max_length=300, blank=True, null=True) def __str__(self): return f"{self.section_heading}" class Post(models.Model): post_section = models.ForeignKey(PostSection, on_delete=models.CASCADE, related_name="posts") post_heading = models.CharField(max_length=30) post_desc = models.CharField(max_length=300, blank=True, null=True) post_img = models.ImageField(upload_to= 'architecture', blank=True, null=True) def __str__(self): return f"{self.id} - {self.post_heading} - {self.post_desc}" My views.py: def index(request): context = { … -
summernote rtl plugin giving error of "can only concatenate tuple (not "set") to tuple"
Hi im using the summernote on my django application and want to allow arabic to be written,I seen this plugin, but when i add the js file to the summernote config I receive the following error "can only concatenate tuple (not "set") to tuple" https://github.com/virtser/summernote-rtl-plugin Setting.py SUMMERNOTE_CONFIG = { # Using SummernoteWidget - iframe mode, default 'iframe': True, # To use external plugins, # Include them within `css` and `js`. 'js': { '../guide/static/summernote/summernote-ext-rtl.js' }, # You can put custom Summernote settings 'summernote': { 'disableResizeEditor': False, # Change editor size 'width': '100%', 'border':'0px', 'height':'545px', 'minHeight': 'null', 'maxHeight': 'null', # Use proper language setting automatically (default) 'lang': None, 'toolbar': [ ['style', ['bold', 'italic', 'underline']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['picture'], ['video'], ['table'], ['hr'], ['ltr','rtl'], ], }, } -
Many-To-Many relationships with Postgresql and accesing them
I'm working with a Posgtgresql database about movies, and I have a few Many-to-Many relationships like the following one: There's a table with movies and each movie has some keywords, as well as two movies can have the same keyword. For that we have three tables: movies, keywords, and movies_keywords. The table named movies is self-explanatory, it contains the title, an ID and many attributes that a movie has. The table movies_keywords has two columns: a movie ID and a keyword ID. This is like the "middle" that connects the two other tables. Lastly, the table keywords contains a keyword ID and the corresponding keyword. The problem is the following: I'm working with Django and I need to access all the keywords for one movie, but they're not directly connected, there's this middle point that doesn't let me access the names. Do you have any idea how can this be achieved? Thanks in advance! -
Django change change default profile picture by gender
I want to change default profile picture depen on gender.I choose Male in Register Form but always display "default_f.png". models.py GENDER_CATEGORY = ( ('U','Undefined'), ('F','Female'), ('M','Male') ) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to="profile_pics",verbose_name="") cover_image = models.ImageField(default="default_cover.jpg",upload_to="cover_pics",verbose_name="") bio = models.CharField(max_length=160,null=True,blank=True) location = models.CharField(max_length=30,null=True,blank=True) birth_date = models.DateField(null=True,blank=True) follow = models.ManyToManyField(User,related_name="follower") date_created = models.DateTimeField(default=timezone.now) gender = models.CharField(choices=GENDER_CATEGORY,max_length=2) Signals So I try this if statement but always show default_f.png.I change pre_save to post_save but it didn't change. def post_save_avatar(sender, instance, *args, **kwargs): if not instance.image: if instance.gender == 'M': instance.image="default_m.jpg" else: instance.image = "default_f.png" print(instance.gender) pre_save.connect(post_save_avatar, sender=Profile) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile,sender=User) forms.py class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username','email','password1','password2') class ProfileRegisterForm(forms.ModelForm): class Meta: model = Profile views.py def register(request): if request.method == "POST": form = RegisterForm(request.POST) p_form = ProfileRegisterForm(request.POST) if form.is_valid() and p_form.is_valid(): user = form.save() user.refresh_from_db()#load the profile instance create by the signal p_form = ProfileRegisterForm(request.POST,instance=user.profile) p_form.full_clean() p_form.save() # username = form.cleaned_data.get('username') return redirect('login') else: form = RegisterForm() p_form = ProfileRegisterForm() context = { 'form':form, 'p_form':p_form } fields = ['bio','gender'] -
Images in Django aren't loading even though they're stored locally
With the code I have currently, my images used to load but now they don't and I can't figure out why. Within my Artist model, I have included an ImageField. This lets me upload an image and store it in a directory called 'artists' in my media directory. class Artist(models.Model): name = models.CharField(max_length=40) genre = models.CharField(max_length=20) location = models.CharField(max_length=20) bio = models.TextField() photo = models.ImageField(upload_to='artists', null=True, blank=True) def __str__(self): return self.name As you can see below, my image 'fontaines.png' has been uploaded and stored in /media/artists/. ├── db.sqlite3 ├── manage.py ├── media │ ├── artists │ │ └── fontaines.png ├── mysite │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ ├── urls.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── settings.py │ ├── static │ │ └── main.css │ ├── templates │ │ └── base.html │ ├── urls.py │ └── wsgi.py └── pages ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-38.pyc │ ├── admin.cpython-38.pyc │ ├── apps.cpython-38.pyc │ ├── forms.cpython-38.pyc │ ├── models.cpython-38.pyc │ ├── urls.cpython-38.pyc │ └── views.cpython-38.pyc ├── admin.py ├── apps.py ├── forms.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_artist.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-38.pyc │ … -
Path is not matching
I have started learning Django and I was watching this lecture (till starting 20 minutes) and following the instructions but I am getting the error as : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello Using the URLconf defined in lecture3.urls, Django tried these URL patterns, in this order: admin/ The current path, hello, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. After running python3 manage.py runserver My settings.py file in "lecture3" app is : # Application definition INSTALLED_APPS = [ 'hello', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] and some other content. views.py file in "hello" app is : from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return HttpResponse("Hello World!") urls.py file in "hello" app is : from django.urls import path from . import views urlpatterns=[ path("",views.index, name="index") ] urls.py file in "lecture3" app is : from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('/hello/', include('hello.urls')) ] I have checked similar questions here but my problem was not resolved. Can … -
ValueError at /pembayaran/ ModelForm has no model class specified
from django import forms from django.forms import ModelForm from .models import pembayaranform class pembayaran(ModelForm): class Meta: models = pembayaranform fields='__all__' what's wrong?