Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send a welcome email after the user has confirmed his account in django
I'm trying to figure out how I can send welcome emails in Django after the user confirms their account. The welcome email should be sent only to users who have their emails confirmed (active users after signing up) and should be sent after the confirmation email. Any help in solving this will be highly appreciated models from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views from django.contrib.auth import login from django.contrib.auth.models import User from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode from core.tokens import account_activation_token # Sign Up View class SignUpView(View): form_class = SignUpForm template_name = 'commons/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('emails/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return redirect('login') return render(request, self.template_name, {'form': … -
django rest framework what is login as the definition
Let me say in advance that thank you for reading my question. The problem I'm facing is related to login and permission from frontend. For example, log in as a user from the browser(like hit localhost:8080/admin in the search engine), and then you can see the user name on the right upper side of the screen which indicates the user is logged in. How Django identify the user login is that when you log in csrftoken is created and set in the cookies, so if you delete csrftoken, the username is disappeared, so you need to log in to access admin if you need. This login system is related to permission.IsAutenticated, so if 'DEFAULT_PERMISSION_CLASSES' : ['rest_framework.permissions.IsAuthenticated'], you cannot access any data if you are not logged in. Then I implemented social google login which receives google access_token to log in as a Django user(I will omit to describe how to get a google access token process), which works fine in the browser. I can see the username on the screen, and permission is working ok. But when I hit google social login endpoint from the front end, I can't log in, also csrftoken is not created in the cookies.(no error … -
PERFORMANCE Calling multiple times a posgres db to get filtered queries vs querying all objects and filtering in my django view
I'm working in a Django project and it has a postgreSQL db. I'm calling multiple times the model to filter the results: latest = Product.objects.all().order_by('-update_date')[:4] best_rate = Product.objects.all().order_by('rating')[:2] expensive = Product.objects.all().order_by('-price)[:3] But I wonder if it's better for performance and resources consumption to just do 1 query and get all the objects from the database and do the filtering inside my Django view. all = Product.objects.all() # Do some filtering here iterating over variable all Which of these do you think would be the best approximation? Or do you have a better option? -
Trying to embed a form within a form of foreign keys
I'm trying to create a form where a logged in user (PrincipalGuest) can update themselves but also multiple guests (AccompanyingGuest). I want an entire form with the attending and dietary_restrictions field embedded within a form, not just the ModelMultipleChoiceField. models.py class Guest(models.Model): """ """ attending = models.ManyToManyField("itinerary.Event", blank=True) dietary_restrictions = models.ManyToManyField(DietaryRestrictions, blank=True) last_modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class PrincipalGuest(Guest, AbstractUser): """ """ USERNAME_FIELD = "email" REQUIRED_FIELDS = [] username = None email = models.EmailField(_("email address"), unique=True) phone_number = PhoneNumberField(null=True) address = AddressField(on_delete=models.CASCADE, null=True) objects = PrincipalGuestManager() @property def name(self): return self.first_name + " " + self.last_name def __str__(self): return self.name class AccompanyingGuest(Guest): """ """ principal = models.ForeignKey( PrincipalGuest, related_name="accompanying_guests", on_delete=models.CASCADE ) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_under_ten = models.BooleanField(default=False) @property def name(self): return self.first_name + " " + self.last_name def __str__(self): return self.name views.py class RendezvousFormView(SuccessMessageMixin, UpdateView): template_name = "rsvp.html" form_class = RendezvousForm success_url = "/rsvp" success_message = "Thank you for your RSVP" def get_object(self): return self.request.user forms.py class RendezvousForm(ModelForm): """ """ first_name = CharField( label="", widget=TextInput(attrs={"placeholder": "First Name"}) ) last_name = CharField( label="", widget=TextInput(attrs={"placeholder": "Last Name"}) ) email = CharField(label="", widget=TextInput(attrs={"placeholder": "Email"})) phone_number = CharField( label="", widget=TextInput(attrs={"placeholder": "Phone Number"}) ) address = AddressField( label="", widget=AddressWidget(attrs={"placeholder": … -
NOT NULL constraint failed: ial_profile.user_id
I am new to Django and was trying to follow a tutorial. But i came across this problem and is not able to solve it myself. When i try to access 127.0.0.1:8000/profile/id(1,2,3...) then it is throwing 'IntegrityError'. Can anyone please help me to overcome it? Code example : views.py from django.shortcuts import render from .models import Profile # Create your views here. def dashboard(request): return render(request, "base.html") def profile_list(request): profiles = Profile.objects.exclude(user=request.user.id) return render(request, "ial/profile_list.html", {"profiles": profiles}) def profile(request, pk): if not hasattr(request.user, 'profile'): missing_profile = Profile(user=request.user.id) missing_profile.save() profile = Profile.objects.get(pk=pk) # edit 1 if request.method == "POST": current_user_profile = request.user.profile data = request.POST action = data.get("follow") if action == "follow": current_user_profile.follows.add(profile) elif action == "unfollow": current_user_profile.follows.remove(profile) current_user_profile.save() return render(request, 'ial/profile.html', {'profile': profile}) models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField( "self", related_name = "followed_by", symmetrical=False, blank=True ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() user_profile.follows.set([instance.profile.id]) user_profile.save() profile.html {% extends 'base.html' %} {% block content %} <div class="column"> <div class="block"> <h1 class="title is-1"> {{profile.user.username|upper}}'s djail </h1> </div> … -
Django DecimalField fails to save even though I give it a floating number
class WithdrawRequests(models.Model): withdraw_hash = models.CharField(max_length=255, unique=True, db_index=True) timestamp = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=255, unique=False, db_index=True) currency = models.CharField(max_length=255, unique=False, db_index=True) user_balance = models.DecimalField(max_digits=300, default=0.0, decimal_places=150) withdraw_address = models.CharField(max_length=255, unique=False, db_index=True) withdraw_amount = models.DecimalField(max_digits=30, default=0.0, decimal_places=15) This is my models.py file. currency = request.data['currency'] payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) timestamp = datetime.datetime.now() timestamp = timestamp.timestamp() withdraw_hash = hashlib.sha256() withdraw_hash.update(str(timestamp).encode("utf-8")) withdraw_hash = withdraw_hash.hexdigest() username = user.username currency_balance = GAME_CURRENCIES[request.data['currency']] user_balance = getattr(user, currency_balance) withdraw_address = request.data['withdraw_address'] withdraw_amount = request.data['withdraw_amount'] if user_balance < withdraw_amount: return Response({ "message": "Not enough funds." }) else: # row format - hash timestamp username currency user_balance withdraw_address withdraw_amount withdraw = WithdrawRequests() withdraw.withdraw_hash = withdraw_hash, withdraw.timestamp = datetime.datetime.now(), withdraw.username = username, withdraw.currency = currency, withdraw.user_balance = user_balance, withdraw.withdraw_address = withdraw_address, withdraw.withdraw_amount = withdraw_amount withdraw.save() And here is the views.py file. Whatever I do the error is the following. ... File "C:\Users\Msi\cover_game\cover\lib\site-packages\django\db\models\fields\__init__.py", line 1554, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: ['“(0.011095555563904999,)” value must be a decimal number.'] As you can see with user_balance everything is fine and it's floating number. -
how to upload multipe images in django rest framework(drf)
I want to upload multiple images,Is there a way to do it without using foreign keys. The images is just a attribute in my model. model.py class sellGoods(models.Model): img = models.ImageField(max_length=100, upload_to=get_file_path, default='sell.png', verbose_name='图片', null=True, blank=True) # 与用户绑定 # user = models.ForeignKey(UserInfo, on_delete=models.CASCADE) goods_name = models.CharField(verbose_name=_('物品名称'), max_length=90) # Many attributes are omitted here serializers.py ` class sellSerializer(serializers.ModelSerializer): class Meta: model = sellGoods fields = '__all__' ` view.py class sellGoodsList(APIView): def post(self, request, format=None): serializer = sellSerializer(data=request.data) qdata = request.data print('1: ',qdata) print('2: ',qdata['img']) print('3: ',qdata.get('img')) print('------------') if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) in postman Realize uploading multiple image -
Getting values from django database
I'm just learning python and django. I am writing a thing that reads the values in the xlsx file, and if the values are similar to those in the database, then the value in the adjacent column in the xlsx file changes to the one I specify models.py class imgUpload(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to='img') def __str__(self): return self.title views.py def upload_xlsx(request): if request.method == 'POST': form = xlsxForm(request.POST, request.FILES) if form.is_valid(): form.save() fileName = xlsxUpload.objects.last() fileNameStr = str(fileName.file) book = load_workbook(fileNameStr) sheet: worksheet = book.worksheets[0] for row in range(2, sheet.max_row + 1): a = sheet[row][0].value fileNameImg = imgUpload.objects.all() fileNameImgStr = fileNameImg.filter(title=a) if a == fileNameImgStr: sheet[row][1].value = str(fileNameImgStr) book.save(fileNameStr) book.close() return redirect('xlsx_list') else: form = xlsxForm() return render(request, 'img/upload_xlsx.html', { 'form': form }) I have achieved that it takes all the values, but does not compare them -
How do I get rid of labels in django Form?
I have dealt with only ModelForm previously, so it is my first time using Form. I'd like to get rid of labels from my form, however, how I get rid of labels in ModelForm does not seem to work with Form. Here is my code: forms.py class UserLoginForm(forms.Form): email = forms.CharField(max_length=255) password = forms.CharField(max_length=255) labels = { 'email': '', 'password': '' } widgets = { 'email': forms.TextInput(attrs={'class': 'login_input', 'placeholder': 'Email'}), 'password': forms.PasswordInput(attrs={'class': 'login_input', 'placeholder': 'Password'}) } It seemed like a simple problem but it turned out I could not get what I wanted from the official django document or Google. I'd be really appreciated if you could help me solving it. Thank you. -
Django Unit Test login
I am trying to do a Unit-Test to check that an authenticated user accesses the url /downloads on my Django site but I get the following error: django.db.utils.ProgrammingError: (1146, "1146 (42S02): Table 'test_my_db_dev.filminfo' doesn't exist", '42S02') My Unit-Test looks like this: from django.test import TestCase class TestLoginView(TestCase): def test_authenticated_user_can_see_page(self): user = User.objects.create_user("SomeUser," "some_user@mymail.net", "my_testP@ss!") self.client.force_login(user=user) response = self.client.get("/downloads") self.assertEqual(response.status_code, 200) I would appreciate any help/comments. Thanks :) -
style.css not loading in django html template
I created a login page and calling a static css sheet for styling but its not working. I load static in my login.html and use <html> <head> <title>PWC Login</title> <link rel="stylesheet" href="{% static 'css/style.css'%}"> </head> <body> <div class="loginbox"> <img src="{% static 'images/avatar.png' %}" class="avatar"> <h1 class="h1">Login Here</h1> <form> <p>Username</p> <input type="text" name="" placeholder="Enter Username"> <p>Password</p> <input type="password" name="" placeholder="Enter Password"> <input type="submit" name="" value="Login"> <a href="#">Forgot your password?</a><br> <a href="#">Don't have an account?</a> </form> </div> </body> </html> css: body { margin: 0; padding: 0; background: url('static/images/pic1.jpeg'); background-size: cover; background-position: center; font-family: sans-serif; } .loginbox{ width:320px; height:420px; background: #000; color: #fff; top:50%; left:50%; position: absolute; transform: translate(-50%,-50%); box-sizing: border-box; padding: 70px 30px; } .avatar{ width: 100px; height: 100px; border-radius: 50%; position: absolute; top: -50px; left: calc(50% - 50px); } i tried the html and css file separately and it works fine. the background is the jpeg file and the login box is centered. it has to be something in django but not sure what it is. -
How do I target a ForeignKey attribute inside a loop?
I've a cart view and when a user is authenticated and has products in the cart view, I wanna check against product availability and if one product is found with availability set to False I wanna render Out of stock, the code for not authenticated users works, but for authenticated users Traceback Error is 'OrderItem' object has no attribute 'availability' Models class Product(models.Model): availability = models.BooleanField() class OrderItem(models.Model): product = models.ForeignKey(Product) order = models.ForeignKey(Order) Views def cart(request): data = cartData(request) items = data['items'] orderitemlist = OrderItem.objects.all() if not request.user.is_authenticated: available = all(x['product']['availability'] for x in items) else: available = all(x.availability for x in orderitemlist) context = {"items": items, 'available': available} Template {% if available %} <a href="#">Checkout</a> {% else %} <p>Out of stock</p> {% endif %} -
Hi everyone, I just started learning DJango and I am stuck with Jinja
In my folder Templates I created 2 html files: main.html projects.html The structure of the main.html is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DJANGO</title> </head> <body> {% block userinfo %} {% endblock userinfo %} </body> </html> The structure of the user.html is: {% extends "main.html" %} {% block userinfo %} <h2>John Doe</h2> <p>Explorer of life.</p> {% endblock userinfo %} I don't understand why <h2>John Doe</h2> <p>Explorer of life.</p> doesn't appear in the browser when I call main.html I have tried writing in this way too {% extends "main.html" %} {% block userinfo %} <h2>John Doe</h2> <p>Explorer of life.</p> {% endblock %} without user in the endblock but it does not work. In settings.py file in Templates list and DIR list I added: os.path.join(BASE_DIR,'templates'), and I importend os too. In views.py file that I've created I have written from django.shortcuts import render from django.http import HttpResponse def main(request): return render(request,'main.html') In urls.py file that I've created I have written from django.urls import path from . import views urlpatterns = [ path('main/',views.main,name='') ] When I call the page with http://localhost:8000/main/ I don't have any error. The only problem is that the page is blank. … -
How can i Access primary key in template tag
I am trying to create an update view that allows users to update their data. I am trying to access the data by using primary keys. My problem is that i do not know the syntax to implement it. views.py def updatedetails(request, pk): detail = Detail.objects.get(id=pk) form = Details(instance=detail) if request.method == "POST": form = Details(request.POST, instance=detail) if form.is_valid(): form.save() return redirect(success) return render(request, "details.html", {"form":form}) urls.py from django.urls import path from . import views urlpatterns = [ path("details/", views.details, name="details"), path("success/", views.success, name="success"), path("edit/<str:pk>/", views.updatedetails, name="updatedetails"), ] my html template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Success</title> </head> <body> <h1>Thank You for Filling Out the Form</h1> <p><a href="/edit/{{request.detail.id}}/">Click Here To Edit</a></p> </body> </html> So what i am trying to figure out is how to call the primary key in my template -
Django - use multiple fields proprieties
class Event(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) guests = models.IntegerField() description = models.CharField(max_length=300) venue = models.BooleanField(default=False) garden = models.BooleanField(default=False) candybar = models.BooleanField(default=False) games = models.BooleanField(default=False) wine = models.BooleanField(default=False) premiumphoto = models.BooleanField(default=False) premiumvideo = models.BooleanField(default=False) limo = models.BooleanField(default=False) stuff = models.BooleanField(default=False) totalprice = models.IntegerField() This is my event model, i want the user to be able to select if they want, for example games, if they do i want the total price to be updated with the price of games wich could be 500$, how can i set games to be a bool and to have a value that can be changed by the admins. I think an interesint idea could be to have some kind of model that is default and the other models to take the price from the Price model -
DRF method GET not allowed on @action based function
I have the two models: Article and Comment. I have the ArticleAPI viewset, which have methods decorated with @action to handle requests to comments model, but when I am trying to test this endpoint via Postman I get an error: { "detail": "Method \"GET\" not allowed." } ArticleAPI.py class ArticleAPI(viewsets.ModelViewSet): serializer_class = ArticleSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] queryset = Article.objects.order_by('number') lookup_field = 'pk' ... @action(methods=['GET'], detail=True, url_path='comments', url_name='article-comments-list') def get_comments_queryset(self, request): instance = self.get_object() serializer = CommentSerializer(queryset=instance.comment_set.all(), many=True) return Response(serializer.data) @action(methods=['GET'], detail=True, url_path='comments', url_name='article-comments-object') def get_comment_object(self, request, pk=None): instance = self.get_object() serializer = CommentSerializer(queryset=instance.comment_set.get(pk=pk)) return Response(serializer.data) urls.py router = DefaultRouter() router.register('articles', articleAPI.ArticleAPI, basename='articles') -
Python Django session expire on redirect url is called
I have made an medium size website and am trying to implement payment gateway(paytm). In order to process the payment token is needed to start the payment, i could able to generate the token from the api request and the JS payment page is being invoked successfully. The main problem am encountering is after selecting the payment and start the payment pop up page appears to getting an error Session expired due to inactivity with in a seconds the page load. I tried contacting the payment gateway dev team but the could able to generated the payment successfully. However they are doing it in flask or through postman. when i try to run the code i have no problem processing the payment but when i use the same code in the Django am unable to process the payment.Even they are unable to understand the problem am getting(i.e session expired due to inactivity.) I am wondering this has to do something with the sessions and when i have stored the token in the session and call the payment page at then i do not get the error but am getting another issue is that the values are not being passed to … -
Django and DRF Why isn't my password hashing
I am using DRF and I have these pieces of code as models, register view and serializer But anytime I signup a user the password does not hashed and I can't see to figure out why. models.py class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email") email = self.normalize_email(email).lower() user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): if not password: raise ValueError("Password is required") user = self.create_user(email, password) user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) role = models.CharField(max_length=255) department = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name", "role", "department"] def __str__(self): return self.email serializers.py class RegisterSerializer(serializers.ModelSerializer): email = serializers.CharField(max_length=255) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField(max_length=255) last_name = serializers.CharField(max_length=255) role = serializers.CharField(max_length=255) department = serializers.CharField(max_length=255) class Meta: model = User fields = ["email", "password", "first_name", "last_name", "role", "department"] def create(self, validated_data): return User.objects.create(**validated_data) def validate_email(self, value): if User.objects.filter(email=value).exists(): raise serializers.ValidationError("This email already exists!") return value views.py class RegisterView(APIView): serializer_class = RegisterSerializer def post(self, request, *args): serializer … -
How to display the progress of a function in an html page Django?
I'm learning Django, tell me if it's possible to implement my idea. In the file views.py I have a script def index(request): .... for i in range(100000): print(i) return render(request, 'main/index.html', {'title': 'Website main page', 'tasks': ...}) How can I display these prints in the index.html page? If I insert the variable i into render, then the page is in the process of waiting and, as a result, shows only the last value in the iteration. I understand why this is happening. But how can I then display online in the process - what happens in the terminal, all the values in the enumeration? It seems to me that javascirpt is needed for this - I think or is it possible to display this in a simpler way? -
react + django, problem with file import, does not recognize boostrap
these problems enter image description here this is my webpack.config.js const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "../src/index.js", output: { path: path.resolve(__dirname, "../static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, { test: /\.css$/, exclude: /node_modules/, use: { loader: "babel-loader", } }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { // This has effect on the react lib size NODE_ENV: JSON.stringify("production"), }, }), ], }; my input import React from 'react'; import "bootstrap/dist/css/bootstrap.css" import { Route, Routes } from 'react-router-dom'; import Home from './pages/Home'; I've already tried installing bootstrap, both in react and in django, but it won't, I don't think it's recognizing any files that I'm importing. -
How to fix website picture problem on HTML
{% extends 'base.html' %} {% block content %} <hi>Products</hi> <div class="row"> {% for products in products %} <div class="col"> <div class="card" style="width: 70rem;"> <img src="{{ products.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ products.name }}</h5> <p class="card-text">${{ products.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} Is there a problem with this code I tried reformatting the code, by replacing the products. url into the alt brackets. But it was what i typed on in the brackets that showed up. Please help me. I'm frustrated. I'm a 13 year old beginner programmer. This is my first website which i have restarted about 19 times because of this problem. Help me -
Different user types with Django default auth
For my Django project, I have 3 different user types. I use boolean flags to know what kind of user is the actual one and have 3 models with one to one relation to the user model and the extra fields for each one: class Usuario(AbstractUser): es_centro = models.BooleanField(default=False) es_tutor = models.BooleanField(default=False) es_proveedor = models.BooleanField(default=False) class Centro(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) provincia = models.CharField(max_length=20) localidad = models.CharField(max_length=50) codigo = models.PositiveIntegerField(null=True, blank=True) cursos = models.ManyToManyField(Curso) class Tutor(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) dni = ESIdentityCardNumberField() centro = models.ForeignKey(Centro, on_delete=models.CASCADE) class Proveedor(models.Model): usuario = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) nif = ESIdentityCardNumberField() now, i want to use the default auth urls to manager the users. I have something like this: urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('centros/', include('django.contrib.auth.urls')), path('centros/registro', views.centrosregistro, name='centrosregistro'), path('tutores/', include('django.contrib.auth.urls')), #path('tutores/registro', views.tutoresregistro, name='tutoresregistro'), path('proveedores/', include('django.contrib.auth.urls')), #path('proveedores/registro', views.proveedoresregistro, name='proveedoresregistro'), ] each user type have a path where auth.urls are included. These urls look for templates in a default folder called 'registration', where there has to be a login.html, logout.html, ... My question is ¿how can I have different templates for every user type or, at least, how to know which user type is trying to login, logout, ...? So … -
Problem with logging with auth_views.loginView in Django
When I try to login via LoginView, the process seems successful. I'm redirected to LOGIN_REDIRECT_URL. urlpatterns = [ ... path('login', auth_views.LoginView.as_view(), name='login'), ] But when I try to access a view which requires login, I can't: class MyView(viewsets.ViewSet): @method_decorator(login_required(login_url='/login')) def list(self, request, server_id): .... What am I missing? Thanks by now. Here's my login form. <form method="POST" action="{% url 'login' %}"> {% csrf_token %} <div class="form-group"> <label>Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Username"> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" id="password" class="form-control" placeholder="Password"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> -
Django generated error on server log and have try to log the error but it didn’t work
I need assistant on this, i saw this error on server log: django.request.log_response:228- Bad Request: endpoint. Can anyone help with what causing this error? I try printing the request body to see maybe it request body that causes the error but it seems not to be the problem -
.env file not gitignored. I had someone do it manually for me once
So im currently working on a project and my my .env file is not greyed out (gitignore?). Trying to figure out what I need to do globally because I do have the file but my .env is never greyed out. Any suggestions? I can provide screenshots if needed. I had someone do a a few commands in the terminal and was able to get my .env to go grey once. But I believe he told me he wasn't able to do it globally. Reach out for help.