Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue - TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
I tried everything to fix this issue, it is so frustrating!! After the registration (with React) I receive the verification email including the link. After I clicking the link the issue with the "TemplateResponseMixin" appears, no matter what I try... Here is my code, you can also find the complete on my GitHub repository: https://github.com/ChrisCross1983/pp5-paw_buddy: enter image description here views.py from allauth.account.views import ConfirmEmailView from allauth.account.models import EmailConfirmation, EmailAddress from django.views.generic.base import TemplateResponseMixin from django.http import JsonResponse, HttpResponse from django.template.response import TemplateResponse from django.views.generic import TemplateView from django.shortcuts import render from django.contrib.sites.models import Site import logging logger = logging.getLogger(__name__) class CustomConfirmEmailView(ConfirmEmailView): template_name = 'account/email_confirmed.html' def get(self, request, *args, **kwargs): print("DEBUG: CustomConfirmEmailView gestartet mit Key:", kwargs.get("key")) try: confirmation = self.get_object() print("DEBUG: Confirmation gefunden:", confirmation) confirmation.confirm(request) print("DEBUG: Benutzer erfolgreich bestätigt") user = confirmation.email_address.user user.is_active = True user.save() return JsonResponse({"message": "Email erfolgreich bestätigt"}) except Exception as e: print(f"DEBUG: Fehler in CustomConfirmEmailView: {e}") return JsonResponse({"error": str(e)}, status=400) def test_template_view(request): return render(request, 'account/email_confirmed.html', {"message": "Test erfolgreich"}) def account_inactive_view(request): logger.debug("Account Inactive View aufgerufen") return JsonResponse({"error": "Your account is inactive. Please confirm your email to activate it."}, status=403) def index(request): return render(request, 'index.html') urls.py: from django.contrib import admin from django.urls import path, include from project.views import CustomConfirmEmailView, … -
AttributeError: 'str' object has no attribute 'is_registered' in Django Custom Add Product Page
Title: AttributeError: 'str' object has no attribute 'is_registered' in Django Custom Add Product Page Problem Statement: I am creating a custom page in Django to allow users (staff members) to add a product. The product is defined in the Product model, which includes a ManyToManyField for Color. While the product creation works fine in the admin panel (with the ability to add new colors using the "plus" icon in the color field), this functionality does not work in my custom page. When attempting to wrap the widget for the color field using RelatedFieldWidgetWrapper, I encounter the following error: AttributeError at /useradmin/add_product/ 'str' object has no attribute 'is_registered' Below are the relevant code snippets and configurations. I’d appreciate any help identifying the issue and achieving the desired functionality. Models Product Model from django.db import models from taggit.managers import TaggableManager from shortuuidfield import ShortUUIDField from ckeditor_uploader.fields import RichTextUploadingField from django.utils.safestring import mark_safe class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") user = models.ForeignKey('CustomUser', on_delete=models.SET_NULL, null=True) viewers = models.ManyToManyField('CustomUser', related_name="viewed_products", blank=True) cagtegory = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, related_name="category") subcategory = models.ForeignKey('SubCategory', on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategory") vendor = models.ForeignKey('Vendor', on_delete=models.SET_NULL, null=True, related_name="product") main_product_color = models.ManyToManyField('Color_main', blank=True) color = models.ManyToManyField('Color', blank=True) size = models.ManyToManyField('Size', blank=True) title … -
How to resolve CORS issues with Django backend on Heroku for Flutter frontend?
I am working on a Django backend hosted on Heroku and a Flutter frontend hosted on https://anirni.web.app. My API requests are getting blocked due to CORS policy, and I'm struggling to configure Django to handle this properly **My current setup: ** Backend: Django hosted on Heroku. Frontend: Flutter app hosted on https://anirni.web.app and also tested locally (http://localhost:52360). CORS library: I'm using django-cors-headers. **Relevant parts of my settings.py: ** ` """ Django settings for anirni_server project. Generated by 'django-admin startproject' using Django 5.1. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ import os from pathlib import Path import dj_database_url from corsheaders.defaults import default_headers EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'mail.anirni-dz.com' # Remplacez par le serveur SMTP de Bluehost EMAIL_PORT = 465 # Port SMTP (généralement 587 pour TLS) EMAIL_USE_TLS = False EMAIL_USE_SSL = True # Activer SSL EMAIL_HOST_USER = '###' # Adresse email EMAIL_HOST_PASSWORD = '###' # Mot de passe DEFAULT_FROM_EMAIL = '###' # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent from corsheaders.defaults import default_methods # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used … -
Not able to start a dead letter queue (RabbitMQ / Celery)
I have defined task_queues = ( Queue('celeryDrawingRegister', Exchange('celeryDrawingRegisterExchange', type='direct'), routing_key='register.#', queue_arguments={ 'x-dead-letter-exchange': 'dlx_exchange' }), Queue('celeryDrawingRegisterDLQ', Exchange('dlx_exchange'), routing_key='dlq.#'), # Dead Letter Queue ) in my settings.py file, I then run my workers using elery multi start devCeleryDatasheetMaitainance devCeleryDocument devCeleryDrawingRegister -A imageTranslateApp -l info -P eventlet --loglevel=DEBUG -c:devCeleryDatasheetMaitainance 3 -c:devCeleryDocument 3 -c:devCeleryDrawingRegister 3 -Q:devCeleryDatasheetMaitainance celeryDatasheetMaintainance -Q:devCeleryDocument celeryDocument -Q:devCeleryDrawingRegister celeryDrawingRegister Now my normal workers and task works fine , but I can't use celeryDrawingRegister as Dead Letter queues to acknowledge task and then send it to celeryDrawingRegisterDLQ. What am i missing here?? P.S This is my Celery configuration import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'imageTranslateApp.settings') app = Celery() app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
I am getting a error: everse for 'genre' with arguments '('',)' not found. 1 pattern(s) tried: ['genres/(?P<genre_id>[0-9]+)\\Z']
am trying to run a Django site but have a error when i click on this url: 'book:genres' this is the error: Reverse for 'genre' with arguments '('',)' not found. 1 pattern(s) tried: ['genres/(?P<genre_id>[0-9]+)\Z'] something is wrong with this url: <a href="{% url 'book:genre' genre.id %}"> my models page: from django.db import models # Create your models here. class Genre(models.Model): """A Genre of a book""" text = models.CharField(max_length=20) date_added = models.DateTimeField(auto_now=True) def __str__(self): """return a string representation of the model""" return self.text class Title(models.Model): """A Title of a book""" genre = models.ForeignKey(Genre, on_delete=models.CASCADE) text = models.CharField(max_length=20) date_added = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'titles' def __str__(self): """"Return a string rep of model""" return f"{self.text[:50]}" my veiws: from django.shortcuts import render # Create your views here. from .models import Genre def index(request): """Home page""" return render(request, 'book/index.html') def genres(request): genres = Genre.objects.order_by('date_added') context = {'genres': genres} return render(request, 'book/genres.html', context) def genre(request, genre_id): genre = Genre.objects.get(id=genre_id) titles = genre.entry_set.order_by('-date_added') context = {'genre': genre, 'titles':titles} return render(request, 'book/genre.html', context) my urls: """Defines url patterns for book app""" from django.urls import path from . import views app_name = 'book' urlpatterns = [ # Home page path('', views.index, name = 'index'), path('genres/', views.genres, name="genres"), … -
Django is adding slash into dynamic URL segment
I have a dynamic url configured like so: path('segment/', func1, name='func1'), path('segment/<str:string>/', string, name='string'), However, when I go to https://example.com/segment/watch?v=nTeq0U_V15U (watch?v=nTeq0U_V15U being the string), a slash is automatically added in middle, making it https://example.com/segment/watch/?v=nTeq0U_V15U/. Interestingly enough that does not throw a 404 error even though I have no URL pattern with 3 segments in urls.py. However, my question is why is the slash being added in, and how can I avoid it? -
Where to deploy real estate web app (django + django rest framework + reactjs + postgresql) with many images (kind of zillow.com)?
I developed a real estate web application with following design: database: postgresql backend: django, django rest framework frontend: reactjs. This app is a real estate application something like www.zillow.com. The idea is following: User registers on the platform, logs in to her/his account and publishes her/his properties. There can be uploaded up to 20 images and 1 obligatory video mp4 for every property. The images and video are stored in backend media/images and media/videos and their urls are stored in postgresql. As there are many platforms such as AWS, DigitalOcean, Render, fly.io, Vercel, Heroku, etc. I am not sure which one I should pick up for my project (Django, django rest framework, postgresql, reactjs). Moreover, in spite of the pricing of platforms, I am not able to predict my monthly costs. Also, I am not able to find any video tutorial on youtube which fulfills my expectations. In other words, everything bad :)) My requirements should be: lower costs, fast loading images, easy configuration, easy scalability. I only have a basic/junior experience with web development. In fact, I only deployed MERN app on fly.io since it was recommended in a module/course at the university. Otherweise, I have only developed app … -
Django "Pinax" magick ... unexplained form behavior
This legacy Django website uses "Pinax" for notification. I know for certain that the following "Signup" template is being used: {{ form.captcha.label }} {{ form.captcha }} {{ form.captcha.errors }} <br/> {{ form.email.label }} {{ form.email }} {{ form.email.errors }} <br/> {{ form.email2.label }} {{ form.email2 }} {{ form.email2.errors }} But here are my two problems. First of all, my "captcha" field is not appearing in the output. Second of all, I find no justification for the existence of "email2!" The "form" definition consists, in relevant part: email = forms.EmailField(widget=forms.TextInput()) confirmation_key = forms.CharField( max_length = 40, required = False, widget = forms.HiddenInput() ) # "Solve a math problem" challenge captcha = CaptchaField( label = "Solve A Simple Math Problem", widget = forms.TextInput() ) Notice that there is no "email-two." Yet, it appears with the label, "Email (again)." And, my "captcha" field does not appear in the template at all. I do not understand this "Django magick." I have searched the source code diligently for the phrase, "(again)." And I find no reference to it with regards to "email." (I have already, for other reasons, brought "pinax" directly into my project, because it appears to have been abandoned.) -
Add dynamic data to template
I need to put data into the sidebar. Haven't figured out any other sollution than context_processors. Is this the cleanest and optimal way to do this? Any help appreciated. I find it a bit strange that it has been so hard to find information re. this issue. So maybe this could be of help to others as well. # animals/context_processors.py from animals.models import Cows, Horses from django.shortcuts import render def allcows(request): cows = Cows.objects.all() return {"cows": cows} def lasthorses(request): horses = Horses.objects.all().order_by("-id")[:2] return {"horses": horses} Sidebar.html <h1>Sidebar</h1> <h3>All cows:</h3> {%for cow in cows%} <div> The name is {{ cow.name }}, and the age of {{ cow.name}} is {{ cow.age }}. </div> {%endfor%} <h3>last 2 horses:</h3> {%for horse in horses%} <div> The name is {{ horse.name }}, and the age of {{ horse.name}} is {{ horse.age }}. </div> {%endfor%} base.html <body> <div class="holy-grail-grid"> <header class="header">{% include 'animals/nav.html' %} </header> <main class="main-content"> <header id="main-header"> <h1>{% block main_heading %}Main Heading{% endblock %}</h1> <h3> {% block header_content %}Heading{% endblock %}</h3> </header> {% block content %} {% endblock %} </main> <section class="left-sidebar"> <p>My left sidebar{% include 'animals/sidebar.html' %} </p> </section> <aside class="right-sidebar"> <p>My right sidebar{% include 'animals/justinfo.html' %}</p> </aside> <footer class="footer"> <p>The footer</p> </footer> </div> … -
403 Forbidden Error for Django View Despite Permissions on Custom User Model (in userauths app)
I’m working on a Django project where I’ve implemented a custom user model (CustomUser) in the userauths app. The custom user model uses email as the unique identifier instead of the username. My goal is to allow certain users with specific permissions (change_product or delete_product) to edit or delete a product. However, even after assigning the appropriate permissions to the user, they’re still receiving a 403 Forbidden error. I’ve followed Django’s documentation for creating a custom user model, but I suspect there’s a misconfiguration or step I’ve overlooked. Here’s the detailed setup: Custom User Model and Manager (in userauths app): Below is the code for my custom user model and its manager: # userauths/models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): def _create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if not extra_fields.get('is_staff'): raise ValueError('Superuser must have is_staff=True.') if not extra_fields.get('is_superuser'): raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class … -
ManyToManyField lookup which Django seems doesn't support yet
I want to do something which it seems Django doesn't officially supports it yet. Here goes the models.py class Report(models.Model): # using default `AutoField`, `id` / `pk` pass class BulkOfReports(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid7, editable=False, verbose_name="ID", ) reports = models.ManyToManyField( Report, verbose_name=_("laporan-laporan"), related_name="bulk_of_reports", ) And for example if those BulkOfReports can be represented like this: BulkOfReports = [Reports_ids] Then with data like this: A = [1, 2, 3] B = [1, 2] C = [1] D = [2] E = [3] How could I get the A option only with Django's QuerySet API? I have tried this: self.reports.filter(id__in=[1, 2, 3]) But what I have is all of those QuerySet mentioned above: A, B, C, D, E -
SMTP ERROR using Django in Railway Production
I am getting error while trying the same end point locally so it's working properly fine but in production it dosen't work and always throwing this error. The code of my settings.py file is as EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True # or False depending on your setup EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') I am using my gmail (codingwithhasnin@gmail.com) and the password which I got from gmail app password which works fine locally and also on AWS EC2 instance but not in railway production. What can be the issue? -
Included App URLs not showing in DRF browsable API
I'm using the Django Rest Framework to provide an API, which works great. All needed URLs for routers and others too are hold in the root urls.py To better handle the growing number of routes I tried to move routes from Apps to their related app folders - as one would do with pure Django. # urls.py from django.contrib import admin from django.urls import include, path from rest_framework.routers import DefaultRouter import core.views router = DefaultRouter() router.register(r'core/settings', core.views.SettingsViewSet, basename='settings') router.register(r'core/organization', core.views.OrgViewSet, basename='org') urlpatterns = [ path('api/', include(router.urls)), path('api/een/', include('een.urls')), path('admin/', admin.site.urls), path('', include('rest_framework.urls', namespace='rest_framework')), path('api/tokenauth/', authviews.obtain_auth_token), ] # een/urls.py from django.urls import path, include from rest_framework import routers from . import views app_name = 'een' router = routers.DefaultRouter() router.register( r'cvs', views.EENSettingsViewSet, basename='een-cvs', ) urlpatterns = [ path('', include(router.urls)), ] Everything shown here is working as expected, but the included URLs are not shown in the browsable API. They are reachable and working, but they are not listed. I do use drf-spectacular, which correctly picks up even the included app urls. I've tried several different combinations, different url order, etc - with no luck. What do I overlook? Or is this a general thing with DRF and I should really keep everything … -
How to architect the external evnets and Django models?
I'm building a django backend app and I have a few different models in my app. One of these models is a Driver and I want to do the following when calling the create-driver endpoint: create the driver in database create a user account for the driver in my B2C directory send an email to the driver on successfull creation send a notification to admins on succesfull creation Operation 1 and 2 should either be succesfull or fail together (an atomic transaction). I was initially handling 1 and 2 in the Driver model's save method like this: Class Driver(models.Model): ... def save(self, *args, **kwargs): if self.pk is None: # Creating a new driver if self.b2c_id is None: graph_client = MicrosoftGraph() try: with transaction.atomic(): user_info = B2CUserInfoSchema( display_name=f"{self.first_name} {self.last_name}", first_name=self.first_name, last_name=self.last_name, email=self.email, phone_number=self.phone, custom_attributes={ "Role": UserRole.DRIVER.value, }, ) res = graph_client.create_user(user_info) # create B2C user self.b2c_id = res.id super().save(*args, **kwargs) # create driver in database except Exception as e: raise e else: # Updating an existing driver super().save(*args, **kwargs)``` This was working perfectly fine but I didn't like mixing responsibilites here and adding the B2C user creation logic to my Driver's save method. I like to keep the save method simple … -
Django with MSSQL Server – GUID Type is maped as char(32) not uniqueidentifier
I would like an app that can easily use different databases. Currently, I’m using SQLite and MSSQL, switching between them via a config file. I noticed that the following field could be quite important from a performance standpoint: user_guid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True, null=False, blank=False, db_index=True ) In MSSQL, the field is mapped as char(32), and I have mixed feelings about that. Over time, I might switch to PostgreSQL, but as I mentioned before, I’m not entirely comfortable using char(32) instead of uniqueidentifier. -
Celery chord, execute code after callback
I am working on a Django application that uses celery tasks for complex and time intensive calculations. I have a task in which subtasks are used to process a large number of combinations of values and determine the best combination based on predefined parameters. The subtasks are created like this: combinations = itertools.product(*bm) # setup for multicore processing using celery tasks static_args = (nt, mp, f, levels) chunk_size = 10000 tasks = _chunked(combinations, chunk_size) chunk_tasks = group(evaluate_combination_chunk.s(list(chunk), static_args) for chunk in tasks) final_task = compare_chunk_results.s() best_result = chord(chunk_tasks)(final_task) # do some stuff with this result return best_result the subtask methods like this: def evaluate_combination_chunk(chunk, static_args): # evaluate a chunk of combinations best_result = None highest_power = -1 for comb in chunk: result = evaluate_combination(comb, *static_args) if result[0] and result[1] > highest_power: best_result = result highest_power = result[1] return best_result and def compare_chunk_results(results): best_result = None highest_power = -1 for result in results: if result: if result[1] > highest_power: best_result = result highest_power = result[1] return best_result both marked with @shared_task(). so i am finding the best result in each chunk (that works just fine based on what i see in the console) and then compare those to find the best … -
Django Serializer - `methodViewSet(viewsets.ViewSet)` is not displayed in url list
I am trying to combine multiple serializers into a single API call, and as a result, I am using viewsets.ViewSet. I am aware that viewsets.ModelViewSet automatically generates the routes, but with viewsets.ViewSet, I am not seeing the expected route for my API. When I switch to viewsets.ModelViewSet, the route becomes available. This makes me think my issue is specific to how viewsets.ViewSet handles routing. According to the documentation (https://www.django-rest-framework.org/api-guide/viewsets/), I should be able to register the URL like I would with ModelViewSet. However, the route doesn't appear when using viewsets.ViewSet. Any suggestions on what might be going wrong? views.py class MethodViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] @action(detail=False, methods=['get'], url_path='method-path') def list(self, request): ... urls.py from rest_framework.routers import DefaultRouter from .views import ( MethodViewSet, ) from rest_framework.authtoken.views import obtain_auth_token router = DefaultRouter() ... router.register(r'method-path', MethodViewSet, basename='methodbasename') -
Twilio Return gathering after client press star
I'm trying to create a fallback gathering if the interpreter hangup from the conference while the client is still on the line, I have to return the gathering to the client to ask him if he wants another interpreter or disconnect everything work perfect but, when the client pressed star, the gather said the first part of the word only, and then the call disconnected def handle_incoming_call(self, call_sid, from_number, language_code): try: with transaction.atomic(): next_interpreter = CallSelector.get_next_interpreter(language_code) conference_name = f"conferenceـ{call_sid}" conference = CallSelector.create_conference( language=next_interpreter.language, interpreter=next_interpreter.interpreter, conference_name=conference_name, ) response = VoiceResponse() response.say("Please wait while we connect you with an interpreter") dial = Dial( hangup_on_star=True, action=f"{settings.BASE_URL}/api/calls/webhook/interpreter_leave/{conference.conference_id}/", timeout=30, ) dial.conference( conference_name, start_conference_on_enter=True, end_conference_on_exit=False, # record=True, # recording_status_callback=f"{settings.BASE_URL}/api/calls/webhook/recording/{conference.conference_id}/", status_callback=f"{settings.BASE_URL}/api/calls/webhook/conference-status/{conference.conference_id}/", status_callback_event="start end join leave announcement", status_callback_method="POST", beep=True, participant_label="client", ) response.append(dial) self._add_client_to_conference(conference, from_number, call_sid), self._call_interpreter(conference, next_interpreter.interpreter), return response except Exception as e: logger.error(f"Call handling failed: {str(e)}", exc_info=True) return self._generate_no_interpreter_twiml() And here is the callback interpreter_leave def handel_interpreter_leave(self, conference_id: str): try: print("Interpreter leave handling started") conference = CallSelector.get_conference_by_conference_id(conference_id) response = VoiceResponse() gather = Gather( num_digits=1, action=f"{settings.BASE_URL}/api/calls/webhook/client_choice/{conference_id}/", method="POST", timeout=10, input="dtmf", ) gather.say("Press 1 to connect with a new interpreter, or press 2 to end the call.") response.append(gather) return response except Exception as e: logger.error(f"Interpreter leave handling failed: {str(e)}", exc_info=True) … -
Show Data of Customer and License from database according to the click on dropdown list of financial year
dropdown financial year show data from database as per the financial year in all pages enter image description here dropdown that i created def get_financial_year(date): year = date.year if date.month < 4: # before April, in the previous financial year year -= 1 return f'{year}-{year + 1}' financial_years = {} for license in licenses: financial_year = get_financial_year(license.Subscription_End_Date) if financial_year not in financial_years: financial_years[financial_year] = 0 financial_years[financial_year] += 1 print(financial_years.keys()) financial_years_list = sorted(financial_years) how show data -
SMTP Error in Django on Production using Railway
I am getting error while trying the same end point locally so it's working properly fine but in production it dosen't work and always throwing this error. The code of my settings.py file is as EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True # or False depending on your setup EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') -
Django view is rendering 404 page instead of given html template
I'm working on a wiki project with django. I'm trying to render 'add.html' with the view add, but it sends me to 404 instead. All the other views are working fine. How should I fix add? views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django import forms import re from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def detail(request, entry): #if search based on title returns result if util.get_entry(entry): content = util.get_entry(entry) return render(request, "encyclopedia/details.html", { "title": entry, "content": content }) else: return render(request, "encyclopedia/404.html", { 'entry': entry }) def add(request): return render(request, "encyclopedia/add.html") urls.py: from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:entry>/", views.detail, name="entry"), path("add/", views.add, name="add"), ] -
How fix redirect after registration? Django
today I faced such a problem that after registration the form does not go anywhere. The catch is that the form does not send a request to the database, but I can create a user through the Django admin panel. views.py def registration(request): if request.method == 'POST': form = UserRegistrationForm(data=request.POST) if form.is_valid(): form.save() user = form.instance auth.login(request, user) messages.success( request, f'{user.username}, Successful Registration' ) return HttpResponseRedirect(reverse('user:login')) else: form = UserRegistrationForm() return render(request, 'users/registration.html') forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm, \ UserCreationForm, UserChangeForm from .models import User class UserLoginForm(AuthenticationForm): username = forms.CharField() password = forms.CharField() class Meta: model = User fields = ['username', 'password'] class UserRegistrationForm(UserCreationForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'username', 'email', 'password1', 'password2', ) first_name = forms.CharField() last_name = forms.CharField() username = forms.CharField() email = forms.CharField() password1 = forms.CharField() password2 = forms.CharField() class ProfileForm(UserChangeForm): class Meta: model = User fields = ( 'image', 'first_name', 'last_name', 'username', 'email', ) image = forms.ImageField(required=False) first_name = forms.CharField() last_name = forms.CharField() username = forms.CharField() email = forms.CharField() registration.html {% extends 'main/base.html' %} {% load static %} {% block title %}Registration{% endblock title %} {% block content %} <section class="login-reg d-flex"> <div class="login-title"> <h2>Registration</h2> <form action="{% … -
Django Template Override Works Locally but Not on Azure
I’m working on a Django project where I’m overriding the submit_line.html template. This override works perfectly in my local development environment, but when I deploy the application to Azure, the override doesn’t seem to take effect. Here’s the custom submit_line.html override in my templates directory: {% extends 'admin/submit_line.html' %} {% load i18n admin_urls %} {% block submit-row %} {{ block.super }} {% for obj in transitions %} <input type="submit" value="{{ obj }}" name="{{ obj }}"> {% endfor %} <!--{{ perms.ForecastResponse }}--> {%if perms.ForecastResponse.add_project%} <input type="submit" value="{% translate 'Clone project from source'%}" name="_cloneproject"> {%endif%} {% endblock %} File structure: myproject/ ├── ForecastResponse/ │ ├── migrations/ │ ├── templates/ │ │ └── admin/ForecastResponse/project │ │ | └── submit_line.html # Overridden template │ │ ├── ForecastResponse/ │ │ │ ├── base.html # Global base template │ │ │ ├── other_template.html │ │ ├── static/ │ │ ├── views.py │ │ ├── models.py │ │ └── admin.py │ ├── manage.py │ ├── settings.py │ ├── urls.py │ └── other_project_files/ What I've tried: Verified that the custom submit_line.html file exists in the correct location on Azure by inspecting the deployed files. Updated the settings.py to include the TEMPLATES section: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
Can not get group permissions by custom User and Group
I create my custom user and group as below: models.py (myusers app) ` from django.db import models from django.contrib.auth.models import AbstractUser, GroupManager, Permission class AbstractGroup(models.Model): name = models.CharField(_("name"), max_length=150, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_("permissions"), blank=True, related_name="fk_group_permission", ) objects = GroupManager() def __str__(self): return self.name def natural_key(self): return (self.name,) class Meta: verbose_name = _("group") verbose_name_plural = _("groups") abstract = True class Group(AbstractGroup): is_active = models.BooleanField(_("Is Active"), default=True) class User(AbstractUser): groups = models.ManyToManyField( Group, verbose_name=_("groups"), blank=True, help_text=_( "The groups this user belongs to. A user will get all permissions " "granted to each of their groups." ), related_name="user_set", related_query_name="user", ) ` and point in settings.py: AUTH_USER_MODEL=myusers.User AUTH_GROUP_MODEL=myusers.Group All is ok but when get group permissions (a_user.get_all_permissions() or a_user.get_group_permissions()) raise error: ValueError: Cannot query “a_user”: Must be “Group” instance. (a_user here is the user user instance) what is wrong? The get_group_permissions() return error. -
retrieving media files on render with django
Hopefully a simple issue that I cannot find any answer to online so far. Background : I have an django web app that is hosted on render.com. Everything is working apart from the media files that are hosted on a bought disk (mounted at /var/data) for my project. I have followed the documentation and added the following to settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = '/var/data' media context is set: "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.template.context_processors.media", ], I have urlpatterns configured for media: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) whitenoise is configured: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' requirements.txt asgiref==3.8.1 click==8.1.8 dj-database-url==2.3.0 Django==5.1.4 django-crispy-forms==2.3 gunicorn==23.0.0 h11==0.14.0 packaging==24.2 pillow==11.0.0 psycopg2-binary==2.9.10 sqlparse==0.5.3 typing_extensions==4.12.2 uvicorn==0.34.0 whitenoise==6.8.2 index.html {% extends "airfryer_app/base.html" %} {% block body %} <div class="product-container flex flex-wrap justify-content-center"> {% for recipe in recipes %} <div class="product shadow-lg w-1/5 rounded-lg m-10"> <div class="product-image"> <img src="{{ recipe.image.url }}" alt=""> </div> <div class="p-5"> <div class="font-bold"> {{ recipe.name }} </div> <div> {{ recipe.description }} </div> <div class="text-orange-700 font-bold text-orange"> {{ recipe.time }} minutes </div> <div class="mt-5"> <a class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded" href="{% url 'recipe' recipe.id %}">View Details</a> </div> </div> </div> {% if forloop.counter|divisibleby:3 %} <div class="w-full"></div> {% endif %} {% endfor %} </div> {% endblock %} Using …