Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CKEditor in django displays as a textarea when i save it from form
I have a form with CKEditor and i need to save it to database. When i save it, it somehow save it with textarea like this: <div> <label for="id_body">Body:</label> <div class="django-ckeditor-widget" data-field-id="id_body" style="display: inline-block;"> <textarea name="body" cols="40" rows="10" required id="id_body" data-processed="0" data-config="{&quot;skin&quot;: &quot;moono-lisa&quot;, &quot;toolbar_Basic&quot;: [[&quot;Source&quot;, &quot;-&quot;, &quot;Bold&quot;, &quot;Italic&quot;]], &quot;toolbar_Full&quot;: [[&quot;Styles&quot;, &quot;Format&quot;, &quot;Bold&quot;, &quot;Italic&quot;, &quot;Underline&quot;, &quot;Strike&quot;, &quot;SpellChecker&quot;, &quot;Undo&quot;, &quot;Redo&quot;], [&quot;Link&quot;, &quot;Unlink&quot;, &quot;Anchor&quot;], [&quot;Image&quot;, &quot;Flash&quot;, &quot;Table&quot;, &quot;HorizontalRule&quot;], [&quot;TextColor&quot;, &quot;BGColor&quot;], [&quot;Smiley&quot;, &quot;SpecialChar&quot;], [&quot;Source&quot;]], &quot;toolbar&quot;: &quot;Full&quot;, &quot;height&quot;: 291, &quot;width&quot;: &quot;100%&quot;, &quot;filebrowserWindowWidth&quot;: 940, &quot;filebrowserWindowHeight&quot;: 725, &quot;language&quot;: &quot;en-us&quot;, &quot;versionCheck&quot;: false}" data-external-plugin-resources="[]" data-id="id_body" data-type="ckeditortype">&lt;p&gt;fhdgh&lt;/p&gt; </textarea> </div> </div> But when i just click save from admin panel it all works perfectly form.html: <div class="form-group"> {{form.as_p}} {{form.media}} </div> forms.py class PostForm(forms.Form): body = forms.CharField(widget = CKEditorWidget()) class Meta: model = Document fields = 'body' models.py from django.db import models from ckeditor.fields import RichTextField from simple_history.models import HistoricalRecords class Document(models.Model): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' header = models.CharField(max_length = 32) body = RichTextField() category = models.ForeignKey(Category, on_delete = models.CASCADE) timestamp = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE) history = HistoricalRecords() def __str__(self): return self.header views.py def add_document_view(request): categories = Category.objects.all() languages = get_language_choices() context = {"allCategories":categories, "form":PostForm, … -
TemplateSyntaxError at \stats2
this is my django code def stats2_view(request): monthly_expenses={} months_ = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] # if request.method == 'POST': # year = request.POST.get('selected_year') # if year: expenses = Expense.objects.filter(owner=request.user, date__year=2024) monthly_expenses = calculate_expense_month_summary(expenses) years = range(2010, datetime.datetime.now().year+1) return render(request, 'expense/stats2.html', {'expense_month_data': monthly_expenses,'yr': years,'months':months_}) and, this template <div class="col-md-6"> <h2>Details</h2> <div class="text-md-start center-paragraph"> <h3>For the year 2024 the break down for each month is as follows</h3> {% for month_num, expense in expense_month_data.items %} <p>Total amount spent in {{ months[month_num]}} till now is <span class="fw-bold">{{ expense }}</span></p> {% endfor %} </div> </div> error Im receiving TemplateSyntaxError at /stats2 i want to print month from the index -
Trouble in integrating express.js with Django
i built a login system for a web app using node and express but my friend built a dashboard in Django. Now I am not sure how to integrate both .How do I authenticate the user in dashboard side? can i run both on a single server? I tried creating a Json web token with email and some other details and storing it in session cookie ,which then is authenticated on dashboard side but that isn't working .I am not sure what to do. -
Collapse tree structure in django
I have a tree structure in Django. It is displayed as a menu. To make it compact, you need to design it as an expandable/collapsible list. How to do this? class Composition(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', db_index=True) mapping = models.BooleanField(default=False) id_drawing = models.ImageField(upload_to='media/image/', blank=True, null=True, default='null') position = models.PositiveIntegerField() designstion = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=255, default='null') description = models.TextField(blank=True, null=True, default='null') quantities = models.PositiveIntegerField(blank=True, null=True, default='null') slug = models.SlugField() objects = TreeManager() @property def drawing_url(self): if self.id_drawing and hasattr(self.id_drawing, 'url'): return self.id_drawing.url class MPTTMeta: order_insertion_by = ['designstion'] class Meta: verbose_name = 'Спецификация' verbose_name_plural = 'Спецификация' def __str__(self): return "%s (%s)" % (self.name, self.designstion) {% recursetree catalog_list %} <li > <a href="{{ node.get_absolute_url }}">{{ node.name }}</a> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> So far it outputs like this: enter image description here It should be like this: enter image description here -
TemplateSyntaxError at /taskapp/taskapp-board/ Could not parse the remainder: '(status='new')' from 'tasks.filter(status='new')'
i got an error called "TemplateSyntaxError", i created a project that handle tasks in this app i create task-board.html page that handle user's task i create 3 section for it 1 section add new task 2nd in-progress tasks, and 3rd completed task, if i want to start that task move new tasks section to inprogress section with help of drag and drop same gose for inprogress to completed section task-board.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Task Board</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <style> .task-section { border: 1px solid #ccc; margin: 10px; padding: 10px; width: 200px; float: left; } </style> </head> <body> <div class="task-section" id="new-section"> <h3>New</h3> <div class="draggable" id="new"> {% for task in tasks.filter(status='new') %} <div class="task" id="task_{{ task.id }}">{{ task.title }}</div> {% endfor %} </div> </div> <div class="task-section" id="in-progress-section"> <h3>In Progress</h3> <div class="draggable" id="in_progress"> {% for task in tasks.filter(status='in_progress') %} <div class="task" id="task_{{ task.id }}">{{ task.title }}</div> {% endfor %} </div> </div> <div class="task-section" id="completed-section"> <h3>Completed</h3> <div class="draggable" id="completed"> {% for task in tasks.filter(status='completed') %} <div class="task" id="task_{{ task.id }}">{{ task.title }}</div> {% endfor %} </div> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function() { $(".draggable").sortable({ connectWith: ".draggable", update: function(event, ui) { var taskId = ui.item.attr("id").split("_")[1]; var … -
Setup HTTP web through WSGI and Websocket through ASGI on the same Heroku app
I've got a quick question for Heroku Pros. How do you handle both websockets(django-channels) and http web dynos together in a Django app? Here's my Procfile setup-web: gunicorn my_proj.wsgi worker: celery -A my_proj.celery_app worker websocket: daphne my_proj.asgi:application --port 8001 --bind 0.0.0.0 -v2 I'm using Gunicorn for regular web stuff and Celery for background tasks, which are all good. But the websocket part isn't kicking in at all. This works fine on local (tested on postman) but after deploying on heroku I try to call this endpoint I get to see NO logs heroku logs -t -d websocket I'm using Django-channels with ASGI, hence Daphne (also tried uvicorn), but it just stalls out. After digging around a bit, I stumbled on the fact that Heroku doesn't play nice with multiple ports. Not sure if I've got that right, but assuming I do, how can I get this working? I could do below as well (which is working fine!) web: daphne logistics_service.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: celery -A logistics_service.celery_app worker But I'd rather not switch everything over to ASGI for the basic web stuff. My question is do I need to use a process manager like Supervisor or maybe create … -
HTMX Syntax Error When Retrieving data Value from Event in Django View
I have a view def tag_delete(request): if request.method == 'POST': tag_name = request.POST.get("tag") tag = Tag.objects.get(name=tag_name) tag.delete() response = HttpResponse(status=204, headers={'HX-Trigger': json.dumps({ "taglistchangeddelete": {"tag": tag_name} })}) return response When the user clicks a button to delete a tag, this view is called. This view works fine. But the problem start because i have a session variable that contains a list of selected tags. If the tag that has been deleted is in this list, it should be removed from there. So, I created another view to handle this deletion: def process_tags_deleted(request, tag): selected_tags = request.session['selected_tags'] if tag in selected_tags: selected_tags.remove(tag) request.session['selected_tags'] = selected_tags #The rendered template will show the user their selected tags response = render(request, 'espace/tags_selected.html', { 'selected_tags': selected_tags, }) return response To call the process_tag_deleted function, I created an HTMX get request within a random div in the template: <div hx-get={% url 'process_tags_deleted' %} hx-vals='{"tag": evt.detail.tag}' hx-target="#tags_selected" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}' hx-trigger="taglistchangeddelete"> </div> I'm pretty sure that the problem lies in the hx-vals. I can't retrieve the 'tag' value that comes from the event "taglistchangeddelete". It gives a syntax HTMX error in the console: htmx:syntax:error b @ htmx.min.js:1 function b(e) { if (console.error) { console.error(e) #ERROR } else … -
Nginx is showng welcome-page instead of my Django-app
Here is /etc/nginx/sites-available/myapp: server{ listen 80; listen [::]:80; server_name .somedomain.com; location = /favicon.ico{access_log off; log_not_found off;} location /static/ {root /var/www/myapp;} location / {include proxy_params; proxy_pass http://unix:/run/gunicorn.sock;} } Nginx doesn't show my app instead of welcome-page Also made a simlimk to sites-enabled. I'm using Django + gunicorn to handle this app, so using ddns and already set my router port preferences. Gunicorn runs the application normally, but on localhost. Nginx does not want to transfer the application to the domain, although every guide says that it should simply launch it if there are no errors. I didn't change anything in nginx.conf, so it looks like: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } -
django.contrib.auth user added can't authenticate
New user created by this sign_up can't login. I can see the user successfully created through admin portal. Only super user can login. What is missing here? forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username','first_name','last_name','email'] labels= {'email': 'Email'} views.py def sign_up(request): if request. Method == "POST": fm=SignUpForm(request.POST) if fm.is_valid(): fm.save() messages.success(request, 'Account Created Successfully !!') else: fm = SignUpForm() return render(request, 'enroll/signup.html', {'form':fm}) def user_login(request): if not request.user.is_authenticated: if request.method == "POST": fm = AuthenticationForm(request=request, data=request.POST) if fm.is_valid(): uname = fm.cleaned_data['username'] upass = fm.cleaned_data['password'] user = authenticate(request, username=uname, password=upass) else: fm = AuthenticationForm() return render(request, 'enroll/userlogin.html', {'form' : fm}) if user is not None: print(user) login(request,user) messages.success(request,'Logged in Successfully !!') return HttpResponseRedirect('/profile/') else: fm=AuthenticationForm() return render(request, 'enroll/userlogin.html', {'form': fm}) else: return HttpResponseRedirect('/profile/') -
How to handle authentication and authorization process if the users data are stored in elasticsearch database?
I am working on a project in which its backend side is implemented using Django framework, and its database is Elastic Search. I have seen several Django projects in which their authentication has been done using JWT(Json Web Token) and related packages. But in my project since all the user data like first name, last name, username and password are stored in an elastic index, I do not know what is the best way to implement a secure authorization and authentication process using tokens which should have time limits. I have searched on net, but could not find relative and helpful results. The only solution which I decided to try was to clone Django-Rest-Simple-JWT repository, and then change all of its models to elastic indices, and change all of their usages. But I think there must be better ways to handle this problem. I will be really grateful for any advice, solution or suggestion. -
Docker is running very slow in ubuntu 18.04 for a simple django hello world
I am just learning dockr generally but specifically for django. I am still very new to docker and all the question on SO does not seem to help me reduce the build time I have tried to dockerize my hello wold app of django, it has taken moe than 3.5 hours for the process of downloading and extacting packages in docker, this seems to be part of a stage 1 of 5 stages in the building process. this is my dockerfile # The first instruction is what image we want to base our container on # We Use an official Python runtime as a parent image FROM python:3.6 # set environment variables #ENV PYTHONDONTWRITEBYTECODE =1 ENV PYTHONBUFFERED = 1 # where your code lives WORKDIR /app ## Allows docker to cache installed dependencies between builds COPY requirements.txt requirements.txt # install dependencies #RUN pip install --upgrade pip # run this command to install all dependencies RUN pip install -r requirements.txt ##old docker file start ## Allows docker to cache installed dependencies between builds #COPY requirements.txt requirements.txt #RUN pip install --no-cache-dir -r requirements.txt # copy whole project to your docker home directory. COPY . . EXPOSE 8000 CMD python3 manage.py runserver Also … -
Substitute auth_user model not authenticating properly (Django)
Hello everyone I started working on a Django app for a class project but I am running into some confusion when trying to authenticate custom users. The app is a social media platform for my school and as per the requirements of the project I must attach a biography and a role (position at the school). I figured the best way to do this is to attach it to the existing auth_user model but upon following almost all the content I could find users wont authenticate. Even when supplied the correct information the user object is still None. To start off lets take a look at my user model which is declared in an app called "landingpage" from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio=models.TextField() role=models.CharField(max_length=32) Then we go to the main app and declare which AUTH_USER_MODEL we want AUTH_USER_MODEL = "landingpage.User" Finally applying the migration commands python manage.py makemigrations python manage.py migrate Then to test it out I have this code. My login system is a popup form so in order to avoid visiting the page I just redirect back to the index which also refreshes the page so I can update content based on the authenticated user. There is … -
What is best way to implement RBAC in Django?
I have this scenario for a software system: A company has many teams. People belong to different teams and have different roles in each team they belong. They have documents stored on a server and they have a web interface to edit those files over web. It is obvious that we want the people to have only the permissions to have specific access (based on their role in a specific team) on their team's files. As an example, consider Mary. Mary belongs to three teams in this company, namely 'ABC', 'DEF', 'GHI'. Mary is the admin of 'ABC', scrum master of 'DEF' and a simple developer in 'GHI'. Now Mary should be able to: do whatever she wants in 'ABC' team view documents related to 'DEF' team edit documents related to 'GHI' team So, I hope you have understood the scenario. The question here is that obviously, default auth app (with its default settings) provided by Django is not that much useful for implementing this scenario, however, I can make make some changes to somehow work around the problem. I can create Django groups like this: ABC_admin ABC_scrummaster ABC_developers And so on. I mean I create a Django group object … -
Pre-populating DateField in Django REST Framework Serializer Not Working
I am developing a web application using Django and Django REST Framework. I have a serializer with a date field that I want to pre-populate with the current date when the form is displayed. The rest framework documentation demonstrate how to use initial to pre-populate a field, but it doesn't seems to be working. Despite following the documentation, the date field of my form displays "yyyy-mm-dd". Environment: django==3.2.18 djangorestframework==3.14.0 Here is my current code: # serializer.py class FormSerializerCurrentStatus(ModelSerializer): date = serializers.DateField(initial=datetime.date.today) class Meta: model = CurrentStatus fields = ('date', 'user', 'currentstatus') # views.py def retrieve(self, request, *args, **kwargs): form_serializer = FormSerializerCurrentStatus() return Response({'serializer': form_serializer}) # html <form action="{% url 'SomeUrl' %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> I have also attempted to override the init method of the serializer to set the initial value of the date field. Does anyone could help me understand what my mistake might be? Thank you! -
How to replicate RegisterSerializer.custom_signup for social signups
I have overridden RegisterSerializer.custom_signup (REGISTER_SERIALIZER) to set certain parameters in the user's profile based on cookie values and it works fine when a user registers using email/password. However, what I realized was that it's not getting called when the user registers through social (Google, specifically). I found SocialLoginSerializer.post_signup which sounds like it might be the right place to inject similar logic, but I am not sure how to tell dj_rest_auth to use the overridden class. There does not appear to be an equivalent to the REGISTER_SERIALIZER config variable that points to the new class. I also considered moving this logic to User's post_save signal event, but unfortunately one can't access the request therefore any cookies from there (without some middleware acrobatics). I am using dj_rest_auth 4.0.1 and allauth 0.50.0 Thanks in advance for any pointers. -
How can I filter my contacts by user that it belongs?
I need to show names that belong only to one user.. models.py class Contact(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=False) surname = models.CharField(max_length=50, null=True, blank=True, unique=False) father_name = models.CharField(max_length=50, null=True, blank=True, unique=False) dob = models.DateField(null=True, blank=True, unique=False) photo = models.ImageField(upload_to='static/photos/', null=True, blank=True) email = email = models.EmailField(max_length=254, null=True, blank=True, unique=False) phone_number = models.CharField(max_length=12, null=False, blank=False, unique=False) contact_belongs_to = models.ForeignKey(User, on_delete=models.CASCADE) views.py def post(self, request:HttpRequest)->HttpResponse: form = ContactForm(request.POST) if form.is_valid(): Contact.objects.create(name=form.cleaned_data['name'], surname=form.cleaned_data['surname'], father_name=form.cleaned_data['father_name'], dob=form.cleaned_data['dob'], photo=form.cleaned_data['photo'], email=form.cleaned_data['email'], phone_number=form.cleaned_data['phone_number'], contact_belongs_to=request.user).save() return HttpResponse('OK') else: return render(request, 'contacts/contact_form.html', context={'form':form}) this is how 'contact_belongs_to' takes value->user And when user wants to see only his own contacts I should filter them by 'contact_belongs_to' or no? Could you help please... -
Unable to list all api endpoints in swagger file in django and drf spectacular
Unable to list all api endpoints in swagger file. API endpoints are working as expected wrt functionalities. I'm using py3 and gunicorn as I need this deployed. Settings.py of djServer project has all req settings REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema' } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_spectacular', 'corsheaders', 'djApi', 'djBookings', 'sample', ] #djServer/djServer/urls.py """ URL configuration for djServer project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from drf_spectacular.views import( SpectacularAPIView, SpectacularSwaggerView, ) from django.contrib import admin from django.urls import path, include, re_path from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('help/Schema/',SpectacularAPIView.as_view(),name='help-schema'), path('help/Docs/',SpectacularSwaggerView.as_view(url_name='help-schema'),name='help-docs'), path('sampleApi/', include('sample.urls')), path('api/', include('djApi.urls')), path('bookings/', include('djBookings.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) While the project has many djnago apps … -
Chaining django queries on dates not working as expected
I have a Django 4.2 app with a model Album. The Album model has a DateTimeField called date. I run a query to select albums by the year in launch_date: >>> launch_date = datetime(2014, 5, 10) >>> albums = Album.objects.filter(date__year=launch_date.year) >>> albums <QuerySet [<Album: 732 - September 30, 2014>, <Album: 734 - February 6, 2009>, <Album: 735 - March 29, 2010>, <Album: 736 - April 5, 2010>, <Album: 738 - May 20, 2014>]> >>> for a in albums: print(a.album_id, a.date.year, a.date.month) 732 2014 10 734 2014 10 735 2014 10 736 2014 10 738 2014 5 Which is what I expected. However, when I run this query to further filter the albums by month, it fails. I expected the query to return the one album with album_id = 738: >>> albums.filter(date__month=launch_date.month) <QuerySet []> These chained filters do not produce the results I expected, either: >>> Album.objects.filter(date__year=2014, date__month=5) <QuerySet []> >>> Album.objects.filter(date__year=launch_date.year).filter(date__month=launch_date.month) <QuerySet []> What am i doing wrong? -
Django messages with javascript fetch() API and redirect
I am doing a request with the fetch() API to a django view, which will set a message with the messages app and redirect the request. I can capture the redirect with response.redirected and the messages-cookie is set, but when i do the redirect with location.replace, the messages get lost. How do i pass on the messages from the original response? The django view: def add(request): if request.method != 'POST': return HttpResponse("not post") pproject = request.POST['pproject'] print("pproject:", pproject) messages.add_message(request, messages.INFO, "Test.") return redirect("project_detail") my urls.py: path('project/add/', views_project.add, name='project_add'), and in my template (javascript): var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; const headers = new Headers(); headers.append("X-CSRFToken", csrftoken); const form = new FormData(); form.append("pproject", "{{ project.id }}"); const ops = { method: "POST", headers: headers, body: form, credentials: "same-origin" }; const req = new Request("{% url 'project_add' %}"); fetch(req, ops) .then((response) => { if (response.redirected) { console.log("response redirect:", response); window.location.replace(response.url); return false; } else if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } else { return response.json(); // Parse JSON response } }) -
Passing Form Data to pre-select django-filter sets before loading view
My problem: I'm utilizing Django and bootstrap4 crispy forms to simply display data from one of my database tables with a django-filters included in order to provide more in-depth information. The issue is, this table can have upwards of 20 million records. Though I've implemented a pagination technique to allow for loading all 20 million records rather quickly... it is still not ideal! What I would like to do is create a non-model-based form that I can use to get the request.POST.get() data and load the view with 2 of my django-filters selected and "locked." I already have the form and structure in place to successfully load all records and filter, I'm just not quite sure how to actually pass the data from my form to my view and render it with 2 filters pre-selected, locked so users can't change them... I know I'll need to load the model based on the filter selection but need help with how to pass that data and use it to render the view with filters pre-selected and applied. Consider the example/flow below as expected behavior: example flow -
Websites and their release on the Internet [closed]
Hello, I need to bring the site online, I have html and css, how do I bring them online, should I use something? according to the Django/React type, how were sites displayed before? to put them on the server I do not know what to try and how to start, I think to start with django or what? -
Do redirect with a imported function in a called view
I have a Django App "A" with a view "view_A" where I execute a function: from app_B.views import usercheck_B def view_A(request): function_B(request) return render(request) And in my Django App "B" with a function "usercheck_B": def usercheck_B(request): if not request.user.is_authenticated: redirect('view_B:login') What I want is, that a directly redirect the client if he is not logged in in the called function. But that is not working. I only can return a Httpresponse to my first called view "view_A" a redirect to login. My idea is to place the usercheck_B function in every view I have and redirect visitors. But I want to do this check also in special cases if for exapmple other parameters are not fitting. -
if user is already logged in do not show sign in form
I have used User Creation Form for user registration. class UserSignUpView(SuccessMessageMixin, FormView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'core/signup.html' success_message = 'Account created successfully.' When user is already logged in it should not see the signup form -
TypeError: 'module' object is not iterable. Django DeleteView
I am writing Django app named polls I decided to put Deleteview there in polls/views.py I put from django.views.generic.edit import DeleteView class QuestionDelete(DeleteView): model = Question success_url = reverse('polls:index') in polls/urls.py in urlpatterns I added a line path('createnewchoice/', views.create_question_with_choices, name="create_new_choice_question"), and in templates/polls I created question_confirm_delete.html <form method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ object }}"?</p> {{ form }} <input type="submit" value="Confirm"> </form> Before that always worked fine but after I run python manage.py runserver I get folowing Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/urls/resolvers.py", line 740, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/management/base.py", line 486, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "/Users/myuser/PycharmProjects/mypolls1/venv/lib/python3.11/site-packages/django/urls/resolvers.py", … -
Troubleshooting TemplateDoesNotExist Error in Django Despite Correct Configuration
I'm relatively new to Django and encountering an issue with template loading in my project. Despite following tutorials and setting up my project structure correctly, I'm facing a TemplateDoesNotExist error. Here's my project structure: storefront\__pycache__ storefront\storefront\__init__.py storefront\storefront\asgi.py storefront\storefront\settings.py storefront\storefront\urls.py storefront\storefront\wsgi.py playground playground\__pycache__ playground\migrations playground\templates playground\__init__.py playground\admin.py playground\apps.py playground\models.py playground\tests.py playground\urls.py playground\views.py db.sqlite3 manage.py In my settings.py, the template configuration is as follows: python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] However, when trying to render a template using the render function in my view: #python from django.shortcuts import render def say_hello(request): return render(request, 'playground/hello.html') I'm encountering the TemplateDoesNotExist error for playground/hello.html. I've verified my project structure, and it appears to be correct. Could someone provide guidance on what might be causing this issue and how to resolve it? Any beginner-friendly explanations or suggestions would be greatly appreciated!