Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Return search results in template
I have a search form that looks like this: <form class="main_cont_nav_searchform" method='GET' action='/api-search/'> <div class="main_cont_nav_searchform_group"> <input class="main_cont_nav_searchform_input" placeholder="search for users..." type="search" name="search"> <div class="main_cont_nav_searchform_btn" type="submit">Search</div> </div> </form> And a view that looks like this: class UserSearchView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [filters.SearchFilter] search_fields = ['username'] I get the correct response, but how can I return the search result in a template? Thank you for any suggestions -
Is there any method to add bootstrap style to Django password input field?
I'm trying to add a registration page to my Django project and I have made the registration form in the forms.py file. class createUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username' : forms.TextInput(attrs={'class':'form-control form-input','placeholder':'Username...'}), 'email' : forms.EmailInput(attrs={'class':'form-control form-input','placeholder':'Email...'}), 'password1' : forms.PasswordInput(attrs={'class':'form-control form-input','placeholder':'Password'}), 'password2' : forms.PasswordInput(attrs={'class':'form-control form-input','placeholder':'Re-type password'}), } HTML <h4>Sign in</h4> <div class="form-container"> <form method="POST" action=""> <div class="form-render" style="display: block;"> {% csrf_token %} <div style="margin-bottom: 1rem;"> {{form.username}} </div> <div style="margin-bottom: 1rem;"> {{form.email}} </div> <div style="margin-bottom: 1rem;"> {{form.password1}} </div> <div style="margin-bottom: 1rem;"> {{form.password2}} </div> <button type="submit" class="btn btn-primary" style="border-radius: 0px; outline-color: #167896; background-color:#167896; width: 15rem; margin-left: 1.5rem;">Submit</button> </div> </form> <div style="display: flex; margin-left: 1.75rem; margin-top: 1rem; margin-bottom: 0rem;"> <p>Already have an account?</p><a style="text-decoration: none; " class="forgot" href="{% url 'login' %}">&nbsp Log in</a> </div> </div> After rendering out HTML, bootstrap styles are not added to the password input fields. This is the screenshot of my output page. -
How do I get a specific field in Django query?
I'm trying to query only a specific field in Django model. After some searching, I figured out that I need to use only(). However I need to use filter(authuser=request.user) as well. How do I make it possible? Thank you. -
Cannot create many-to-many object with multiple connections
I have a Playlist object and also a Song object. In the playlist model, I defined a many-to-many field that allows playlist to store multiple songs inside of it. Through the admin interface, I can easily create a playlist object that has multiple songs inside of it. However, when I try to create a playlist object through a template's multiple selection form, the playlist object is created with only one song object attached to it. I have tried to add songs to it by iterating through the request.POST[] of the multiple selection while using .add(), or to set it using .set(), however, all of them ended up with only one of the songs being added to the playlist object. Here is the related code: models.py: class Song(models.Model): song_title = models.TextField(max_length=128) album = models.ForeignKey(Album, on_delete=models.CASCADE) def __str__(self): return f"{self.song_title}" class Playlist(models.Model): creator = models.ForeignKey(Profile, on_delete=models.CASCADE) playlist_name = models.CharField(max_length=128) description = models.TextField(max_length=1024) playlist_content = models.ManyToManyField(Song, blank=True, related_name="playlist_content") def __str__(self): return f"{self.playlist_name}: {self.description}" views.py: def create_playlist(request): if request.method == "GET": all_songs = Song.objects.all() profile = Profile.objects.get(user=request.user) return render(request, "website/create_playlist.html", { "songs": all_songs, "profile": profile }) if request.method == "POST": creator = Profile.objects.get(user=request.user) title = request.POST["playlist_title"] description = request.POST["description"] p = Playlist.objects.create(creator=creator, playlist_name=title, description=description) … -
Not Found: /hello/
> from django.http import HttpResponse > from django.shortcuts import render > > # Create your views here. > def index(request): > return HttpResponse("Hellow, World !") from django.urls import path from . import views urlspattern=[ path("",views.index,name="index") ] from django.contrib import admin from django.urls import include,path urlpatterns = [ path('admin/', admin.site.urls), path("hello/", include("hello.urls")) ] INSTALLED_APPS = [ 'hello', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Error I am gettting is Using the URLconf defined in helloproject.urls, Django tried these URL patterns, in this order: admin/ The current path, hello/, didn't match any of these. -
Sendgrid port shiftingh
I got the following mail form SentGrid, "Twilio SendGrid is removing access to our APIs via http, port 80. Once we remove this access, your requests to APIs via the mentioned endpoints will be rejected if not sent via https, port 443. If you are currently using http, port 80, please update your call to https, port 443. Http, port 80, requests will be rejected on October 1st, 2020." Prresenly i am sending maild to sentgrid by using following credentials, EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'#gateway_settings.EmailBackend EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_USE_TLS = False EMAIL_PORT = 587 EMAIL_HOST_USER = 'xx@gmail.com' EMAIL_HOST_PASSWORD = 'xxx' Is this port shifting affect me? -
Clean architecture/repository pattern in Django
I'm trying to find common agreements about implementing clean architecture in Django. Could you help me? At least I wanna remove repository logic from controllers ( views ) something like that: posts = Post.objects.all . It shouldn't be in controllers -
Url is not showing on server even if i map my url in dajnago url.py file
from django.contrib import admin from django.urls import path from HR import views urlpatterns = [ path('Home/', views.Home_page,name='HOME'), path('About/', views.About_page,name='ABOUT'), path('NewCompany/',views.New_registraion,name='NEW_COMPANY'), path('EngLog/',views.location,name='ENGINEER_LOGIN'), path('EngReg',views.Eng_registraion,name='ENGINEER_REGISTRATION'), path('DeleteUser/', views.Delete_user, name='DELETE_USER') from django.contrib.auth.models import User def Delete_user(request): username1=request.POST.get('username') print(username1) s1='' if request.method=='POST': s=User.objects.filter(username=username1) print(s) s1=s[0] print(s1) if s1 == username1: User.objects.filter(username=username1).delete() messages.success(request,'User is deleletd successfully') print('hello') else: messages.success(request, 'User withe eneter user name is not found') return render(request,'deleteUser.html') Using the URLconf defined in APP.urls, Django tried these URL patterns, in this order: > admin/ HR/ Home/ [name='HOME'] HR/ About/ [name='ABOUT'] HR/ > NewCompany/ [name='NEW_COMPANY'] HR/ EngLog/ [name='ENGINEER_LOGIN'] > HR/ EngReg [name='ENGINEER_REGISTRATION'] Owner/ Supplier/ RowProduct/ > The current path, HR/UserDelete, didn't match any of these. -
New page loading instead of the one I want while rendering in django
This is my views.py: def payment(request): if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() shippingddress=ShippingAddress.objects.filter(customer=customer) context={ 'items':items, 'order':order, 'ship':shippingddress } param_dict = { "requestType" : "Payment", 'MID': 'abcd', } param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(param_dict, MERCHANT_KEY) return render(request, 'paytm.html', {'param_dict': param_dict,}) return render(request,"payment.html",context) and this is my urls.py: path("payment/",views.payment,name="payment"), Whenever I write localhost/payment instead of opening the payment html page it takes me to paytm.html(the action url): <form action="https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=TzoyBB65679567960126'&orderId='{{order.id}}'" method="post" name="paytm"> {% for key,value in param_dict.items %} <input type="hidden" name="{{key}}" value="{{value}}"> {% endfor %} </form> What I want is that on opening localhost/payment it should open /payment page only and in that payment page when someone clicks on continue button then paytm.html should open but this is not working currently. Please help me. -
How do I use Django templates in React frontend?
I have a website with Django as the backend and React frontend. As per this website, social-auth-django provides Django templates like so: <a href="{% url "social:begin" "google-oauth2" %}">Google+</a> How can I use this template to find which URL is being hit so that I can have this button in the React frontend, and when clicked it, how would the data exchange take place between the client (React) and server(Django)? Currently, my URLs.py inside api app looks like this: path('social-auth/', include('social_django.urls', namespace='social')), And when I visit http://localhost:3001/api/v1/social-auth/login I get the following error. TIA. -
i am making a school management system and my media files are not uploading but when i upload from admin page it was working properly
the image field is working from admin page but i want to make it work in web page models.py class StudentRegisteration(models.Model): name = models.CharField(max_length=150) father_name = models.CharField(max_length=150) mother_name = models.CharField(max_length=150, blank=True) GENDER = ( ("Male", "Male"), ("Female", "Female"), ("Other", "Other"), ) gender = models.CharField(max_length=50, choices=GENDER) image = models.ImageField(upload_to="students_pics", blank=True) father_mobile = models.CharField(max_length=50) mother_mobile = models.CharField(max_length=50, blank=True) current_adress = models.CharField(max_length=200, blank=True) email_id = models.EmailField(max_length=254, blank=True) add_in_class = models.ForeignKey(Classes, on_delete=models.CASCADE) def __str__(self): return self.name settings.py but i did not do any this in urls.py STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(BASE_DIR, "assets") MEDIA_url = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media") forms.py in forms.py i made some widgets to style my form but i tryed tafter removing all widgets but nothing was changed class StudentForm(ModelForm): class Meta: model = StudentRegisteration fields = "__all__" widgets = { "gender": forms.Select( attrs={"class": "form-control", "id": "default-select",} ), "add_in_class": forms.Select( attrs={"class": "form-control", "id": "default-select"} ), "name": forms.TextInput(attrs={"class": "form-control"}), "father_name": forms.TextInput(attrs={"class": "form-control"}), "mother_name": forms.TextInput(attrs={"class": "form-control"}), "father_mobile": forms.TextInput(attrs={"class": "form-control"}), "mother_mobile": forms.TextInput(attrs={"class": "form-control"}), "current_adress": forms.TextInput(attrs={"class": "form-control"}), "email_id": forms.TextInput(attrs={"class": "form-control"}), "image": forms.FileInput(attrs={"class": "form-control"}), } views.py in views.py file i try differant function and views but nothing worked def StudentCreate(request): if request.method == "POST": form = StudentForm(request.POST) if form.is_valid(): form.save() sn … -
Extended user model not save password correctly
im trying to create a child and parent objects at the same time with same form. After migrations, i have two tables, user as always and doctor, whith the relationship with user in a extra column called user_ptr_id. models.py: class Doctor(User): collegiated = models.CharField(verbose_name="Nº Colegiado", max_length=20, null=True, blank=True) phone = models.CharField(verbose_name="Teléfono", max_length=12, null=True, blank=True) class Patient(User): age = models.PositiveIntegerField(verbose_name="Edad", blank=True) forms.py: class DoctorForm(forms.ModelForm): class Meta: model = app_models.Doctor fields = ['username', 'email', 'password'] view.py: if request.method == 'POST: form = DoctorForm(request.POST.copy()) if form.is_valid(): forms.save() else: form = DoctorForm() return ... The two objects are created, doctor and user, well related with user_ptr_id but the user password appears unencrypted. ¿ How can i integrate UserCreationForm on child models ? ¿ How can i solve this issue ? Anybody could help me please? Thanks in advance. -
E-cart for e-commerce using django channels( without using ajax)
I want to make E-cart for an e-commerce website using Django channels.. How can I do that? (I don't want to use ajax) is there anyway to get CRUD operation in real time without reloading the page from backend? -
How to get colaperation in github/
I just finished my django and react course and now I'm trying to practice web stackby cloning an app called notion.so. I just started with that project but I'm looking for who want share or learn with me. So if anyone from stackoverflow like this idea please join me, also if you know more about social networks for such purposes inform me as well. my project repo: https://github.com/aliplutus/Learning-webstack-from-cloning-notion.so -
django says you don't have column even if i have one
This is my models file and remember i am using django version 2.2 from django.db import models # Create your models here. class User(AbstractUser): pass class Content(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") body = models.TextField(default="type here") subject = models.CharField(max_length=255) archived = models.BooleanField(default=False) def serialize(self): return { "body": self.body, "subject": self.subject, "archived": self.archived } this is my view where i am calling the body of content def new_diary(request): if request.method == "POST": content=Content(body=request.POST["body"],user=request.user,archived=False) content.save() context={"content":content} return render(request, "diary.html",context) And this is the error message:table diary_content has no column named body And i am migrating those files and tried deleting the migration files and doing it again -
Getting field value with DjangoRestFramework serializer
I have two models: class Restaurant(models.Model): adress = models.CharField(max_length=240) name = models.CharField(max_length=140) class RestaurantReview(models.Model): review_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) I use DRF and front-end I need the values of the fields to use in Vue.je templates. Here is my serializer: class RestaurantReviewSerializer(serializers.ModelSerializer): restaurant_name = serializers.CharField(source='restaurant.name') restaurant_adress = serializers.CharField(source='restaurant.adress') created_at = serializers.SerializerMethodField() review_author = serializers.StringRelatedField(read_only=True) class Meta: model = RestaurantReview fields = ('id','restaurant_name','restaurant_adress','created_at','review_author') def get_created_at(self, instance): return instance.created_at.strftime("%d %B, %Y") I get the right data I need but my problem is now I can't update/create new models. As suggested I added ('read_only'=True) but the result is the same. Should I use to_representation to get the same CRUD posibilities than with: class RestaurantReviewSerializer(serializers.ModelSerializer): class Meta: model = RestaurantReview field = fields = '__all__' But with the benefit to have for exemple 'restaurant' named after its name and not its ID so I can use it in my template? -
Django POST request showing up as a GET request w/ parameters in the url
As far as I can tell this is a normal form with a post method and an action url but I must be doing something wrong to be getting the error at the bottom. But it's showing up as a GET request with all of the form data as url parameters, any advice on why this is the case? urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("dogDetails/<int:dog_id>", views.dogDetails, name="dogDetails"), path("userPage/<int:user_id>", views.userPage, name="userPage"), path("dogSearch", views.dogSearch, name="dogSearch"), path("dogMatch", views.dogMatch, name="dogMatch") ] dogMatch.html: {% extends "layout.html" %} {% block heading %} Dog Match {% endblock %} {% block body %} <div id="myDogsContainer" class="container"> <h4 class="mt-5">My Dog Match Test</h4> <div class="row border border-light rounded col-7 bg-light mb-3"> <form action="{% url 'dogMatch' %} method="POST"> {% csrf_token %} <div class="my-2"> Do you want to spend a lot of time with your dog? <div class="watcherCount">(False would be for someone who wants a dog who is more independent)</div> <br> <input type="radio" id="attentionTrue" name="attention" value="True"> <label for="attentionTrue">True</label> <br> <input type="radio" id="attentionFalse" name="attention" value="False"> <label for="attentionFalse">False</label> <br> </div> <div class="my-2"> Do you want an active dog who needs … -
how can I access userprofile from another user?
I need some help when I create a user and user profile accordingly and when I try to access to any user by another user the request turns me on the request I work on not the real user, although, I'm using the slug to specify what the user I click on it maybe I can not explain what happens to me exactly for more explanation, please click on that video to show what I mean: https://www.youtube.com/watch?v=MzSo0ay2_Xk&feature=youtu.be accounts app models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.template.defaultfilters import slugify CHOICE = [('male', 'male'), ('female', 'female')] class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) slug = models.SlugField(max_length=100, unique=True, blank=True) overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet') city = models.CharField(max_length=20, blank=False) phone = models.IntegerField(default=0, blank=True) sex = models.CharField(max_length=10, default='male', choices=CHOICE) skill = models.CharField(max_length=100, default='You have no skills yet') logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): self.slug = slugify(self.user) super().save(*args, **kwargs) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(receiver=create_profile, sender=User) view.py class ViewProfile(UpdateView): queryset = UserProfile.objects.all() template_name = 'accounts/profile.html' form_class = UpdateInfoForm slug_field = 'slug' slug_url_kwarg = 'user_slug' def get_success_url(self): return reverse_lazy('accounts:view_profile', kwargs={'user_slug': self.request.user.userprofile.slug}) def get_context_data(self, **kwargs): context … -
How to run a Docker Container in Heroku
I am writing a Python Django web application which is currently deployed on Heroku. For certain kinds of requests, I want to run a docker container in an isolated environment. For example, one of my API endpoints looks like this: import docker def post(request): # do some work here... client = docker.from_env() client.containers.run('some-image', 'some command') # format and return response here... How can I setup my Heroku application so that I can create and run docker containers like this from within my web application? I have tested everything locally and verified that it works. All I need is to deploy this to Heroku. -
Django not reconnecting to database?
I am using Django channels and once the database connection gets closed, it keeps on returning the following error for subsequent events in consumer: Exception inside application: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. My question is that why is Django not trying to reconnect to database server automatically. If I have to handle it, where should I handle it? Should I wrap the try except around the whole code and reconnect whenever this error occur. I am using pgbouncer layer in between and my database config looks like: 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_pgbouncer', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': '<ip>', 'PORT': '6432', 'CONN_MAX_AGE': None Edit 1 I happen to notice is when I am running something in atomic block like: with transaction.atomic(using='write') as it is working fine at other places. -
Passing Jquery Variable data to Django views
I need to pass the variable from the Jquery to the Django view on the event of the button click from the HTML table. I need to fetch col1, col2 and col3 values from the Jquery and pass it to the "strtestdb" view function in django on clicking the download button HTML (table.html) <table id="rawdatatable" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%"> <thead> <tr align="center"> <!-- <th>ID</th> --> <th>Date</th> <th>Category</th> <th>Sub_cat</th> <th>employee</th> <th>Quantity</th> <th>status</th> </tr> </thead> <tbody> {% for item in data %} <tr align="center"> <td {{ item.date}}</td> <td>{{ item.cat_description }}</td> <td>{{ item.sub}}</td> <td>{{ item.employee}}</td> <td>{{ item.quantity}}</td> <td> <button type="button" class="btn btn-outline-success" href="{% url 'strtestdb' %}">Download</button> </td> </tr> {% endfor %} </tbody> </table> Jquery <script> $(document).ready(function () { $("#rawdatatable").on('click', '.btn', function () { var currentRow = $(this).closest("tr"); var col1 = currentRow.find("td:eq(0)").text(); var col2 = currentRow.find("td:eq(1)").text(); var col3 = currentRow.find("td:eq(2)").text(); var pieFact = col1 + "\n" + col2 + "\n" + col3; alert(pieFact); }); </script> -
Limit user posts/day django (just as what stackoverflow did)
Here is my post model class Post(models.Model): title = models.CharField(max_length=40, blank=True, null=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='comments/posts_images/', null=True, blank=True) post_file = models.FileField(upload_to='comments/file_uploades/', blank=True, null=True) category = models.ForeignKey( Category, on_delete=models.CASCADE,) user = models.ForeignKey(User, on_delete=models.CASCADE) # Voting likes = models.ManyToManyField(User, related_name='post_like', blank=True) dislikes = models.ManyToManyField(User, related_name='post_dislike', blank=True) # AUTO post_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Post by user: {self.user}' here is my user model: class User(AbstractUser): friends = models.ManyToManyField('User', blank=True) bio = models.CharField( max_length=400, default='I love this website!', blank=True, null=True,) avatar = models.ImageField( upload_to='profile_images', default='profile_images/DefaultUserImage.jpg',) ... allow_friend_request = models.BooleanField(default=True) # MAX SENDING max_posts = models.IntegerField(default=0) now in views.py: def create_post(request, pk): category = get_object_or_404(Category, pk=pk) #! NOT SERIALIZING IMAGES # Images category if request.user.max_posts >= 3: messages.error( request, f'You can only make 3 posts a day, please wait till tommorow') return redirect('categories:view_category', pk=pk) else: # if pk == 1: # image = request.GET.get('image') # description = request.GET.get('description') # if image: # if description: # post = Post(description=description, image=image, # user=request.user, category=category) # post.save() # else: # post = Post(description=description, # user=request.user, category=category) # post.save() # else: # # todo return error # pass # Fun Area Category if pk == 2: post = Post(user=request.user, category=category) if request.POST['description']: post.description = request.POST['description'] … -
Django - How to set date format for models.DateField()? Terminal keeps throwing date validation error
I could not find a way to change the format for models.Datefield(). My application accepts date input from users in the format "%m%d%YY". Is there any way I can change the date format for Datefield() django model? Please help My models.py from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class reservations_db(models.Model): name = models.CharField(max_length=100) email = models.EmailField() phone = PhoneNumberField(blank=False) date = models.DateField(null=True, blank=False) time = models.TimeField() person = models.IntegerField() class Meta(): verbose_name_plural = "Reservations list" My views.py from django.shortcuts import render from .models import reservations_db # Create your views here. def reservation(request): if request.method == 'POST': object=reservations_db() object.name = request.POST['name'] object.email = request.POST['email'] object.phone = request.POST['phone'] object.date = request.POST['date'] object.time = request.POST['time'] object.person = request.POST['person'] object.save() return render(request,'reservation.html') Migration file class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='reservations_db', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('email', models.EmailField(max_length=254)), ('phone', phonenumber_field.modelfields.PhoneNumberField(max_length=128, region=None)), ('date', models.DateTimeField(null=True)), ('time', models.TimeField()), ('person', models.IntegerField()), ], options={ 'verbose_name_plural': 'Reservations list', }, ), ] Terminal error message: File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\OneDrive - CACTUS\My Documents\GitHub\Libbys_restaurant\booktable\views.py", line 14, in reservation object.save() File "C:\Users\libin.thomas\Envs\freelancing\lib\site-packages\django\db\models\base.py", line … -
Django inbuilt loginview not working for Non Staff Users
Hi I used a custom user model and django inbuilt authentication to login and logout my urls.py is from django.contrib.auth import views ..... path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'),] It logs in for superuser credentials but for Non-Staff users it redirects to the login page again. So in order to find out the methods that are being called I tried to print the method names in the console to see what actually happens. The below output I got for superuser: dispatch AnonymousUser False Dispatch Inside Class View If Method <bound method ProcessFormView.post of <django.contrib.auth.views.LoginView object at 0x7f165c1635b0>> post get_form_kwargs {'initial': {}, 'prefix': None, 'data': <QueryDict: {'csrfmiddlewaretoken': ['kWGzAoldTVleKHXezf98LX4RbgoOs4ZRO3RI2UjAIJoUYpmYPvQj52HztqZRE5mn'], 'username': ['surendersingh1995nov@gmail.com'], 'password': ['Singo*1995'], 'next': ['/profile/']}>, 'files': <MultiValueDict: {}>} form_valid <WSGIRequest: POST '/login/'> surendersingh1995nov@gmail.com get_redirect_url First the dispatch method is called then dispatch method inside class View is called and so on. Similarly for Non-Staff Users the output which I got is: dispatch AnonymousUser False Dispatch Inside Class View If Method <bound method ProcessFormView.post of <django.contrib.auth.views.LoginView object at 0x7f165c1a7940>> post get_form_kwargs {'initial': {}, 'prefix': None, 'data': <QueryDict: {'csrfmiddlewaretoken': ['6ex3Kzt2KNFrGYM3WAvwClLIQqu73vGlAlIcc5rpzBI7UGbNcQcHWqoq8A5afw3R'], 'username': ['arjunsingh1995nov@gmail.com'], 'password': ['Singo*1995'], 'next': ['/profile/']}>, 'files': <MultiValueDict: {}>} get_context_data get_context_data get_redirect_url The only difference is in this the form_valid method is not being … -
Problem sorting bibliography by author in a Django model with ManyToMany relationship while preserving proper author order
I'm very new to Django so please forgive this question if the answer is obvious. I have struggled with it for several days and finally found a workaround but I'm certain there has to be a better way. Here's the issue in a nutshell: I'm building a Django web site to lists books on various topics. The main listing should be sorted alphabetically by author and that part is easy. Call this 'vertical sorting'. However, quite a few of the books have multiple authors and the ordering of authors for a given book is not alphabetical: it could be anything, e.g., Author B and Author A instead of Author A and Author B. Call this 'horizontal sorting." The problem is that the default SelectMultiple widget for Django forms allows you to select multiple items but doesn't allow you to specify the ordering. It always comes out alphabetically. I found a way to force the ordering I want but this had the undesirable effect of breaking the vertical sorting. Here's a snippet of my Publication model: class Publication(models.Model): """A class to define publication fields""" author = models.ManyToManyField(Author, related_name='publications') title = models.CharField(max_length=200) [snip...] where the Author model (not shown) is sorted alphabetically …