Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django custom 404 page not working
I have essentially tried 2 solutions here. The first one: Created 404.html inside root templates directory which was supposed to be recognized by django. By the way have defined it in settings.py: 'DIRS': [BASE_DIR / 'templates'], The second solution i have tried: In urls.py: from django.conf.urls import handler404 handler404 = 'pdfapp.views.not_found' in views.py: def not_found(request, exception): return render(request, 'partials/not_found.html', status = 404) None of these solutions have worked. Neither youtube videos nor the other forms could help my case. -
SyntaxError: invalid syntax in manage.py in django and python project
I run python program in Django framework that showed error below it. File "manage.py", line 26 ) from exc ^ SyntaxError: invalid syntax command is python manage.py test. manage.py: """Django's command-line utility for administrative tasks.""" import os import sys import io from django.db.backends.mysql.schema import DatabaseSchemaEditor sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xxxxx.settings') DatabaseSchemaEditor.sql_create_table += " ROW_FORMAT=DYNAMIC" try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
Unable to retreive data for profile page (possible authentication problem)
When I login, and then use the nav bar to go to profile page, it does not retreive any information. I am only trying to retreive the user's username for now to simplify the problem. Errors after clicking on 'Profile': GET http://localhost:8000/accounts/login/?next=/profile/ 404 (Not Found) UserProfile.vue:37 Error fetching user profile: Error: HTTP error! status: 404 at fetchUserProfile (UserProfile.vue:30:17) On the network tab, there are 2 names present for the profile: "profile/" has status code of 302 Found and "login/?next=/profile/" has status code of 404 Not Found. "profile/" preview tab shows this: "login/?next=/profile/" preview tab shows this: Here are the relevant parts of my code: views.py from django.contrib.auth import authenticate, login from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .serializers import CustomUserSerializer from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.decorators import login_required from django.http import JsonResponse @api_view(['POST']) def signup_view(request): if request.method == 'POST': serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({ 'response': "Successfully registered a new user.", 'username': serializer.data.get('username') }) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) def login_view(request): if request.method == 'POST': username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return Response({ 'response': "Successfully logged in.", 'username': username }) … -
AttributeError at /blog/tag/security/. 'TaggableManager' object has no attribute 'get_reverse_joining_fields'
when I run the code i get 'TaggableManager' object has no attribute 'get_reverse_joining_fields'. I have read django documentation it suggests doing it in the same way but I have no idea what went wrong. I would really appreciate any help. *models.py * from taggit.managers import TaggableManager class Post(models.Model): tags = TaggableManager() title = models.CharField(max_length=200) body = models.TextField(max_length=200) publish = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank = True, max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author_post")``` *admin.py* from .models import Comment, Post # Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title','slug','body', 'slug','author', 'created', 'publish','updated','status') search_fields = ('author__username','title') list_filter = ('title','author__username','created') search_help_text="Search by author username or title" prepopulated_fields = {'slug':('title',)} raw_id_fields = ['author'] *views.py* def post_list(request, tag_slug=None): post_list = Post.objects.filter(status=Post.Status.PUBLISH) tag = None if tag_slug: tag = get_object_or_404(Tag, slug = tag_slug) post_list = post_list.filter(tags__name__in=[tag]) paginator = Paginator(post_list, 100) page_number = request.GET.get('page',1) try: posts=paginator.page(page_number) except EmptyPage: posts=paginator.page(paginator.num_pages) except PageNotAnInteger: posts = paginator.page(1) return render(request, 'blog/post/list.html', context={"posts":posts, 'tag':tag}) *urls.py* --> app level from django.urls import path from . import views app_name='blog' urlpatterns=[ path('', views.post_list, name='post_list'), path('<int:id>/share/', views.post_share, name='post_share'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), path('<int:id>/comment/', views.post_comment, name='post_comment'), path('post/<int:id>/', views.post_detail, name='post_detail'), ] -
Django Report Builder - Override Toolbar Header
Is there anyway to override the Django Report Builder toolbar header? Ive isoloated it down to this: span _ngcontent-chv-c159="">Welcome to Django Report Builder </span But don't understand how to override it? I've tried overriding the elements within the template but it doesn't seem to change anything...good chance I'm way off with my thinking here. -
PLEASE, The QuerySet value for an exact lookup must be limited to one result using slicing
It displays a table with reports and I would like to display additional information according to the report, how can I do this? e.g. a table with the details of the report is displayed, and in the browser I want to display additional information, displaying the report itself works, but when I add additional information to the code, an error appears models.py class Submissions(models.Model): submissions_number_id = models.CharField(max_length=10,blank=True, unique=True, default=create_new_ref_number,editable=False) contents = models.TextField() class AdditionalInfo(models.Model): submission = models.ForeignKey(Submissions, on_delete=models.CASCADE, related_name='additional_info', default='') contents = models.TextField() I tried this but I get an error views.py def Schedule(request): date = datetime.date.today() report=Submissions.objects.filter(execution_date=date) info=AdditionalInfo.objects.filter(submission=report) context={ 'date':date, 'report':report, 'info':info, } return render(request, 'staff/work_schedule.html', context) html <tbody> {% for qs in report %} <tr style="font-size: 10px;text-align: center;"> <th style="width: 8%;">{{qs.client.user.get_full_name}}, tel.: {{qs.client.phone_number}}</th> <th style="width: 8%;">{{qs.client.post_code}} {{qs.client.city}}, ul.{{qs.client.street}}</th> <th style="width: 40%;">{{qs.contents}}</th> <th style="width: 40%;">{{info.contents}}</th> </tr> {% endfor %} </tbody> -
Why aren't the environment variables working inside my Django Docker container?
I'm encountering an issue where Django doesn't seem to be reading environment variables when running in a Docker-compose environment. Strangely, the environment variables work fine for PostgreSQL but not for Django. I've tried both the env_file and environment options in my Docker-compose file, and I've also experimented with django-dotenv without success. Here's a snippet of my code: print(f" {os.environ.get('SECRET_KEY')} {os.environ.get('DEBUG')} {os.environ.get('DATABASE_NAME')} ") # The above print statement outputs None for all environment variables SECRET_KEY = os.environ.get("SECRET_KEY") # ... version: '3.9' services: db: # ... web: build: ./src command: gunicorn myapp.wsgi:application --access-logfile /logs/gunicorn/access.log --error-logfile /logs/gunicorn/error.log --bind 0.0.0.0:8000 volumes: # ... # env_file: #not working # - .env environment: - SECRET_KEY=${SECRET_KEY} - DATABASE_NAME=${DATABASE_NAME} # ... (other environment variables) nginx: # ... SECRET_KEY=3df-81ioo^5cx(p9cl$)s%m3mlu3t7*yh#1lr5h0po4_sab3*5 DATABASE_NAME=mydb DATABASE_USER=postgres DATABASE_PASS=postgres DATABASE_HOST=db DATABASE_PORT=5432 DEBUG=0 -
How do I add fields to the django_rest_auth response object?
I am extending the default django rest auth Login class in order to add 2 fields to the response object; the user's subscription and email addresses. from dj_rest_auth.serializers import LoginSerializer class CustomLoginSerializer(LoginSerializer): subscription = SubscriptionSerializer(read_only=True) email_addresses = EmailAddressSerializer(read_only=True, many=True) class Meta: model = User # fields = ['pk', 'username', 'email'] fields = ['pk', 'username', 'email', 'subscription', 'email_addresses'] def to_representation(self, instance): print('instance: ' + instance) data = super(CustomLoginSerializer, self).to_representation(instance) data['subscription'] = instance.user.subscription data['email_addresses'] = instance.user.email_addresses.all() data['lol'] = 'lmao' return data This is the response object. Note the added fields aren't present. { "access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA2NTYxNjQyLCJpYXQiOjE3MDY0NzUyNDIsImp0aSI6ImFhYTg5OTNlODQ5MTRjODJhOGRjNGU3MDE5MjE4YzNkIiwidXNlcl9pZCI6NH0.1l7RtT8G1qL6Tq5RVzLe5ceu_mnNVJV8oW64An_-hHk", "refresh": "", "user": { "pk": 4, "username": "user102", "email": "user102@email.com", "first_name": "", "last_name": "" } } Since overriding the to_representation method doesn't seem to work, how do I add related fields to the response object? -
Skipping a step in a WizardView based on data entered in that step
I'm trying to build a formtools Wizard where a confirmation form is shown in one of the steps. The confirmation form is only show in specific cases (e.g. if a user has previously ordered the same item before), and it should no longer be shown after the user has confirmed. Basically, my code looks like this: def ask_confirmation(wizard): # Database conditions go here return user.has_ordered_same_item_before class ItemWizard(SessionWizardView): condition_dict = { "confirm": ask_confirmation, } ... Obviously, the step where the user is asked to confirm is never passed, because the condition is always True. I don't want to store the user's response in the database, it's just something that the wizard needs to "remember" and that I can check in the condition function. How can I test whether the user has confirmed and skip the form once they did? -
I couldn't get the CompoundSearchFilterBackend class in the django-elasticsearch-dsl-drf library to work properly
I'm using the CompoundSearchFilterBackend class in the django-elasticsearch-dsl-drf library to perform queries. However, I'm receiving all queries. Django==4.2.9 django-elasticsearch-dsl==7.3 django-elasticsearch-dsl-drf==0.22.5 Below is an example of cached data from Elasticsearch along with other relevant classes. { "took": 4, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "betik_app_municy_citizen_municipal_council", "_id": "1", "_score": 1, "_source": { "party_name": "party", "title": "title", "full_name": "erhan koçlar", "email": "test@hotmail.com", "id": 1, "substitute": false } } ] } } documents.py @registry.register_document class MunicipalCouncilDocument(Document): class Index: name = f"{APP_LABEL}_municipal_council" settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = MunicipalCouncilModel fields = [ 'id', 'substitute' ] party_name = fields.TextField() title = fields.TextField() full_name = fields.TextField() email = fields.KeywordField() def prepare_full_name(self, instance): return f"{instance.person.name} {instance.person.last_name}" def prepare_email(self, instance): return instance.person.email def prepare_party_name(self, instance): return instance.political_party.name def prepare_title(self, instance): return instance.title.exp def get_queryset(self): # visible return super().get_queryset() \ .filter( visible=True ) \ .order_by('order_no') views.py class PaginateDocumentView(DocumentViewSet): """ Paginate municipal councils (cache) Paginate cached municipal councils """ document = MunicipalCouncilDocument serializer_class = MunicipalCouncilDocumentSerializer pagination_class = StandardPagination authentication_classes = [] filter_backends = [ CompoundSearchFilterBackend, ] search_fields = ( 'full_name', 'email' ) When … -
Signin Fails With Custom Errors
Signin is working flawlessly but, Signup returns with {"non_field_errors": ["Incorrect creds"]} Which I have specified in LoginSerializer. I think it's happening due to authenticate function but, I am not able to pinpoint the issue as when I print it, it returns None. Does anybody knows what could be the issue? I have given the whole code but, I reckon the problem is created in LoginSerializer.I have also, added the AUTHENTICATION_BACKENDS in settings.py and after then, it's still gives that error. Models: from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class UserManager (BaseUserManager): def create_user(self, username, password, **extra_fields): if not username: raise ValueError("Username should be provided") user = self.model(username=username, **extra_fields) user.set_password (password) user.save() return user def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, password, **extra_fields) class User (AbstractBaseUser): id = models.AutoField (primary_key=True) name = models.CharField(max_length=100) email = models. CharField (max_length=60) password = models. CharField (max_length=16) username = models. CharField (max_length=100, unique=True) USERNAME_FIELD = 'username' objects = UserManager() Serializers: from rest_framework import serializers from .models import User from django.contrib.auth import authenticate class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) email = serializers.CharField(required=False) name = serializers.CharField(required=False) class Meta: model = User fields = ('username', 'password', 'email', 'name') def create(self, validated_data): user = … -
Value error on custom log filter when importing unrelated module
I have the setup below that I'm using to inject extra data from the request object into each log message and it works fine. I recently needed to import a urls.py file from another app into the auth_middleware.py file to check all registered DRF routes and redirect appropriately, but I immediately got ValueError: Unable to configure filter 'session_context' each time I attempt to start the application. The import statement that is triggering this error (called from auth_middleware.py) looks like this: from apps.app_name.api.urls import router proj/middleware/auth_middleware.py import threading local = threading.local() class CheckUserLogin: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): setattr(local, "uip", request.META.get("REMOTE_ADDR")) setattr(local, "sid", request.session.session_key or "n/a") if request.user.is_anonymous and request.path != reverse("auth_service_login"): # apply redirect login and send to url_login return HttpResponseRedirect(url_login) return self.get_response(request) services/log_ctx.py import logging from proj.middleware.auth_middleware import local class ExtraLogCtx(logging.Filter): def filter(self, record): defs = "n/a" record.uip = getattr(local, "uip", defs) record.sid = getattr(local, "sid", defs) return True proj/settings.py MIDDLEWARE = [ ... "proj.middleware.auth_middleware.CheckUserLogin", ] LOGGING = { "filters": { "session_context": { "()": "services.log_ctx.ExtraLogCtx", }, }, "handlers": { "console": { ... "filters": ["session_context"], ... }, }, } I have __init__.py in the services and middleware folders and am unsure where else to look. Any … -
Stream Zeros with Django with StreamingHttpResponse
I have to send an amount of Zeros as response, defined by the request. They have to be plain zeros. (I know, a rather odd task...) so, for example, you need 100mb of zeros, you query ?size=100&unit=mb, you will get a stream of 100mb only zeros. Since it can be up to 16gb of zeros, I do not want to generate them at first, rather generate a stream of zeros and send this "line by line". This is what I came up with, but it does not behave like I want because it first gathers the full data and then sends it. class CreateImageAndResponseView(View): line_count = 0 def get(self, request): size_str = request.GET.get('size', '') unit = request.GET.get('unit', '').lower() if unit not in ('gb', 'mb'): return HttpResponse(status=400) try: size = float(size_str) if unit == 'gb': size_bytes = int(size * 1024**3) else: size_bytes = int(size * 1024**2) except ValueError: return HttpResponse(status=400) self.line_count = size_bytes // 1024 return StreamingHttpResponse((b'0' * 1024 for _ in range(0, self.line_count)), content_type='application/octet-stream',) I already saw Problem with Django StreamingHttpResponse, but I do not know which middleware could block this. Also, I am not running nginx or apache, just django from my console. -
Django - Custom User Model Signal Issue: Token Creation Occurs Before User Is Persisted to Database
CustomUser extends User from django.contrib.auth.models class CustomUser(User): user_id = models.IntegerField(primary_key=True) has_mod_rights = models.BooleanField() picture = models.BinaryField(null=True, blank=True) description = models.CharField(max_length=150, null=True, blank=True) is_premium = models.BooleanField() unban_date = models.DateField(null=True, blank=True) and my signal should be triggered when new CustomUser is created @receiver(post_save, sender=DishDiscoverUser) def create_auth_token(sender, instance=None, created=False, **kwargs): if created and instance.pk: token = Token.objects.create(user=instance) the registration view: @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): user = serializer.save() # breakpoint() data['response'] = 'successfully registered a new user' data['email'] = user.email data['username'] = user.username token = Token.objects.get(user=user).key data['token']=token else: data: serializer.errors return Response(data) and serializer: class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) class Meta: model = CustomUser fields = ['username', 'password', 'password2', 'email', 'first_name', 'last_name'] def create(self, validated_data): user = CustomUser( email=self.validated_data['email'], username=self.validated_data['username'], has_mod_rights=False, is_premium=False, ) password = self.validated_data['password'] password2= self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password must match!'}) user.set_password(password) user.save() return user and i get FAILED authorisation/tests/test_auth.py::test_registration - ValueError: Model instances passed to related filters must be saved. Error when running @pytest.mark.django_db def test_registration(): client = APIClient() # Prepare data for a valid registration valid_data = valid_login_data()[0] url = '/api/auth/register' response = client.post(url, valid_data) assert response.status_code == 200, response.json() assert … -
Django rendered content is different in console.log from page source
I have the following code in my django view project: if request.method == "POST": form = OrderForm(request.POST) if form.is_valid(): datas = Order() datas.user = current_user datas.save() current_datetime = datetime.datetime.now().strftime('%Y%H%S%m%M%d') order_number = current_datetime + str(datas.id) datas.order_number = order_number datas.save() order = Order.objects.get(user=current_user, is_ordered=False, order_number=datas.order_number) context['order'] = order context['user'] = request.user return render(request, 'orders/order.html', context) Inside order.html, I have: <script> console.log('order number 0: ', {{ order.order_number }}) </script> When I view the page source and browser console, the values of {{ order.order_number }} are different. Browser console.log shows wrong values for str(datas.id) part whereas the rest of the part of {{ order.order_number }} is same in both console.log and page source. -
How can I fix the metaclass conflict in django-rest-framework Serializer
I've written the following code in django and DRF: class ServiceModelMetaClass(serializers.SerializerMetaclass, type): SERVICE_MODELS = { "email": EmailSubscriber, "push": PushSubscriber } def __call__(cls, *args, **kwargs): service = kwargs.get("data", {}).get("service") cls.Meta.subscriber_model = cls.SERVICE_MODELS.get(service) return super().__call__(*args, **kwargs) class InterListsActionsSerializer(serializers.Serializer, metaclass=ServiceModelMetaClass): source_list_id = serializers.IntegerField() target_list_id = serializers.IntegerField() subscriber_ids = serializers.IntegerField(many=True, required=False) account_id = serializers.CharField() service = serializers.ChoiceField(choices=("email", "push")) class Meta: subscriber_model: Model = None def move(self): model = self.Meta.subscriber_model # Rest of the method code. The purpose of this code is that this serializer might need doing operation on different models based on the service that the user wants to use. So I wrote this metaclass to prevent writing duplicate code and simply change the subscriber_model based on user's needs. Now as you might know, serializers.Serializer uses a metaclass by its own, serializers.SerializerMetaclass. This results in the following error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. I tried making my ServiceModelMetaClass metaclass to inherit from serializers.SerializerMetaclass but it gave me this error: File "/project-root/segment_management/serializers/subscriber_list.py", line 33, in <module> class InterListsActionsSerializer(serializers.Serializer, metaclass=ServiceModelMetaClass): File "/project-root/segment_management/serializers/subscriber_list.py", line 36, in InterListsActionsSerializer subscriber_ids = serializers.IntegerField(many=True, required=False) File "/project-root/.venv/lib/python3.10/site-packages/rest_framework/fields.py", line 894, in __init__ super().__init__(**kwargs) TypeError: Field.__init__() … -
How to add a new value to model at the very beginning, shifting the ID of other values by 1?
models.py: class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=False) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Category, self).save(*args, **kwargs) def __str__(self): return self.title class Meta: ordering = ['ordering'] verbose_name_plural = 'Categories' def get_absolute_url(self): return '/%s/' % (self.slug) class SubCategory(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(null=False, unique=True) ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=True) category = models.ForeignKey( Category, related_name='subcategory', on_delete=models.CASCADE ) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(SubCategory, self).save(*args, **kwargs) class Meta: ordering = ['ordering'] verbose_name_plural = 'SubCategories' def __str__(self): return self.title def get_absolute_url(self): return '/%s/%s/' % (self.category, self.slug) class SubSubCategory(MPTTModel): parent = TreeForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=50) slug = models.SlugField(null=False, unique=True) sub_category = models.ForeignKey( SubCategory, related_name='subsubcategory', on_delete=CASCADE, null=True ) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name_plural = 'Sub_subcategories' class MPTTMeta: order_insertion_by = ['title'] def get_absolute_url(self): return reverse('susubcategory_detail', kwargs={'slug': self.slug}) def __str__(self): full_path = [self.title] k = self.parent while k is not None: full_path.append(k.title) k = k.apparent return ' / '.join(full_path[::-1]) class Attribute(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(SubSubCategory, related_name='attribute_categories', on_delete=models.CASCADE) def __str__(self): return self.name class AttributeChoice(models.Model): category = models.ForeignKey( SubSubCategory, related_name='attribute_choice_categories', on_delete=models.CASCADE, null=True ) attribute = ChainedForeignKey( Attribute, chained_field="category", chained_model_field="category", show_all=True, auto_choose=True, sort=True, null=True, … -
Using a check box in a web application
Am trying to create a TodoList where a user clicks a checkbox to tick checked when complete is true , but am not understanding the concept with checkboxes. just recently started learning django , the below code is what l have come up with. Model Code from django.db import models # Create your models here. class List(models.Model): list_title = models.CharField(max_length = 200) list_context = models.CharField(max_length = 200) pub_date = models.DateTimeField() complete = models.BooleanField(default=False) def __str__(self): return self.list_title view code from django.shortcuts import render from .models import List # Create your views here. def index(Request): list_items = List.objects.order_by('-pub_date') list_ticked =[] if Request.method == "Post": list_ticked = Request.Post.getlist('items') if list_ticked== True: complete = True context = { 'list_items':list_items, 'list_ticked':list_ticked, } template = 'TodoList/index.html' return render (Request,template,context) Html Code <ul class="list-group mb-0"> <form action="" method="post"> {%if list_items%} {%for item in list_items %} <li class="list-group-item d-flex justify-content-between align-items-center border-start-0 border-top-0 border-end-0 border-bottom rounded-0 mb-2"> <div class="d-flex align-items-center"> <input class="form-check-input me-2" type="checkbox" value="{{item.id}}" id="item {{forloop.counter}}" name="list_ticked =[]" /> {{item.list_context}} </div> <a href="#!" data-mdb-toggle="tooltip" title="Remove item"> <i class="fas fa-times text-primary"></i> </a> </li> {%endfor%} {%else%} <p>No list available</p> {%endif%} </form> </ul> <ul class="list-group mb-0"> <form action="" method="post"> {%if list_items%} {%for item in list_items %} <li class="list-group-item d-flex … -
The task in Celery is being passed from Celery Beats to Workers, and is being received there but the task is not being executed. I am using Django
Pretty much the title. The task is being passed and received properly but isn't getting executed. So I just kept a simple print statement, it still didn't execute. What I did notice was, in the admin interface, the task is being set as type 'custom' instead of 'registered' although it has same name as that of the registered task I am trying to execute. Am I missing something? Celery config in settings.py celery.py tasks.py Django admin interface. The task is made custom type although there is already a registered task of same name Beat log Worker log What could be the problem? Tried prompting Chat GPT, Bard and Bing, I had already performed everything they suggested. The documentation was less useful. -
Django doesnt render Form
When I request the url in the browser, django does not render the form defined in the forms.py but only the hardcoded html in bulk_import.html. bulk_import.html {% extends 'score/base.html' %} {% load static %} {% block content %} <div class="container my-5"> <h1>Bulk Import</h1> <form action="" method=POST> {% csrf_token %} {{ form2 }} <input type="submit" value="Absenden" class="btn btn-secondary"> </form> </div> {% endblock %} forms.py class BulkModulImport(forms.Form): text = forms.Textarea(attrs={'class': 'form-control', 'rows': '4'}) views.py def bulk_modul_import(request): submitted = False if request.method == "POST": form = BulkModulImport(request.POST) if form.is_valid(): def remove_dots_and_numbers(text): lines = text.split('\n') updated_lines = [] for line in lines: # Use regular expression to remove dots and numbers at the end of each line updated_line = line.replace(' .', '') updated_line = re.sub(r'\s*\d*$', '', updated_line) if "Module der Lehreinheit" not in updated_line: Modul(title=line,proposer=request.user, dozent=None, created_date=timezone.now(), description="").save() updated_lines.append(updated_line) remove_dots_and_numbers(form.cleaned_data['text']) messages.success(request, ('Du hast erfolgreich einen Bulk-Import der Module durchgeführt!')) return HttpResponseRedirect(reverse('modul_list')) else: form2 = BulkModulImport() return render(request, 'score/bulk_import.html', {'form2': form2}) -
NoReverseMatch on extra enpoint in GenericViewSet
urls.py app_name = "auth" urlpatterns = [ path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), path("token/refresh/", TokenRefreshView.as_view(), name="token_refresh"), path( "password/confirm/<str:uid>/<str:token>/", PasswordResetViewSet.as_view({"post": "password_reset_confirm"}, name="password_reset_confirm"), ), path( "password/reset/", PasswordResetViewSet.as_view({"post": "send_reset_password_link"}), name="password_send_link", ), ] views.py class PasswordResetViewSet(GenericViewSet): def get_permissions(self): return [permissions.AllowAny()] def get_serializer_class(self) -> type[Serializer]: action_serializer_map = { "send_reset_password_link": ResetPasswordSerializer, "confirm_password_changed": ResetPasswordConfirmSerializer, } return action_serializer_map[self.action] @extend_schema(request=ResetPasswordSerializer, responses={201: {}, 404: {}}) @action(methods=["POST"], detail=False) def send_reset_password_link(self, request): serializer = ResetPasswordSerializer(data=request.data) serializer.is_valid(raise_exception=True) return Response( data=reset_password_link_service( email=serializer.validated_data.get("email") ) ) @extend_schema( request=ResetPasswordConfirmSerializer, ) @action(methods=["POST"], detail=False) def password_reset_confirm(self, request): return Response() Trying to do reverse("auth:password_reset_confirm", kwargs={uid: uid, token: token}) gives me NoReverseMatch. Really do not know what is going wrong here... Suggestions? Adding usual FBV to the same namespace "auth" works great. -
disable people from downloading pdf
I have a library system where we publish books but unfortunately people download them and bad enough they reprint them and sell, the system is written in django and I am a newbie on python so far I do not know what to do -
I have issue after hosting my django app, working completely fine in ip address all the django style are working but not working in domain?
See in IP address its working fine without any prblemsSee but in domain the styles are not working i don't know what to change and where i made a mistake Problem in domain hosting Can someone check it and resolve my issue to make django app working flauless in domain I have tried to change the Gunicorn confg and run in gunicorn but it doesnt make any changes so again i run in normal python runserver command. -
Configure an nginx proxy to two applications, a Flask and a Django, via two locations /v1 for Flask and /v2 for Django
I am hosting two Applications on same Server. A Flask App and a new Django App. Flask is startet at local server 127.0.0.1:5000. New Django App is startet at local server 127.0.0.1:8000. In my nginx default Configuration File i added a new location Block for the new Django App and i try something like this: # Nginx Config server { listen 80; server_name my-subdomain.my-domain.com; rewrite ^ https://$server_name$request_uri? permanent; } server { listen 443 default_server ssl; server_name 127.0.0.1; ssl_certificate /etc/letsencrypt/live/my-subdomain.my-domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/my-subdomain.my-domain.com/privkey.pem; # Old configuration before new Django App #location / { # include proxy_params; # proxy_pass http://127.0.0.1:5000; #} # Default location (version 1) location / { proxy_pass http://127.0.0.1:5000; include /etc/nginx/proxy_params; proxy_redirect off; } # Version 1 explicit location /v1 { rewrite ^/v1(.*) /$1 break; proxy_pass http://127.0.0.1:5000; include /etc/nginx/proxy_params; proxy_redirect off; sub_filter 'href="/' 'href="/v1/'; sub_filter_once off; } merge_slashes on; # Version 2 location /v2 { rewrite ^/v2(.*) /$1 break; proxy_pass http://127.0.0.1:8000; include /etc/nginx/proxy_params; proxy_redirect off; sub_filter 'href="/' 'href="/v2/'; sub_filter_once off; } } Here is a View of my Django URLS Configuration: urlpatterns = [ path('admin/', admin.site.urls), path("shortener/", include("urlshortener.urls")), path('projects/', include('projects.urls')), ] Now the Problem is, when i access https://my-subdomain.my-domain.com/v2/admin I get from Django : Page not found (404) Request Method: GET … -
Creating a logout functionality in Django, however I am getting a HTTP Error 405 when trying to load the page. How do I fix it?
I am creating a blog site. I have found out you are now supposed to use a POST request for Logout, however I did this and I am not sure where I have gone wrong. Here is the relevant code: urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] logout.html {% extends "blog/base.html" %} {% block content %} <h2>You have been logged out</h2> <div class="border-top pt-3"> <form action="{% url 'logout' %}" method="post"> {% csrf_token %} <button type="submit" class="btn btn-primary">Logout</button> </form> <small class="text-muted"> <a href="{% url 'login' %}">Log In Again</a> </small> </div> {% endblock content %} views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in.') return redirect('login') else: form = UserRegisterForm() return render (request, 'users/register.html', {'form': form}) @login_required def profile(request): return render(request, 'users/profile.html') Even tried using Chatgpt to help me, and …