Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Hide modal after form successful submition
I'm using Bootstrap Modals and HTMX to create an event in Django. I got the form rendering OK inside the modal, but when I submit the form the index page appears inside the modal (the success_url parameter of the CreateView). I'd like to hide the modal after the submission and then show the index full screen. This is the modal in the template: <!-- Start modal --> <button type="button" hx-get="{% url 'events:create' %}" hx-target="#eventdialog" class="btn btn-primary"> Add an event </button> <div id="eventmodal" class="modal fade" tabindex="-1"> <div id="eventdialog" class="modal-dialog" hx-target="this"> </div> </div> <!-- End modal --> And this is the Javascript that makes it show the modal: ;(function(){ const modal = new bootstrap.Modal(document.getElementById('eventmodal')) htmx.on('htmx:afterSwap', (e) => { if (e.detail.target.id == "eventdialog") modal.show() }) I tried adding this to the Javascript code but it doesn't work: htmx.on('htmx:beforeSwap', (e) => { if (e.detail.target.id == 'eventdialog' && !e.detail.xhr.response) modal.hide() }) How can I make the modal hide after submitting the form? This is my view: class CreateEvent(LoginRequiredMixin, CreateView): model = Event form_class = EventForm template_name = 'events/events_form.html' success_url = reverse_lazy('events:index') def form_valid(self, form): form.instance.author = self.request.user event_obj = form.save(commit=True) image = self.request.FILES.get('image') if image: EventImage.objects.create(title=event_obj.title, image=image, event=event_obj) return super(CreateEvent, self).form_valid(form) -
I want different authentication system for user and admin in djagno
I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in into user page. def userlogin(request): error = "" if request.method == 'POST': u = request.POST['emailid'] p = request.POST['pwd'] user = authenticate(username=u, password=p) try: if user: login(request, user) error = "no" return redirect(profile) else: error = "yes" except: error = "yes" return render(request, 'login.html', locals()) def login_admin(request): error = "" if request.method == 'POST': u = request.POST['uname'] p = request.POST['pwd'] user = authenticate(username=u, password=p) try: if user.is_staff: login(request, user) error = "no" else: error ="yes" except: error = "yes" return render(request,'login_admin.html', locals()) I want to achive different authentication system for user and also for admin. -
URL with parameters does not find static files Django
I'm making a URL with parameters but it does not find the static files because it adds the name of the URL to the location of the static files, with normal urls this does not happen (I already have some pages working like this). This is a url without parameters This is a url with parameters Look that add 'validador' to static file urls This is the function URLs file -
Django ORM ignoring globally related_name
I have a project with more than 100 models generated from PostgreSQL, when I use it there are many Reverse accessor clashes with ForiegnKey and ManyToManyFields. How can we ignore this functionality of Django globally, instead of adding related_name="+" for each model? -
Django rest Ecommerce category and product offers
I'm trying to acheive catgeory and product offers in my project and am unable to come up with a solution. Like if i give offer to a category all products price in category should get the offer and for products its individual. class Category(models.Model): category_name = models.CharField(max_length=15, unique=True) slug = models.SlugField(max_length=100, unique=True) class Meta: verbose_name_plural = "Category" class Products(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=500) price = models.IntegerField() images = models.ImageField(upload_to="photos/products") images_two = models.ImageField(upload_to="photos/products") images_three = models.ImageField(upload_to="photos/products") stock = models.IntegerField() is_available = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Products" def __str__(self): return self.product_name class CategoryOffer(models.Model): category = models.OneToOneField(Category, on_delete=models.CASCADE, related_name='cat_offer') valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(100)] ) is_active = models.BooleanField(default=False) def __str__(self): return self.category.category_name class ProductOffer(models.Model): product = models.OneToOneField(Products, on_delete=models.CASCADE, related_name='pro_offer') valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(100)] ) is_active = models.BooleanField(default=False) def __str__(self): return self.product.product_name So above are my models. I don't know how to implement, thought of many ways but it keeps leading to errors. -
Django pressing browser back button causes data to reappear
When a user adds a comment to a post, and they want to go back to the home page, and if they press the browser back button, the form cycles through every time the form had data that they had posted. The user has to press the back button (depending on the amount of comments made) at least 2 or 3 times to get to the home page. For Example: A user adds 1 comment to a form, they press the browser back button and the data that they just submitted appears and has to press the browser back button again A user adds 2 comments to a post, and they press the browser back button and they are on the same page with the last form submission data. They press the browser back button again and they are on the first form submission data. And so on.... I know that we can use a redirect call to the same or different page, but the comments need to update once submitted, and even then the data is still cached. Is there a way to have the user press the browser back button once and it will bring them back to … -
CSRF verification failed when used csrf_token and CSRF_TRUSTED_ORIGINS
I try to change my profile but when i subbmit my form, it shows CSRF verification failed even when i used csrf_token and CSRF_TRUSTED_ORIGINS. Here is my models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) avatar = models.ImageField(default='static/images/default.jpg', upload_to='static/images') @classmethod def create(cls, authenticated_user): profile = cls(user=authenticated_user, name= authenticated_user) # do something with the book return profile def __str__(self): return self.user.username My view: @login_required def profile(request): """Show profile""" # profile = UserProfile.objects.get(id= request.user) profile = UserProfile.objects.get(user=request.user) if request.method != 'POST': # No data submitted; create a blank form. form = UserProfileForm(instance=profile) else: # POST data submitted; process data. form = UserProfileForm(instance=profile, data= request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('base:index')) context = {'profile': profile} return render(request, 'users/profile.html', context) My template: {% if user.is_authenticated %} <p>Thong tin nguoi dung:</p> <a>Ten nguoi dung: {{profile.name}}</a> <p>Anh dai dien: <img src="{{profile.avatar.url}}" alt=""></p> <form action="{% url 'users:profile'%}" method="post"> {% csrf_token %} <input type="hidden" name="csrfmiddlewaretoken"> <p> <label for="id_name">Name:</label> <input type="text" name="name" maxlength="200" required="" id="id_name"> </p> <p> <label for="id_avatar">Avatar:</label> <input type="file" name="avatar" accept="image/*" id="id_avatar"> </p> <button name="submit">save changes</button> </form> {% else %} {% endif %} How can i sumit my form ? -
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! enter code here models.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() views.py class ActivateAccount(View): def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) messages.success(request, ('Your account have been confirmed.')) return redirect('login') else: messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.')) return redirect('login') token.py from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.profile.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Enter a valid email address') class Meta: model = User fields = [ 'password1', 'password2', ] -
Django App Engine deployment stops responding after 5 or 6 requests
I have been fighting this for a while now. Setup: I have Django 4 application running on Google App Engine (Standard) connected to Cloud SQL. Issue: I will load a page, and either refresh it 5 (ish) times or load 5 (ish) different pages. Then the application just stops responding. Observations: No errors are thrown. I have looked at the metrics and it doesn't appear anything is off. When I go to the instances page, they say they are "restarting" but they just are frozen there for many many minutes. Things I have tried: Manual, Basic, and Automatic Scaling Warmup requests Larger instance sizes Higher scaling thresholds Non-zero min instance sizes None of these items have changed the number of requests it takes to freeze the server. I have run the same server locally and it does not stop responding. Thanks people you make the world go round!