Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I run a function on each post in my list view and pass a boolean variable into my html?
My html {% if is_liked %} <i class="fa fa-check" aria-hidden="true"></i> {% else %} <i class="fa fa-times" aria-hidden="true"></i> {% endif %} My views.py class PostListView(ListView): queryset = Post.objects.filter(created__range=['2020-03-01', '2020-03-31']) template_name = 'main/problems.html' context_object_name = 'posts' ordering = ['-created'] for post in queryset: def get_liked(self): if self.likes.filter(id=self.request.user.id).exists(): is_liked = True else: is_liked = False return is_liked Even if I set both conditionals to return true my html does not read is_liked as true. -
CORS Policy Issue Between React and Django App
I got this issue when trying to get data in my React app from my Django app: Access to XMLHttpRequest at 'https://quiet-retreat-95482.herokuapp.com/api/todos/' from origin 'https://infallible-jackson-111720.netlify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I made a React todo list app and deployed it here: https://infallible-jackson-111720.netlify.com/ I made my Django backend and deployed it on Heroku: https://quiet-retreat-95482.herokuapp.com/ In my backend code, I think I installed and have the correct settings for corsheader: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'todo' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'https://infallible-jackson-111720.netlify.com' ] import django_heroku django_heroku.settings(locals()) I also had requirements.txt and Procfile for heroku and the app was deployed successfully. I was able to get data locally when my backend was running on my localhost: http://127.0.0.1:8000/api/todos/ What was the cause of this error and how can I fix it? If need any other information, please let me know. Thank you a lot! -
Iterate over several querysets in django template with nested loop
I am making a hotell-page, and have made models for bookings and rooms. I want to display the bookings related to a room in a table, and have the related bookings laying under the spesific room. I show the code from the views.py file here: def vaskehjelp(response): available_rooms = Room.objects.filter(available=True) room_nums = [] context = {} for room in available_rooms: related_bookings = Booking.objects.filter(room=room) if related_bookings: room_nums.append(room.room_no) context[room.room_no] = related_bookings context["room_nums"] = room_nums context["available_rooms"] = available_rooms print(context) return render(response, "../templates/se_vaskbare_rom.html", context) and the code from my template file here: <table class="table table-striped table-dark"> <tr class="thead-dark"> <th scope="col">Room No.</th> <th scope="col">Capacity</th> <th scope="col">Room Type</th> </tr> {% for item in available_rooms %} <tr scope="row"> <td>{{ item.room_no }}</td> <td>{{ item.capacity }}</td> <td>{{ item.room_type }}</td> </tr> {% if item.room_no in room_nums %} {% for booking in item.room_no %} <h1></h1> <tr scope="row"> <td>{{ booking.cin_date }}</td> <td>ku</td> <td>{{ booking.cout_date }}</td> </tr> {% endfor %} {% endif %} {% endfor %} </table> The problem is that the booking-element in the template code doesent seem to work. I dont manage to access the lists of bookings related to the current selected room. As you see i have an outer for loop to iterate over the rooms, and then the … -
psycopg2.errors.UndefinedColumn: column ... does not exist
Hello I am trying to migrate an app 'projects'. On my local machine, I had made many changes to the model over time and so I have many different migrations for the app. When I am trying to migrate to my web server, I receive an error on the fourth migration file. Error: Applying projects.0001_initial... OK Applying projects.0002_auto_20200227_1959... OK Applying projects.0003_project_garage... OK Applying projects.0004_auto_20200301_2331...Traceback (most recent call last): File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column projects_project.accessible_to_foreigners does not exist LINE 1: ...opertytype2", "projects_project"."propertytype3", "projects_... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 233, in handle fake_initial=fake_initial, File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/spadmin/pyapps/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state … -
Python django model validate min and max value
I want to limit the title to between 3 and 25 characters. I could not get MinLengthValidator to work. I'm new to Python. class Video(models.Model): title = models.CharField(max_length=255) url = models.URLField() youtube_id = models.CharField(max_length=255) def clean_title_length(self): data = self.cleaned_data['title'] length= len(data) if length < 3 or length > 25: raise ValidationError("The length of the title must be between 3 and 25 characters") else: return data views.py def add_video(request): form = VideoForm() if request.method == 'POST': filled_form = VideoForm(request.POST) if filled_form.is_valid(): The above form always returns valid. Suggestion on how I can get this range validator to work? TIA -
Django admin for User changes Groups widget when I add a custom admin
I want to use the out-of-the-box User model in Django, but add an action to the admin. Without any custom admin, the User's admin has this many-to-many control for groups: But when I register a custom Admin: class CustomModelAdmin(admin.ModelAdmin): actions = ['custom_action'] def custom_action(self, request, queryset): pass custom_action.short_description = "Custom Action" admin.site.unregister(User) admin.site.register(User, CustomModelAdmin) The control changes to a simpler select. I want the original one, as my list of groups may get large. Why did it change? How do restore it to the former? -
How to get a model's last access date in Django?
I'm building a Django application, and in it I would like to track whenever a particular model was last accessed. I'm opting for this in order to build a user activity history. I know Django provides auto_now and auto_now_add, but these do not do what I want them to do. The latter tracks when a model was created, and the former tracks when it was last modified, which is different from when it was last accessed, mind you. I've tried adding another datetime field to my model's specification: accessed_on = models.DateTimeField() Then I try to update the model's access manually by calling the following after each access: model.accessed_on = datetime.utcnow() model.save() But it still won't work. I've gone through the django documentation for an answer, but couldn't find one. Help would be much appreciated. -
upload_to attribute giving wrong path
upload_to attribute isn't working correctly. I have no idea what's causing this, instead of uploading a file I'm getting a SuspiciousFileOperation exception. The base path component stated in the exception is correct but joined path is not correct as it should just be 'img/posts'. I'm looking for a reason that's causing this. models.py thumbnail = models.FileField(upload_to='img/posts') Exception value The joined path (/media/tb1.jpg) is located outside of the base path component (/home/user/Documents/project/project/media) -
encoded html reportlab python
I am creating a pdf with reportlab in python I have the following problem one of the data has to show is type longText because html strings have been saved, as I decode it to show it in my pdf if the data arrives as follows, sometimes html will come tables and would like to keep them. I do the following but it still looks the same comentatios = '<p><br></p><table class="table table-bordered"><tbody><tr><td>dato 1</td><td>dato 2</td></tr><tr><td>dato 3</td><td>dato 4</td></tr></tbody></table><p><br></p>' from six.moves.html_parser import HTMLParser h = HTMLParser() data = [][enter image description here][1] data.append(['Comentarios',h.unescape(comentarios),'','']) t4 = Table( data, ) -
Why does I get either NoReverseMatch or FieldError
I am working on a project, and want to create a report on a film. (That it doesn´t exist) At the moment I only get error when I try to go to either film// or film//report. Can anybody help me? **models.py** class Report(models.Model): title = models.CharField(default="", max_length=100) comment = models.TextField(default="") reporter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Reporter") # receiver = models.ForeignKey( # User, on_delete=models.CASCADE, related_name="Receiver" # ) reports = models.ForeignKey(Film, on_delete=models.CASCADE) def __str__(self): # pragma: no cover return f"{self.reporter.username} reports {self.reports.title}" **urls.py** urlpatterns = [ path("", views.films_view, name="board-home"), path("film/add", FilmAddView.as_view(), name="film-add"), path("film/<int:pk>/", FilmDetailView.as_view(), name="film-detail"), path("film/<int:pk>/report", FilmReport.as_view(), name="film-report") ] **views.py** class FilmReport(LoginRequiredMixin, UpdateView): model = Report fields = ["title", "reported"] # def __str__(self): # return self.title def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) This should be the page where I can click on "Report", and then be redirected to a report page. **film_detail.html** {% extends "board/base.html" %} {% block content %} <article class="media content-section"> <img class="rounded-circle film-img" src="/media/{{object.poster}}"> <!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. --> <a href=" {% url 'film-add' %}" class="waves-effect waves-light green btn"><i class="material-icons right">rate_review</i>add review</a> <a href=" {% url 'film-report' %}" class="waves-effect waves-light red darken-4"><i class="material-icons right">report</i>report</a> <!-- <a onclick="myFunction()" class="waves-effect … -
Django choices that change automatically based on male/female checkboxes. Categories will be displayed based on the gender choice
I have searched on the internet but did not find anything suitable. I want to have a model that will have a a set of choices of categories which will change based on whether the male or female checkbox/choice (whichever is more appropriate) was selected. In models.py, class MyModel(models.Model): MALE_CATEGORIES = { ('Male Category 1', 'Male Category 1'), ('Male Category 2', 'Male Category 2'), ('Male Category 3', 'Male Category 3'), } FEMALE_CATEGORIES = { ('Female Category 1', 'Female Category 1'), ('Female Category 2', 'Female Category 2'), ('Female Category 3', 'Female Category 3'), } # Male/Female option as either choices or checkboxes depending on whichever one is more suitable gender = # Either MALE_CATEGORIES or FEMALE_CATEGORIES # Depending on gender categories = models.CharField(max_length=18, choices=) In forms.py, class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'gender', 'categories', ] -
Can't create PostGis extension on PostgreSQL database?
I'm trying to create a postgis extension on my PostgreSQL database for a Django project, but when I run CREATE EXTENSION postgis I get this error: ERROR: extension "postgis" has no installation script nor update path for version "3.0.1" I installed all the dependencies with Homebrew on macOS, and this database is not on the 'postgres' user, it's on my own superuser. Homebrew Dependency Versions postgresql@12.2 postgis@3.0.1 gdal@2.4.4 geos@3.8.1 proj@7.0.0 Any help is appreciated!! Been working on this issue for the last week. -
Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name
I am trying to create a new post and when I click on the save button, I get error as stated in the image. I am not able to understand the error and where to look for it. I am new at django. Please help! Main-urls.py file: from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog_app.urls', namespace='blog_app')), url(r'^accounts/',include('accounts.urls', namespace='accounts')), #path('accounts/login/', views.LoginView.as_view(template_name='blog_app/login.html'),name='login'), #path('accounts/logout/',views.LogoutView.as_view(template_name='blog_app/base.html'),name='logout'), ] blog_app-urls.py file: from django.conf.urls import url from blog_app import views from django.urls import path app_name = 'blog_app' urlpatterns = [ url(r'^$', views.PostListView.as_view(),name='post_list'), url(r'^about/$', views.AboutView.as_view(),name='about'), url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(),name='post_detail'), url(r'^post/new/$', views.CreatePostView.as_view(),name='new_post'), url(r'^post/(?P<pk>\d+)/edit/$', views.UpdatePostView.as_view(),name='edit_post'), url(r'^drafts/$', views.DraftListView.as_view(),name='draft_post_list'), url(r'^post/(?P<pk>\d+)/remove/$', views.DeletePostView.as_view(),name='delete_post'), # url(r'^post/(?P<pk>\d+)/remove/$', views.post_remove,name='delete_post'), url(r'^post/(?P<pk>\d+)/publish/$', views.post_publish, name='post_publish'), url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'), url(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve, name='comment_approve'), url(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove, name='comment_remove'), # path('register/',views.register,name='register'), ] blog_app-views.py file: from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from django.contrib.auth.decorators import login_required from blog_app.models import Post,Comment from blog_app.forms import PostForm,CommentForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.views.generic import (TemplateView,ListView,DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login,logout,authenticate class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(publish_date__lte = timezone.now()).order_by('-publish_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): … -
modelForm got an unexpected argument 'initial'
modelForm got an unexpected argument 'initial' I am getting this error. please can anyone explain how to solve this ? Here is my model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None) StudentID = models.CharField(max_length=8, blank=False, unique=True) Branch = models.CharField(max_length=255,choices=Departments,default="CSE") def __str__(self): return f'{self.user.username} Profile' class complaintForm(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) category = models.CharField(max_length=255,choices=complaints,default='Mess') title = models.CharField(max_length=20) content = models.CharField(max_length=100) image = models.ImageField(upload_to='complaint_pics/') def __str__(self): return self.title form.py class complaintForm(forms.ModelForm): class Meta: model = complaintForm fields = ['title','content','image',] views.py class CreateComplaintView(CreateView): model = complaintForm form_class = complaintForm template_name = 'user/post_complaint.html' success_url = 'success' -
Django - Which model field for dir path?
I need to define a field in my Model, which is supposed to host a valid dir path on server-side. Basically just a string which should be: 1) a formally valid unix-like dir path 2) an existing dir path Tried with FilePathField with options allow_files=False, allow_folders=True . But when I try to create a new instance of the model from the django admin CRUD, I'm getting an error claiming that the initial value of the field (which is by default an empty string) is a not existing path... I have a feeling this is not the right way. Maybe another field type could be more suitable? Maybe it should be just a simple string? (in this case, shall I be able to define correctly the required validators?) Thanks for any hint, Thomas -
chage choice_field if the name starts with A Django
thanks for your time: i'd like to take one choice option off if the name of the People starts with letter 'a': basically if People.nome or People.user starts with letter 'A' i'd like to take the choice (2,'GATO') off. is there a way to do that or should i try another aproach besides a ChoiceField models.py User = get_user_model() class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nome = models.CharField(max_length=200) birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.nome) field_choices1 = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO') ] field_choices2 = [ (1, 'CACHORRO'), (3, 'OUTRO') ] def field_choice(): one = People.user slug = slugify(one) big = slug.upper() initial_big = big[0] if initial_big == 'A': return field_choices1 else: return field_choices2 class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField(choices=field_choice()) forms.py class PetForm(forms.ModelForm): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] name = forms.CharField(max_length=100) tipo = forms.ChoiceField(choices=field_choices) custo = forms.DecimalField(max_digits=7, decimal_places=2) class Meta: prefix = 'animal' model = Animal fields = ('name', 'tipo', 'custo') def clean(self): people_name = self.People.nome upper = people_name.upper() if upper[0] == 'A': Pets.tipo != 2 i've tried o couple of ways: the models.py try returns always … -
How to create unique user folders for different users in django
I have two a user and project models. I want to create a unique folder for each project for a user. In this scenario, whenever the creates a new project, a new project folder is added to the user's folder. So, I want something like this: User_1 Project_1 Project_2 User_2 Project_1 Project_2 Project_3 I am aware of shuntil, I would like to make user that the folder name for each user folder is unique for the user. The name of the project Currently, I have hard coded the following: In my settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) USER_DIR=os.path.join(BASE_DIR, 'User_1/') In another.py I have: settings.ONTOLOGY_DIR + "Project_1/testing.txt" The scenario, I would have to change the USER_DIR path to User_2 if I want the files/folders for user2. Now, instead of hard coding to get the testing.txt. I want to do this dynamically get the testing.txt based on the user that is authenticated. -
Pass form validation errors back to Wagtail Page template
I have a Wagtail Page model that I am using to render a form. I have overridden the get_context and serve methods to pass in the form as page context and then validate it when receiving a POST request: class RegistrationPage(Page): ... def get_context(self, request, *args, **kwargs): # Avoid circular dependency from registration.forms import RegistrationForm context = super().get_context(request) context["form"] = RegistrationForm return context def serve(self, request, *args, **kwargs): # Avoid circular dependency from registration.forms import RegistrationForm if request.method == "POST": registration_form = RegistrationForm(request.POST) if registration_form.is_valid(): registration = registration_form.save() return redirect("/") else: # How do I return the form with validation errors? else: return super().serve(request) Question: When the form validation fails, how do I pass the form back to the template so the user can see the validation errors? -
3 blocks link together base, category and article
hello I tried to make a block in another block more exactly basic block (fixed) block category (variable) block article (variable) but the problem the part of the category that I would like to leave it in the block article disappears which is normal but I don't want it to be erased you have a solution to offer me -
Django Timezones with offsite server
I have a django project running on a digital ocean server in Toronto Canada. I have clients in Winnipeg and Toronto both using the application. I am confused on the correct method of storing and retrieving dates using Django. In my settings.py I have: TIME_ZONE = 'America/Toronto' USE_I18N = True USE_L10N = True USE_TZ = True And in my various python code when I am storing dates in the project I use: from django.utils import timezone from django.utils.timezone import utc myTimeStamp = timezone.localtime(timezone.now()) Then to show the time in my Django Templates I use: {% load tz %} {{myTimeStamp|localtime}} When I view this template in Winnipeg, the time is wrong by 1 hour (it is showing Toronto time) The easy fix is to change the settings.py to TIME_ZONE = 'America/Winnipeg but then I would assume people in Toronto would be seeing the wrong time (Winnipeg time). The challenge I'm having is that people are writing to the database from multiple timezones and reviewing data from multiple timezones, and I'm confused as heck as you can tell! Any help is appreciated Where am I going wrong here? My assumption is that you write to the database in the timezone where the … -
Reporting in django
I need some advice on what to do. I am developing an app for a course at my university. The userstory I working on at the moment is: "As a user I want to be able to report films that doesn´t exist." My thought was to have a report-button at my film_detail.html, where clicking this button would trigger the BooleanField in my model, and mark the film as reported. When clicking the report-button I was thinking on just having a pop-up window to confirm the reporting, and I believe I won´t need to create a complete new view for this(?). Does anyone have any idea on how to do this (cause I´m kinda stuck), or maybe having a better idea? **models.py** class Film(models.Model): title = models.CharField(max_length=100) title_short = models.CharField(max_length=17, default=None, null=True) plot = models.TextField() poster = models.ImageField(default="default.png", upload_to="posters") release_date = models.DateField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) reported = models.BooleanField("Is reported", default=False) #class Admin: # list_display = ("is_reported") #def is_reported(self): # return self.reported == True #is_reported.BooleanField = False **HTML** {% extends "board/base.html" %} {% block content %} <article class="media content-section"> <img class="rounded-circle film-img" src="/media/{{object.poster}}"> <!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. --> <!-- <a href=" … -
python 3.8 inconsistent tabs and spaces
when running py manage.py runserver it shows me the following message: File "C: \ Django \ mysite \ forms \ views.py", line 38 producto_sel.delete () Taberror: inconsistent use of tabs and spaces in identation this is views.py: from django.shortcuts import render, redirect from .models import Productos from .forms import RegistrarProducto def index (request): mis_productos = Productos.objects.all() if request.method == 'POST': register_form = RegistrarProducto(request.POST) if register_form.is_valid(): success = register_form.registrar_producto() return redirect('./') else: register_form = RegistrarProducto() return render(request, 'forms/mi_form.html',{'register_form': register_form, 'productos':mis_productos}) def actualizar_producto(request, producto_id): producto_id=int(producto_id) try: producto_sel=Productos.objects.get(id=producto_id) except Productos.DoesNotExist: return redirect('forms/mi_form.html') form = RegistarProducto(request.POST or None, instance=producto_sel) if form.is_valid(): form.save() return redirect('/') return render(request, 'forms/mi_form.html', {'register_form': register_form}) def borrar_producto(request, producto_id): producto_id=int(producto_id) try: producto_sel=Productos.objects.get(id=producto_id) except Productos.DoesNotExist: return redirect('forms/mi_form.html') producto_sel.delete() return redirect('/') try to correct the error with pyhton idle by selecting from product_sel.delete () Format> Untabify Region but the error is not fixed -
Django does redirect to "Next" after custom login when login is required
When I use the login view provided by Django, it redirects to the desired page. My code is as follows: urls.py from django.urls import path from admn import views as views from django.contrib.auth import views as log_views urlpatterns = [ path('login/', log_views.LoginView.as_view(template_name='login.html'), name='login'), path('profile/', views.profile, name='profile'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required @login_required(login_url='/login/') def profile(request): return render (request, 'profile.html') However, when I use a customized login (I need it to check other things), it logs in but does not redirect anymore. My code is as follows: urls.py from admn import views as views from django.urls import path urlpatterns = [ path('login/', views.login, name='administration-login'), path('profile/', views.profile, name='profile'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from myforms import UserLoginForm from django.contrib import messages def login(request): if request.method == 'POST': form = UserLoginForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: dj_login(request, user) messages.success(request, f'You are logged in {username}!') else: messages.error(request, f'Not logged in') else: form = Admin_UserLoginForm() return render (request, 'login.html',{'form':form}) @login_required(login_url='/login/') def profile(request): return render (request, 'profile.html') -
How to get template variables by using FormView?
I am currently following Mozilla's Django tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms). The tutorial mostly shows how to create form using functions. I am trying to make the same function view work by using a generic class view (FormView). I am able to make most of the code to work except for 2 things. First one is that I can't seem to be able to save the due date. And, second one, is that I don't know how to access the model fields in my template using template variables. Here is my form model from the forms.py file. class RenewBookModelForm(ModelForm): def clean_due_back(self): data = self.cleaned_data['due_back'] # Check if a date is not in the past. if data < datetime.date.today(): raise ValidationError(ugettext_lazy( 'Invalid date - renewal in past')) # Check if a date is in the allowed range (+4 weeks from today). if data > datetime.date.today() + datetime.timedelta(weeks=4): raise ValidationError(ugettext_lazy( 'Invalid date - renewal more than 4 weeks ahead')) # Remember to always return the cleaned data. return data class Meta: model = BookInstance fields = ['due_back'] labels = {'due_back': ugettext_lazy('New renewal date')} help_texts = {'due_back': ugettext_lazy( 'Enter a date between now and 4 weeks (default 3).')} The form model implemented as a function: @permission_required('catalog.can_mark_returned') … -
is there anyway to connect django with sharepoint
i'm an intern and they asked me to create a web app and deploy it where employees insert their workhour daily but this web app has to connect with sharepoint to import files also if there is any changes in project status like in progress done anything like that , it has to be changed too in sharepoint ps:is there any requirement any web language i should learn before creating this web app if so how to connect the app with sharepoint and how about the database? also if there is any help in deployement ill be thankful :)))