Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Strawberry GraphiQl explorer tries to use websockets and falls with 500 error and "Connection reset by peer" (with Django)
I am using Strawberry with Django And there is a path to GraphiQl explorer in urls.py: from strawberry.django.views import GraphQLView urlpatterns = [ ... path('graphql', GraphQLView.as_view(schema=schema)), ] And while there is a browser tab with http://127.0.0.1:8000/graphql it continuously makes requests to ws://127.0.0.1:8000/graphql each 10 seconds, that causes next errors on back each request: Internal Server Error: /api/ Traceback (most recent call last): File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/Max/Documents/env/py38/lib/python3.8/site-packages/strawberry/django/views.py", line 50, in dispatch data = json.loads(request.body) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) [02/Jun/2020 00:22:45] "GET /api/ HTTP/1.1" 500 92779 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 57288) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, … -
Django can AJAX field filter be designed with CreateView?
I already ahve a CreateView which handles creating objects. I am wondering if I can simply put an AJAX response in the get method to allow for the form fields to be filtered based on previous selections. e.g. If a user selects an option in the "Category" field called "Food/Beverage" then I send over an AJAX request to GET the queryset which is filtered for that Category, then update the form. Is this how it is accomplished? Is this usually done in the get_queryset method or another method? Is this normally done in a separate view? Should I be using a generic View which is sparate from the CreateView for this? -
What is the use of SlugField in django?
Note: Please dont consider it as duplicate post, all the existing posts are not giving clear understanding of SlugField. My question is "we can sluggify and store the value in a CharField right? then why do we need SlugField for something that can be done easily using CharField?" For example, in my model, I have a field called url = models.CharField(max_length=30) def save(self, ...): self.url = slugify(self.url) ....... Won't the url be saved in slugified format in database? I can use this slugified value in browser right, then what is the use of creating models.SlugFIeld(max_length=30)? What advantage SlugField will add over slugified CharField? -
Accessing foreign keys from the Django template
This is my models.py: class dateEvent(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) class Event(models.Model): title = models.CharField(max_length=50) view.py: def events_list_view(request): events = dateEvent.objects.all() context = { 'dateEvents': dateEvents, } return render(request, 'events/events_list.html', context) template: {% for event in dateEvents %} <tr> <td>{{ dateEvent.start_date_time }}</td> <td><a href="{% url 'event-detail' id=? %}">{{ dateEvent }}</a></td> # I want the event id here <td>{{ dateEvent.venue_event }}</td> {% endfor %} How can I get the Event id which is linked to that dateEvent in my template? Using dateEvent.event_set doesn't seem to work. -
Django - getting "'File' object has no attribute 'read'" error when saving image from url and connecting to ImageField
Basically, my goal is to save an image (for example, this one) to an ImageField. After reading this post, my code currently looks like this: from future import division from django.db import models from django.urls import reverse from io import BytesIO import os import mimetypes from PIL import Image as PilImage import urllib.request from upload.utils import ext_to_format from requests import get from django.core.files.temp import NamedTemporaryFile class File(models.Model): url = models.URLField(null=True, blank=True) image = models.ImageField(null=True, blank=True) def save(self): if self.url and not self.image: img_temp = NamedTemporaryFile() img_temp.write(urllib.request.urlopen(self.url).read()) img_temp.flush() self.image.save("image_%s" % self.pk, File(img_temp)) # error arises self.save() When I run the code, error yields saying: AttributeError: 'File' object has no attribute 'read' The full traceback is: Traceback (most recent call last): File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\edit.py", line 172, in post return super().post(request, *args, **kwargs) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\edit.py", line 142, in post return self.form_valid(form) File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\views\generic\edit.py", line 125, in form_valid self.object = form.save() File "C:\Users\Edgar\AppData\Local\Programs\Python\Python35\lib\site-packages\django\forms\models.py", line 458, … -
Combine parent-childs into one queryset
I have the following model: class Task(models.Model): name = models.CharField(max_length=200, default='New task') start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) task_status = models.IntegerField(default=0) parent = models.ForeignKey( 'self', related_name='childs', null=True, blank=True, on_delete=models.SET_NULL) My app exposes an API endpoint, which return all parent tasks in a data range and all parent tasks with status 0, and all their childs. The filter needs to be applied for parents only, since childs may have different start date and statuses. I need to return all results in a single list. Currently I'm doing it this way: class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all().order_by('id') serializer_class = TaskSerializer @action(detail=False, methods=['post']) def get_tasks(self, request): daterange = request.data.get('daterange') items = list() parents = Task.objects.prefetch_related("childs") .filter(start_date__range=daterange, parent__isnull=True) | Task.objects.prefetch_related("childs") .filter(task_status=0, parent__isnull=True) for parent in parents: items.append(parent) items = items + list(parent.childs.all()) serializer = self.get_serializer(items, many=True) return Response(serializer.data) I was wondering, is it possible to obtain the final result (all parents and childs in one list) using only django queryset methods? If not, is there a more efficient way of doing this (given that the number of tasks may be very large)? Thanks! -
NoReverseMatch at /event/vent_detail/3/myguest/
New to Django and can't figure this out, I'm using a header to view event details such as myguest list and keep getting this error, please help :) NoReverseMatch at /event/vent_detail/3/myguest/ Reverse for 'vent_detail_myguest' with arguments '('',)' not found. 1 pattern(s) tried: ['event/vent_detail/(?P\d+)/myguest/$'] (views.py) def vent_detail_myguests(request,pk): current_vent = Vent.objects.get(pk=pk) user_vent = current_vent.myguest myguests = user_vent.users.all() return render(request, 'event/vent_detail_myguest.html', {'myguests': myguests}) (urls.py) re_path(r'^vent_detail/(?P<pk>\d+)/myguest/$', vent_detail_myguests, name='vent_detail_myguest'), (header_template.html) <a class="gaelvents" href="{% url 'event:vent_detail_myguest' vent.pk %}">MyGuests</a> (vent_detail_myguest.html) {% for object in myguests %} <div class="single-guest-container"> <a class="username" href="{% url 'guest:profile_view' pk=object.pk %}">{{object.username}}</a> <a class="profilepic" href=""><img class="profilepic" src="{% static 'guest/images/logo.png' %}"></a> <a class="remove" href="{% url 'guest:connect_guest' adding='remove' pk=object.pk %}">Remove<a/> </div> {% endfor %} (models.py) class Vent(models.Model): event = models.CharField(max_length=15, blank=False, unique=True) date = models.CharField(max_length=15, blank=True) city = models.CharField(max_length=15, blank=True) venue = models.CharField(max_length=15, blank=True) website = models.CharField(max_length=15, blank=True) info = models.CharField(max_length=300, blank=True) myguest = models.ForeignKey(MyGuest, on_delete=models.CASCADE) def __str__(self): return self.event class Meta: ordering = ['event'] -
Django: python manage.py runserver SyntaxError
I had the server running fine before but now whenever I put "python manage.py runserver" in to terminal it produces the below error. Python and Django are both installed in the correct locations. I'm using Python 3.6 and I'm on Windows 10. C:\Users\liam\code\python\django_project>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\liam\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in … -
Problem while showing active selection on Wagtail navbar
I am trying to highlight the active selection on a navbar in Wagtail. It works if the navbar does not call a new page <li class="nav-item"> <a class="nav-link active" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> But if the link points to a new page, <li class="nav-item"> <a class="nav-link active" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About</a> </li> the highlight shows until the new page is loaded and then disappears. My complete code is: base.html {% load static wagtailuserbar %} <html class="no-js" lang="en"> <head> <meta charset="utf-8" /> <title> </title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {# Global stylesheets #} <link rel="stylesheet" type="text/css" href="{% static 'css/wagtail_nav.css' %}"> {% block extra_css %} <link rel="stylesheet" href="https://bootswatch.com/4/lumen/bootstrap.min.css" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/my.css' %}"> {% endblock %} </head> <body class="{% block body_class %}{% endblock %}"> <div class="container"> <br> <nav class="container-fluid navbar navbar-expand-sm bg-dark navbar-dark" style="padding-left: 75px; margin-top: -16px;"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About</a> </li> </ul> </nav> </div> {% block content %}{% endblock %} {% block extra_js %} <script type="text/javascript" src="{% static 'js/my.js' %}"></script> {% endblock %} </body> </html> my.css .navbar-dark .nav-item .nav-link.active { color:white; background-color: green; } my.js $('.navbar-nav … -
After deploying Django, I am having trouble adding the column and redeploying it
I deployed a Django project using elasticbeanstalk, but after adding columns to the USER table, there was a problem while redeploying. Folder location : .ebextensions/02-django.config Previous container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true 02_createsu: command: "django-admin createsu" 03_collectstatic: command: "django-admin collectstatic --noinput" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "config/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings I used this time container_commands: 01_makemigrations: command: "django-admin.py makemigrations" 02_migrate: command: "django-admin.py migrate" 03_createsu: command: "django-admin createsu" 04_collectstatic: command: "django-admin collectstatic --noinput" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "config/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings However, an error occurred. I think the migration does not seem to work. Is the command wrong??? error django.db.utils.ProgrammingError: column users_user.hint_question does not exist LINE 1: ...sers_user"."gender", "users_user"."login_method", "users_use... ^ I am in the USER model Added hint_question and hint. Any help would be greatly appreciated!! Thank You:) -
django : django.db.utils.OperationalError: no such table:
I'd like to make a category field. so I make a class category in same model.py file.(Im trying to make default value in category like : IT,Marketing,Design, etc...) but there is an error when I'm trying to make migrate: django.db.utils.OperationalError: no such table: preassociations_category How can I solve it? Do i have to make another app? models.py class Category(models.Model): name = models.CharField(max_length=300) class Preassociation(core_models.TimeStampedModel): category = models.ManyToManyField( Category, related_name="category", blank=True ) -
how to make django dynamic URL works properly with django form
This is my form <form action="{%url 'topicname' %}" method="GET"> <input type="search" placeholder="Search topics" name="searchtopic"> <button type="submit">Search</button> </form> This is my View def searchtopic(request): if request.method == 'GET': mysearchtopic = request.GET['searchtopic'] mydata = myhashtaglist.objects.filter(slug = mysearchtopic) context = { 'mydata':mydata, } return render(request, 'hzone/result.html',context) This is my result.html page {% for m in mydata %} <a href="{% url 'topicname' m.slug %}">{{ m.relatedhashtag }}</a> {% endfor %} This is mu urls.py urlpatterns = [ path('', views.apphome, name = 'homepage'), path('topic/', views.searchtopic, name = 'topicname'), ] what i want is whenever user click on any of the topic on result page this topic should open. reult page should look like intro to django django tutorial 1 django tutorial 2 django tutorial 3 but when i am clicking on any of the topic its not taking me to that topic. -
DRF create object with nested serializers and foreign keys
I am using DRF and I'm trying to create an object which has several foreign keys as well as related objects that will need creating in the process. Here's what a reduced version of my models looks like: class Race(models.Model): name = models.CharField(max_length=200) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='races') type = models.ForeignKey(Type, on_delete=models.SET_NULL, related_name='races', null=True) region = models.ForeignKey(Region, on_delete=models.CASCADE, verbose_name=_('region'), related_name='races') country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='races') timezone = models.ForeignKey(Timezone, on_delete=models.SET_NULL, null=True) class Event(models.Model): name = models.CharField(max_length=200) race = models.ForeignKey(Race, on_delete=models.CASCADE, related_name='events') And then here's my Race serializer: class RaceSerializer(serializers.ModelSerializer): owner = UserSerializer(read_only=True) type = TypeSerializer(read_only=True) events = EventSerializer(many=True) country = CountrySerializer() region = RegionSerializer(read_only=True) timezone = TimezoneSerializer(read_only=True) def create(self, validated_data): with transaction.atomic(): events = validated_data.pop('events', None) race = Race(**validated_data) race.save() for event in events: Event.objects.create(race=race, **event) return race And my view: class AddRaceView(CreateAPIView): serializer_class = RaceSerializer permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(owner=self.request.user) And here's some test data I'm sending with my POST request: { "name": "ABC Marathon", "country": { "pk": 1, "name": "United States" }, "region": { "pk": 1, "code": "ME" }, "timezone": { "pk": 1, "code": "EST" }, "events": [ { "name": "Marathon" }, { "name": "Half Marathon" } ] } So the problem I'm having is passing valid … -
display a table showing model instances as rows and let users select instances (rows) to delete
In my app, users can upload files. These files are represented by a model with attributes for associated meta-data (upload time, file name, user created note, max value, etc). A user will upload several files and I want to show them a table of their uploaded files with a checkbox next to each row that can be used to delete selected files and associated model instances. I'm not sure what the right approach is, I've looked at the following options but there doesn't seem to be an obvious solution: 1. model forms, using CheckboxSelectMultiple 2. django_tables2 3. reuse the django admin model form-view-template The default django admin app behavior is perfect for my use case, but I'm not sure what the best way is to reproduce it? app/models.py import uuid from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Document(models.Model): def rename_file(self, filename): ext = filename.split('.')[-1] new_name = uuid.uuid4().hex return f'documents/{new_name}.{ext}' owner = models.ForeignKey( User, on_delete=models.CASCADE, editable=True, ) document = models.FileField(upload_to=rename_file) notes = models.CharField(max_length=258, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True) nice_name = models.CharField(max_length=128, null=True, blank=False) start_date = models.DateField(null=True, blank=False) end_date = models.DateField(null=True, blank=False) def __str__(self): return str(self.document) app/admin.py from django.contrib import admin from .models import Document def uuid(obj): return … -
display image from django model to template using for loop
so i want to show the image of the product from the the Product model to the template in a table but the code below that i wrote shows the broken image sign at the image and does not work here is my code : in models.py class Product(models.Model): Name = models.CharField(max_length=700, null=True) Price = models.FloatField(null=True) Link = models.URLField(max_length=2000, null=True) Image = models.ImageField(null=True) in my views.py : from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * def home(request): Products = Product.objects.all() context = {'products':Products} return render(request, 'Cam/main.html', context) in the template (the html file): <div class="container "> <table class="table table-hover"> <thead> <tr class="row"> <th class="col-md-1" >Name</th> <th class="col " >Picture</th> <th class="col-md-1" >Price</th> </tr> </thead> <tbody> {% for product in products %} <tr class="row"> <td class="col-md-1"> {{product.Name}} </td> <td class="col-md-1"><img id="IMG" src="{{product.Image.url}}" ></td> <td class="col-md-1"> {{product.Price}} </td> </tr> {% endfor %} -
Form ModelChoiceField to exclude object being edited
I hope I can articulate myself properly. I have a model for MerchantGroup which has a one to many relationship with Merchants. I've added a feature that allows two MerchantGroups to be merged together - this basically moves all the Merchants from the two groups into one group and deletes the empty group. Below is the forms.py, views.py and forms.py. To do this merge the user opens the Update view for a MerchantGroup, and selects another MerchantGroup to merge with. The problem I have is that the form field merge_merchantgroup = forms.ModelChoiceField(required=False, queryset=MerchantGroup.objects.all().order_by('name'), empty_label="Merge with") displays the MerchantGroup being updated as one of the groups that can be merdged with, allowing a user to try to merge a MerchantGroup with itself - which is obvious non-sense. I can't think of hor to exclude the existing MerchantGroup from the ModelChoiceField so that users can try to merge a MerchantGroup with itself. Views.py @login_required def merchantgroups_update(request, pk): merchant_group = get_object_or_404(MerchantGroup,pk=pk) if request.method == 'POST': form = MerchantGroupForm(request.POST) if form.is_valid(): if form.cleaned_data['merge_merchantgroup']: merchant_group.merge(form.cleaned_data['merge_merchantgroup']) else: merchant_group.ledger = form.cleaned_data['default_ledger'] merchant_group.name = form.cleaned_data['name'] merchant_group.save() return HttpResponseRedirect(reverse('monzo:merchantgroups_show_all')) else: initial = { 'default_ledger': merchant_group.ledger, 'name': merchant_group.name, } form = MerchantGroupForm(initial=initial) return render(request, 'monzo/merchantgroups_update.html', {'form': form, 'merchant_group': merchant_group,}) Models.py … -
Gunicorn with Django giving a problem with static files
Got a Django project named django_server. When I run python manage.py runserver the page shows up as expected Then, if I run gunicorn django_server.wsgi:application --bind 0.0.0.0:8000 The page shows without styling Checking the console, can see the following errors for both .css and .js files The resource from “http://0.0.0.0:8000/static/....css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). In the terminal where the gunicorn command was executed, can read NOT FOUND: /static/rest_framework/css/bootstrap.min.css NOT FOUND: /static/rest_framework/css/bootstrap-tweaks.min.css ... In settings.py I mention BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') This is the folder structure Checked the permissions in static folder (ls -l)and they show as drwxrwxr-x 4 tiago tiago 4096 jun 2 15:49 static Checking the permissions in the files where the problem happens and Added also to settings.py import mimetypes mimetypes.add_type("text/css",".css",True) mimetypes.add_type("text/javascript",".js",True) But the error remains. -
Blank username in Django allauth
I use Django-allauth for registration and login, without any social options right now. I have 2 issues with one specific user that is able to register with a blank username and incorrect e-mail. How can I avoid this behaviour in the future? I've added a couple of additional restrictions, but I can't validate if they will work. ACCOUNT_USERNAME_MIN_LENGTH = 4 ACCOUNT_USERNAME_BLACKLIST = ['',] I assume that special characters are used. Unfortunately, I can't replicate this behaviour myself. -
Django : I have a problem with showing the number of comments
I want to display the number of comments on this post Django posts app models.py class posts(models.Model): post_title = models.CharField(max_length=40) post_imge = models.ImageField(default='post.jpg', upload_to='post_images') post_text = models.TextField() Django comments app models.py from posts.models import posts class comments(models.Model): post = models.ForeignKey(posts, on_delete=models.CASCADE) comment = models.CharField(max_length=100) Django comments app views.py from django.shortcuts import render from .models import comments def posts(request): posts= comments.objects.all() template = 'comments /posts.html' context = { 'tum_posts': posts, 'title': 'tum post sayfası', } return render(request, template, context) Templates posts.html {% for comment in tum_posts %} {{ comment.post.post_title}} {{ comment.post.post_imge}} {{ comment.post.post_text }} {{ comment.count}} # is not runing {% endfor %} {{ comment.count}} is not runing how to fix this Thanks... -
How to get columns from joined table in django ORM
Keeping the problem simple : Trying to Learn ORM. And now I am stuck with simple left join issue . So Lets start with basic model : class City(models.Model): city=models.CharField(max_length=30) pin_code = models.IntegerField(null=False) class State(models.Model) city = models.ForeignKey(City,on_delete=models.CASCADE) state = models.CharField(max_length=30) province = models.CharField(max_length=30) Now, I basically want to do : select c.pin_code from State s left join City c on s.city = c.city; The equivalent of above in ORM that I could grasp from the mighty World Wide Web is : State.objects.select_related('city') The above querset on looping through gives me only data from State Table . I dont get 'pin_code' column . I did all the search possible on the internet , but couldnt find any solution . -
Stripe payment integration, error: does not exist on type 'HTMLElement'
I am integrating Stripe in my Angular 8/Django 3 app. I am so close... Following this doc page Payment Stripe I have already: 1. Set up stripe 2. Created a PaymentIntent object and received the clientSecret key from Stripe API (done on the Django server side) 3. Collected card details by mounting the Stripe Elements to the correct DOM Its the last step #4 "Submitting Payment to Stripe" that I am caught up on. I am currently trying to submit the payment on the client side using the stripe.confirmCardPayment() method. However to do this you are supposed to include the clientSecret. Problem is when I try to do this as shown below I get the error Property 'client_secret' does not exist on type 'HTMLElement'. I am not sure how to pass the clientSecret to that method. I am thinking that I could do step#4 on the backend, but I read that this should be done on the frontend. If i did this I guess i would just essentially build my own form for the card and bind it to an angular value, and then send that to the backend? Any help is appreciated. checkout.component.ts import { Component, OnInit, ChangeDetectorRef,} from … -
Django why models.py class attributes not instance attributes
I am new to Django and Python, so any help to clarify my question would be much appreciated! In models.py, why the attributes are not instance attribute but class attribute. Because I think each of these attributes will be different for each model instance created, so they should be instance attribute. For example: # articles/models.py from django.db import models from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() In the last 2 lines, the title and body I think should be self.title and self.body because they contain information specific to each model instance created, right? If created as a class attribute, all model instances would have the same title and body, which is wrong. -
Django: use of __lte for automatic publication of a post
I'm developing a blog and I'm using this filter for put online the posts automatically: geopost_filter = GeoPost.objects.filter(draft=False, publishing_date__lte=timezone.now()) This filter run in local but doesn't run in production. For put online the post that pass from "it will be published in future" to "it is now online" I must restart the server in production. Why happen this? I can change the post's status using the draft field without problem, both in local than in production. But it seams not possible to publish automatically a post if it is marked as future post. -
How to combine to models in Django view
How do i combine this two model in 1 queryset? class ScheduleOfPayment(models.Model): GradeLevel_Category= models.ForeignKey("gradelevel_category", on_delete=models.CASCADE,blank=True, null=True) Education_Levels = models.ForeignKey(EducationLevel, on_delete=models.CASCADE, blank=True, null=True) Semester = models.ForeignKey("semestral", related_name='+', on_delete=models.CASCADE,blank=True,null=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, on_delete=models.CASCADE, blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.IntegerField(null=True, blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True, blank=True) School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Track") strands = models.ForeignKey("N_strand", on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, on_delete=models.CASCADE, null=True ,blank=True) Discount_Type = models.ForeignKey(Discount, on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel,on_delete=models.CASCADE,blank=True,null=True) Semester = models.ForeignKey("semestral", on_delete=models.CASCADE,blank=True,null=True) I have this code in my views.py I just want to combine the (studentenrollment query) and (scheduleofpayment query) gradelevel = request.GET.get('gradelevel') semester = request.GET.get('semester') payment = request.GET.get('payment') studentenrollment = StudentsEnrollmentRecord.objects.filter(Education_Levels=gradelevel).filter(Semester =semester).filter(Payment_Type=payment) scheduleofpayment = ScheduleOfPayment.objects.filter(Education_Levels=gradelevel).filter(Payment_Type = payment).filter(Semester=semester) and in my html {% for obj **Combination of two queryset**%} {% endfor %} -
Why do errors occur when connecting celery to sending mail with passord_reset?
I am trying to connect celery task to send mail when resetting the password. I use django views (PasswordResetView). I created a form and inherited from PasswordResetForm. Overrided the send_mail method, which sends a message to e-mail class CustomResetPasswordForm(PasswordResetForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form_control'})) def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): send_email_for_reset_password.apply_async(args=[subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name]) I put the send logic in task send_email_for_reset_password def send_email_for_reset_password(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name): """ Send a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') email_message.send() But an error occurs EncodeError at /user/password_reset/ Object of type CustomUser is not JSON serializable Also I only tried email_message.send (), but the error is the same. What am I doing wrong?