Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
bootstrap padding from sidebar
I am creating a site from scratch using Django and bootstrap. I've created a sidebar as a Django template and used {% include 'website/components/sidebar.html' %} to include it on all pages. but for each new page, the padding between the sidebar and any other content is not aligned. How do add a margin all the way around so that any content is central to the space between the sidebar and the edge of the screen? The sidebar is using some custom CSS and the rest of the site is using bootstrap. I've wrapped the content of the next page in container-fluid but I'm not sure about the approach. -
Django YearArchiveView with date in related model
I have this one-to-one relationship between my models: class Training(models.Model): date = models.DateField(unique=True) class Report(models.Model): training = models.OneToOneField( Training, on_delete=models.CASCADE, primary_key=True ) and would like to have a yearly archive of Report: class ReportYearArchiveView(generic.YearArchiveView): queryset = Report.objects.all() date_field = "training_date" However, I get the following error: FieldError at /reports/2022/ Cannot resolve keyword 'training_date' into field. Choices are: ..., training, training_id And with date_field = "training__date" I get FieldDoesNotExist at /reports/2022/ Report has no field named 'training__date' Any ideas? -
How to retrieve 2 datas and integrate them into api view?
body I need a help please. I'm going to build a API for an abstract/easy, so I'm writing the code as following: Python3.9 Django 3.2 gunicorn psycopg2-binary requests #models.py from django.conf import settings class Abstracts(models.Model): title = models.TextField(max_length=100) first_author = models.CharField(max_length=100, blank=True, null=False) first_author_unit = models.CharField(max_length=100, blank=True, null=False) author_list = models.TextField(null=True) author_unit_list = models.TextField(null=True) #views.py from .models import Abstracts from django.shortcuts import get_object_or_404 from django.http import JsonResponse def api_abstract_view(request, id): # API get abstract apiabs = get_object_or_404(Abstracts, pk=id) datas = { "title": apiabs.title, "first_author":{"name":apiabs.first_author, "unit":[apiabs.first_author_unit]}, "author_list": {"name":apiabs.author_list, "unit":[apiabs.author_unit_list]}, } return JsonResponse({"abstract": datas}) #url.py from .views import api_abstract_view app_name = 'abstracts' urlpatterns = [ path("apiabstractview/<int:id>/", api_abstract_view, name="api_abstract_view"), ] The output of json The abstract has been created, the json I got after accessing the id by url: http://127.0.0.1:8000/apiabstractview/9/ API URL : http://127.0.0.1:8000/apiabstractview/9/ { "abstract": { "title": The name of Title, "first_author": { "name": "First Author", "unit": ["C School", "A School", "D School"] }, "author_list": { "name": "2 author, 3 author", "unit": ["A School, B School, C School"] }, } } HOWEVER.... Please help, what should I do? As the result below. The result JSON I hope as below: author_list must be separated as a property individually. { "abstract": { "title": The … -
django-allauth custom user not working properly
I am trying to use Extra Data from Social accounts but first i need to create custom user, this is my approach, fields are created but for some reason they are not set to custom_field2 = "hey" #forms.py from allauth.socialaccount.forms import SignupForm from django import forms from pprint import pprint class MyCustomSocialSignupForm(SignupForm): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') custom_field1 = forms.IntegerField(label='Custom field 1') custom_field2 = forms.CharField(label='Custom field 2') def save(self, request): pprint(vars(request)) user = super(SignupForm, self).save(request) custom_field1 = 12 custom_field2 = "hey" user.custom_field1 = custom_field1 user.custom_field2 = custom_field2 user.save() return user #setting.py AUTH_USER_MODEL = 'MyUser.User' SOCIALACCOUNT_FORMS = {'signup': 'MyUser.forms.MyCustomSocialSignupForm'} #models.py from django.db import models from django.contrib.auth.models import AbstractUser from pprint import pprint class User(AbstractUser): custom_field1 = models.IntegerField(default=10) custom_field2 = models.CharField(max_length=20) #admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User class CustomUserAdmin(UserAdmin): fieldsets = ( *UserAdmin.fieldsets, # original form fieldsets, expanded ( # new fieldset added on to the bottom 'Custom Field Heading', # group heading of your choice; set to None for a blank space instead of a header { 'fields': ( 'custom_field1', 'custom_field2' ), }, ), ) admin.site.register(User, CustomUserAdmin) -
Increment Integer Field in Django
I am creating a simple blogging application and would like users to be able to like a post. In terms of scalability I've decided it would be best to have likes as a separate table made up of pointers to both the user and post. I have managed to enable the post request adding a like to the model however the likes field in the post model is not incrementing. I've tried using a simple likes += 1 technique in the serializer but that made no changes and have now used an F string but still no changes are being made. I am still fairly new to Django and suspect it may be because I'm trying to update a field on a different model within a CreateAPIView serializer but I'm not sure. This is what I have so far # views.py class LikeView(generics.CreateAPIView): permission_classes = [ permissions.IsAuthenticated, ] queryset = Like.objects.all() serializer_class = LikeSerializer def like(self, request, format=None): serializer = self.serializer_class(data=request.data) if(serializer.is_valid()): user_id = serializer.data.get('user_id') post_id = serializer.data.get('post_id') l = Like(user_id=user_id, post_id=post_id) l.save() # likes field not updating with this post = Post.objects.get(id=post_id) post.likes = F('likes') + 1 post.save() return Response(LikeSerializer(l).data, status=status.HTTP_200_OK) return Response(serializer.errors(), status=status.HTTP_400_BAD_REQUEST) #models.py class Post(models.Model): id = … -
How can I save the username in the database as an email?>
I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much! model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] # Sign Up Form class SignUpForm(UserCreationForm): # first_name = forms.CharField(max_length=30, required=False, help_text='Optional') # last_name = forms.CharField(max_length=30, required=False, help_text='Optional') email = forms.EmailField(max_length=254, help_text='Enter a valid email address') class Meta: model = User fields = [ 'username', 'password1', 'password2', ] views.py from django.contrib import messages from django.contrib.auth.models import Group from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from django.template.loader import render_to_string from .token import AccountActivationTokenGenerator, account_activation_token from django.shortcuts import render, redirect from .forms import * from django.contrib.auth import authenticate, login, logout from django.contrib.auth import get_user_model, login from django.utils.http import urlsafe_base64_decode from django.views.generic import View, UpdateView from django.contrib.auth.decorators import login_required from .decorators import * from django.urls … -
Pass audio from flutter to python?
I have a flutter app that converts a voice to text and I would like to pass the voice from flutter to python to convert it to text without saving the voice. I would like to transfer audio from the flutter to python without saving it -
what is the best way to create a custom admin panel in Django?
I want to create a custom admin panel in Django. what is the best way to do that ? I have found some ways : use some packages to customize that like jet, django-material-admin, django-cms, django-jazzmin create an admin app with python manage.py startapp admin and develop that with my own views and templates is there any better way to do that ? I want to know what professionals do. I would be grateful if you could introduce a clue or a helpful article. -
Can't install Django in visual studio code
So I'm creating a forum according to this tutorial: https://www.youtube.com/watch?v=YXmsi13cMhw&t=2594s I'm stuck at 2:10.I've successfully created a virtual enviroment, can't go past this error.enter image description here Where do I get project name?What on Earth is wrong here?Sorry if I got a little emotional. I tried to do everything exactly like in aforementioned tutorial. -
raise ParseError('JSON parse error - %s' % str(exc))
[views.py terminal errors page ](https://i.stack.imgur.com/YTK7f.png) myapp.py -
Checkbox ALWAYS returns False/ not in request.POST - Django
I have a checkbox on my django app, where user can add or remove a listing from their watchlist. However, this checkbox always returns False, and is never in request.POST, i have tried sooo many solutions from SO and all over the internet for literal days now and cant figure it out Models.py class Watchlists(models.Model): user = models.CharField(max_length=64, default='user') title = models.CharField(max_length=64, blank=True) watchlist = models.BooleanField(default=False, blank=False) def __str__(self): return f"{self.title}, {self.user}, {self.watchlist}" Forms.py class CheckForm(ModelForm): watchlist = forms.BooleanField(required=False) # watchlist = forms.DecimalField(widget=forms.CheckboxInput(attrs={"value":"watchlist"})) class Meta: model = Watchlists fields = ['watchlist'] Checkbox didnt have a value so i thought that was the issue and tried to give it one here on the commented line, it didnt help Views.py watchlist = CheckForm(request.POST or None) if request.method == 'POST': # if request.POST['watchlist']: # if 'watchlist' in request.POST: # if request.POST.get('watchlist', False): if request.POST.get('watchlist', '') == 'on': if watchlist.is_valid(): check = watchlist.cleaned_data['watchlist'] watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first() if not watchlist_data: watchlisted = Watchlists.objects.create(title=title, user=username, watchlist='True') watchlisted.save() if watchlist_data: watchlist_data.delete() I have tried all the different solutions i could find Template <form action="listing" method="POST"> {% csrf_token %} {{ checkbox }} </form> It has a name and id attribute, label is fine too -
Why Django doesn't see change when I add/remove a field from my models? [closed]
I removed a ForeignKey from a model and I guess the migration wasn't applied properly. It was three days ago and others migrations were applied since then. The problem is that now I'm unable to recreate the same ForeignKey because Django doesn't see the change in models.py when I comment or uncomment the field. I assume it thinks the migration is already applied but it's not because my code complains the relation doesn't exist. What is the best way to solve this issue ? class Account(TimestampedModel): name = models.CharField(max_length=50, null=True) # exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, related_name='account', null=True) # ForeignKey I cant recreate I have tried to specify the name of the application when calling makemigrations but it doesn't help. -
Deploy Django Project Using Pyinstaller
I have a django project, that works similar to Jupyter Notebook, in terms of Being a program launched offline in localhost on a web browser, moreover my webapp has an opencv webcam pop-up, that will be launched when you press a button. I want to deploy my django project, so it can be launched by just clicking a file in Windows. According to what I read, There are two possible solutions: Install Python Interpreter with Dependencies on client computer first, and using a bat file, to launch the django server. Containerizing the Django project with Python and its dependencies, either using Docker or perhaps an exe file? Which solution is better? I would prefer the second one personally, but I’m confused how to do so. Can it be done as simple as using pyinstaller or not? Here are my dependencies for reference: Django pillow django-object-actions django_user_agents django-cleanup opencv-python imutils cmake dlib face-recognition -
ImportError: cannot import name 'get_named_type' from 'graphql'
I am new to graphql, so I am trying to learn after installing graphene-django getting this error Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/mdhv/graphql/env/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/mdhv/graphql/env/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/mdhv/graphql/env/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/mdhv/graphql/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/home/mdhv/graphql/env/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/mdhv/graphql/env/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mdhv/graphql/env/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/mdhv/graphql/env/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/mdhv/graphql/env/lib/python3.10/site-packages/graphene_django/__init__.py", line 1, in <module> from .fields import DjangoConnectionField, DjangoListField File "/home/mdhv/graphql/env/lib/python3.10/site-packages/graphene_django/fields.py", line 5, in <module> from graphql_relay import ( File "/home/mdhv/graphql/env/lib/python3.10/site-packages/graphql_relay/__init__.py", line 7, in <module> from .connection.connection import ( File "/home/mdhv/graphql/env/lib/python3.10/site-packages/graphql_relay/connection/connection.py", line 3, in <module> from graphql import ( ImportError: cannot import name 'get_named_type' … -
Best way to deploy multiple client websites by Wagtail
I want to create wagtail website for my clients. The webistes will be identical and have same features, but the templates should be different. Every time I upate a feature to a new version, all websites will get the latest version automatically. By this approach, I don't need to deploy new feature versions (or base website version) to my clients separtely. I just need to deploy onec & all clients will get the latest website version. I will use 'Multi-instance' feature of Wagtail which seems to fit to my requirement. https://docs.wagtail.org/en/stable/advanced_topics/multi_site_multi_instance_multi_tenancy.html On this page, they mention 'Multi-instance' feature of Wagtail. Quote: "multiple sites share the same, single set of project files. Deployment would update the single set of project files and reload each instance." https://www.accordbox.com/blog/add-bootstrap-theme-wagtail/ Say, I want to have 2 different blog templates in this tutorial. The blog temlate file is 'post_page.html', and is a project file, so it will be deployed once and all website will get the same template, in the 'Multi-instance' feature of Wagtail. So my question is: How can I deploy one blog template (post_page.html) to one client website, & another blog template to another client website? -
OperationalError at /admin/app1/coursemodel/ no such column: app1_coursemodel.money
i tried to add a new field to already existing model and this is being displayed. class CourseModel(models.Model): cname = models.CharField(max_length=15) dur = models.IntegerField() fee = models.IntegerField() money = models.IntegerField() --- this is what is added I tried python makemigrations whc=ich is giving the follwing error: You are trying to add a non-nullable field 'money' to coursemodel without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models. -
Django request.session don't save data
I'm trying to retrieve the session data after login but it doesn't seem to be saving the information . class getSession(View): def post(self, request): print('====================>') print(request.session.get('usuario')) sesion = request.session.get('usuario') return JsonResponse({'nombre': sesion.nombre, 'rut':sesion.rut}) class Login(View): def post(self, request): data = json.loads(request.body) try: usuario = Usuario.objects.get(rut=data['rut'], password=data['password']) request.session['usuario'] = {'nombre': usuario.idpersona.name, 'rut': usuario.rut} request.session.modified = True #print(self.request.session['usuario']) return JsonResponse({'usuario':usuario.rut}) except: return JsonResponse({'usuario':'no existe'}) I'm get this error. AttributeError: 'NoneType' object has no attribute 'nombre' I'am using fetch with react. async login() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rut: this.state.rut, password: this.state.password, }), }; const response = await fetch("http://127.0.0.1:8000/test", requestOptions); const data = await response.json(); if (data.usuario == "no existe") { mensajeError("RUT o contraseña inválidos."); } else { mensajeExitoso("Usuario validado correctamente."); setTimeout(() => { window.location.href = "/Inicio"; }, 2000); } console.log(data.usuario); } try setting SESSION_SAVE_EVERY_REQUEST = True in settings.py -
How to programatically run custom command for specific schema using django-tenants?
I am new with django-tenants. I want to programatically run a cummand I have created with management.call_command() but I am getting error. Can someone help me with this? This command runs without error. I want to achieve same programatically. python manage.py tenant_command load_some_data --schema=<schema_name> my code: call_command('tenant_command', 'load_user_groups', schema_name=schema_name) I get following error: File "/home/stackuser/Desktop/DjangoPr/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 114, in call_command app_name = get_commands()[command_name] TypeError: unhashable type: 'list' -
Purpose of using an API
I'm learning API. So, I have a Django app, in development (I'm building it).I can also render my data (or user's data POST through forms) with urls.py, views.py and my template files. When runserver with localhost. I can GET,POST any data through processing some kind of forms and render it. So my question is, when my app is in production, should I need to write an API to GET,POST data. Here is my processing of views.py ` @login_required(login_url="login") def createProject(request): profile = request.user.profile form = ProjectForm() if request.method == "POST": form = ProjectForm(request.POST, request.FILES) if form.is_valid(): project = form.save(commit=False) project.owner = profile project.save() return redirect("account") context = {"form": form} return render(request, "projects/project_form.html", context) ` What's wrong with my thinking. Could u help me! Thanks -
How can I do this complex Django queryset correctly?
Let's say I have these three models: class Author(models.Model): name = models.CharField(max_length=64) class Book(models.Model): author = models.ForeignKey( Author, blank=True, null=True, on_delete=models.SET_NULL ) name = models.CharField(max_length=64) class Store(models.Model): books = models.ManyToManyField(Book) name = models.CharField(max_length=64) I don't know the author of some books. In these cases, the author is null. When I query Store, I would like to know how many books each store has and sort them. So my queryset is something like this: Store.objects.all().annotate(books_count=Count('books')).order_by('-books_count') Now, what if I want to count only the books that have an author? I tried this queryset, but it is clearly not correct: filter = Q(books__author__isnull=False) Store.objects.annotate(books_count=Count(filter)).all().order_by('-books_count') Does anyone know the correct way to do this query? -
Forbidden (403) CSRF verification failed. Request aborted-Real time chat application with Django Channels
I'm doing a course from YouTube "Python Django Realtime Chat Project - Full Course" and I'm new to django.My problem is, When I try to send message in room chat (submit form) I get this error Forbidden (403) CSRF verification failed. We don't have CSRFtoken in our form in room.html but The instructor fixed the error by adding e.preventDefault(); and return false; in submit querySelector block in room.html. I still get the error. when submitting the form message should add to div with chat-messages id. room.html: {% extends 'core/base.html' %} {% block title %} {{room.name}} {% endblock %} {% block content %} <div class="p-10 lg:p-20 text-center"> <h1 class="text-3xl lg:text-6xl text-white">{{room.name}}</h1> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id="chat-messages"> <div class="p-4 bg-gray-200 rounded-xl"> <p class="font-semibold">Username</p> <p>Message.</p> </div> </div> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <form method='POST' action='.' class='flex'> <input type="text" name="content" class="flex-1 mr-3" placeholder="Your message..." id="chat-message-input"> <button class="px-5 py-3 rounded-xl text-white bg-teal-600 hover:bg-teal-700" id="chat-message-submit"> send </button> </form> </div> {% endblock %} {% block script %} {{room.slug|json_script:"json-roomname"}} {{request.user.username|json_script:"json-username"}} <script> const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function(e) { … -
Is it possible to prefetch model with one query in this case?
Is it possible to prefetch Models B to Model A with one query or with minimal queries. I'm confused. Thanks. from django.db import models class ModelA(models.Model): pass class ModelB(models.Model): pass class ModelC(models.Model): model_a = models.ForeignKey(ModelA, related_name="models_a", on_delete=models.CASCADE) models_b = models.ManyToMany(ModelB, through="ModelD") class ModelD(models.Model): model_c = models.ForeignKey(ModelC, on_delete=models.CASCADE) model_b = models.ForeignKey(ModelB, on_delete=models.CASCADE) I'm do something like that, and it is work. But seems a bit ugly. models_a_list = ModelsA.objects.all() model_d_qs = ModelD.objects.select_related("model_c", "model_b") model_d_map = defaultdict(list) for d_item in model_d_qs: model_d_map[d_item.model_c.model_a.id].append(d_item.model_b) for a_item in models_a_list: settatr(a_item, "model_b_set", model_d_map.get(a_item.id)) return models_a_list -
How to convert Polygon object in Django GIS to an image
I am running a Django project, I created a Company model with company_activity_area field. My goal is to generate an image from the map. and even better, to generate a map image for each polygon. this is my code. from django.contrib.gis.db import models class Company(models.Model): company_activity_area = models.MultiPolygonField(null=True, blank=True, srid=4326, verbose_name='Area of Operation') def save(self, *args, **kwargs): for polygon in self.company_activity_area: # TODO: generate the map image for each polygon, where the polygon appear at the middle of the map super(Company, self).save(*args, **kwargs) -
How to get "starred mails" from Gmail or other mail services using IMAP_tools in django
I am able to get inbox emails and also able to get emails from specific folder but i am unable to get "starred" emails. I tried below code. and i am expecting emails with "starred flag" in response. from imap_tools import MailBox, A # Create your views here. def temp(request): #Get date, subject and body len of all emails from INBOX folder with MailBox('smtp.gmail.com').login('admin@gmail.com', 'password', 'INBOX') as mailbox: temp="empty" for msg in mailbox.fetch(): temp = (msg.date, msg.subject, msg.html) return HttpResponse(temp) -
How to import external .json file to Django database(sqlite)?
So, what is the basic thing I can do to initialize my Django database with the data I have in external .json file. I tried to upload through admin's page after running py manaeg.py runserver but there is no import options.