Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Railways.app postgres database is too slow
DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'engine url', 'NAME': 'railway', 'USER': 'postgres', 'PASSWORD': 'pass', 'HOST': 'host', 'PORT': 'port', } } here is the code for the connection of postgress database to my django app it is feeling too slow. I don't know my even while developing my app(local server) it takes about 2sec to just start the server after every save. and even basic urls like of admin panel took 2sec each time. My plan of railways.app is developer plan. did i did something wrong? but as I switched to mine localone app becomes faster I am expecting it to be little faster. Even when in past in works with herku its faster then this. -
I want to return Subcategory (ManyToManyField to Category---another Class) with def __str__(self):
in the last line i want to return sub category it didn't show any error but it is not show as i am expecting it is showing like NEW ITEM--**Shop.Category.None** new arrival--**Shop.Category.None** Adidas Shoes blue color--**Shop.Category.None** class Category(models.Model): CHOICES = ( ('Accessories','Accessories'), ('Fashions','Fashions') ) class IndexProduct(models.Model): Title = models.CharField(max_length=50) Subcategory = models.ManyToManyField(Category) def __str__(self): return self.Title + '--' + str(self.Subcategory) -
React Django Google Sign In
I am trying to implement google sign in my Django rest react application. This is my front-end function that gets the access token and then sends it to the backend. const gLogin = useGoogleLogin({ onSuccess: tokenResponse => { axios.post('http://127.0.0.1:8000/api/auth/google/signin/', {token: tokenResponse.access_token}) .then(response => { console.log('Successfully logged in'); }) .catch(error => { console.error('failed to login'); }) }, }); This is my backend code for verifying the access token and then getting the user details from google. @csrf_exempt def google_signin(request): if request.method == 'POST': data = json.loads(request.body) token = data.get('token') print(token) if token is None: return JsonResponse({'error': 'Token is missing.'}, status=400) try: idinfo = id_token.verify_oauth2_token( token, requests.Request(), settings.GOOGLE_CLIENT_ID ) email = idinfo['email'] print(email) user = authenticate(request, email=email) if user is not None: login(request, user) return JsonResponse({'success': True}) else: return JsonResponse({'error': 'User does not exist.'}, status=404) except ValueError: return JsonResponse({'error': 'Invalid token.'}, status=400) else: return JsonResponse({'error': 'Invalid request method.'}, status=405) This is the error in the backend. Making request: GET https://www.googleapis.com/oauth2/v1/certs Starting new HTTPS connection (1): www.googleapis.com:443 https://www.googleapis.com:443 "GET /oauth2/v1/certs HTTP/1.1" 200 1577 Bad Request: /api/auth/google/signin/ Bad Request: /api/auth/google/signin/ HTTP 400 response started for ['127.0.0. I tried reworking the code many times but no use. Still the same error -
How to make that users of a certain group in Geonode, can only edit/delete the resources they have created
I am using geonode-project and I want to to create the following permissions for geonode. I have previously created the "Institution" group. An user of the Institution Group can only Edit/Delete the resources(Datasets, Maps, Documents, etc.), he/she have created. How can I do it? I also want to create an "Managers" group that can create/edit/delete all resources -
In django, how can I have two different methods for instantiating the same model?
I am building a system to register parts for manufacturing (for context: temperature sensors). As I'm dealing with many different subtypes of actual physical parts, I'm using django-polymorphic to define the models for the actual temperature sensors: class TempSensor(PolymorphicModel): """Abstract model for temperature sensors"""" part_number = models.OneToOneField(Part, on_delete=models.CASCADE) class TempSensorA1(TempSensor): calibration = models.CharField(max_length=1, choices=Calibration.choices) junction = models.CharField(max_length=1, choices=Junction.choices) def __str__(self): return f"A1-{self.calibration}{self.junction}" class TempSensorB1(TempSensor): calibration = models.CharField(max_length=1, choices=Calibration.choices) termination = models.CharField(max_length=1, choices=Termination.choices) def __str__(self): return f"B1-{self.calibration}{self.termination}" The Part model acts as a container for the TempSensor instances. This lets me assign a simpler consecutive part number and associate them with orders. class Part(models.Model): part_number = models.AutoField(primary_key=True) order = models.ManyToManyField(Order, through="OrderDetail") production_notes = models.TextField(blank=True) sales_notes = models.TextField(blank=True) class Meta: ordering = ["part_number"] Right now, I have the django admin interface working as expected. When adding a new Part instance, I can add a TempSensor, select the correct child type and input the fields manually, all through an inline. This works great when working from raw specifications. However, since model codes are often provided directly, I also need to be able to instantiate TempSensor directly from the model code. To solve this, I've created a create_from_model_code method that takes the model code, … -
you need to register and authorize on django. How to add models and views
On the main page, I made a pop-up window with a registration form. How to attach registration to it now, I searched everything, but found only registration through a separate page. ` <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#staticBackdrop1">Log In</button> <button type="button" class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#staticBackdrop">Sign Up</a> </div> </div> </nav> <!-- Modal sign up--> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content rounded-4 shadow"> <div class="modal-header p-5 pb-4 border-bottom-0"> <!-- <h1 class="modal-title fs-5" >Modal title</h1> --> <h1 class="fw-bold mb-0 fs-2">Sign up for free</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body p-5 pt-0"> <form class="" method="POST"> {% csrf_token %} <div class="form-floating mb-3"> <input type="email" class="form-control rounded-3" id="floatingInput" placeholder="name@example.com"> <label for="floatingInput">Email address</label> </div> <div class="form-floating mb-3"> <input type="password" class="form-control rounded-3" id="floatingPassword" placeholder="Password"> <label for="floatingPassword">Password</label> </div> <button class="w-100 mb-2 btn btn-lg rounded-3 btn-primary" type="submit">Sign up</button> <small class="text-muted">By clicking Sign up, you agree to the terms of use.</small> <hr class="my-4"> <h2 class="fs-5 fw-bold mb-3">Already have an account? <a type="button" class="btn btn-link fs-5 fw-bold mb-2 " data-bs-toggle="modal" data-bs-target="#staticBackdrop1"> Log in</a></h2> </form> </div> </div> </div> </div>` -
How to set up types in graphene-django project?
After upgrading django graphql project reqirements to latest django (4.1.7) and latest graphene (3.2.2) following error is displayed: raise cls(f"{self.name} fields cannot be resolved. {error}") from error TypeError: Query fields cannot be resolved. Argument type must be a GraphQL input type. Does anyone facing such issue and has idea how to get rid of it? I tried to change argument type but it didn't help. Error is still displayed (output type instead of input but still does not work). -
Django signals and proxy models
From what I tested, if I have a model (Vehicle) and 2 proxy models (Car and Bike, proxies of Vehicle) and I want to trigger a post_save signal, the signal will be triggered only by the save operation on the Vehicle model. I was expecting the signal to be triggered by the save operation also for Car and Bike because it's the same db table. Does anyone knows where I can find an explanation for this behavior? -
Problems writing "Add to wishlist" function
So I've been stuck on the issue of now really knowing how to write an add to wishlist function. I've been battling it in my head for 10 hours as I'm unsure how to get a product to the wishlist and I'm wondering how you guys would write the whole function of it. I know that this is not a specific issue, but I'm kind of new to this and just trying to learn. Please do tell if I'm missing to hand you some information. views.py def all_products(request): """ A view to show all products, including sorting and search queries """ products = Product.objects.all() query = None categories = None sort = None direction = None if request.GET: if 'sort' in request.GET: sortkey = request.GET['sort'] sort = sortkey if sortkey == 'name': sortkey = 'lower_name' products = products.annotate(lower_name=Lower('name')) if sortkey == 'category': sortkey = 'category__name' if 'direction' in request.GET: direction = request.GET['direction'] if direction == 'desc': sortkey = f'-{sortkey}' products = products.order_by(sortkey) if 'category' in request.GET: categories = request.GET['category'].split(',') products = products.filter(category__name__in=categories) categories = Category.objects.filter(name__in=categories) if 'q' in request.GET: query = request.GET['q'] if not query: messages.error(request, "You didn't enter any search criteria!") return redirect(reverse('products')) queries = Q(name__icontains=query) | Q(description__icontains=query) products … -
Django AWS Secrets Manager password authentication failed
I have a working database connection with AWS Secrets Manager storing the username and password. Below is my implementation get_secrets_manager.py import os import json import boto3 import botocore.session from botocore.exceptions import ClientError from aws_secretsmanager_caching import SecretCache, SecretCacheConfig def get_rds_credentials(): secret_name = os.environ.get( "RDS_Secret", "rds!cluster-552a7c8b-8e0f-40e6-96f1-91a124066c58" ) region_name = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") session = boto3.session.Session() client = session.client( service_name="secretsmanager", region_name=region_name, ) cache_config = SecretCacheConfig() cache = SecretCache(config=cache_config, client=client) secret = cache.get_secret_string(secret_name) rds_credentials = json.loads(secret) os.environ['POSTGRES_USER'] = rds_credentials['username'] os.environ['POSTGRES_PASSWORD'] = rds_credentials['password'] return rds_credentials settings.py import environ from apps.utils.get_secrets_manager import get_rds_credentials get_rds_credentials() env = environ.Env() DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": env.str("POSTGRES_DB"), "USER": env.str("POSTGRES_USER"), "PASSWORD": env.str("POSTGRES_PASSWORD"), "HOST": env.str("POSTGRES_HOST", default="postgres"), "PORT": 5432, }, } It works initially but after a few days it will throw an authentication failed error. How to solve this? I am expecting either an auto-rotation mechanism or a continuous connection from my Django to DB(despite password rotation) but neither seems to be the case -
choose option in django fetching from different django application
i am new to djano and working on an Django project where I have to put categories from different application like I have two application product application - Here will manage my products and want t drop down, where I want to show the categories created in another application. 2 category application - here I am creating the category with its code please let me know how I can access the category application in product application how to save the category in database note - I am not using django form.* please let me know the steps by which I can user to complete this task. need to know about the html part also I have implemented these things in my code I model class I have create class(model:Model): choose_category={ ('g', "Jeans"), ('p', "pant"), product_category = model.charFiel(choose=chooose_category, default = 'g') error I am receiving a null value from the html -
Django "Unknown column 'userdata.password' in 'field list'" >> fix WITHOUT deleting existing table?
I have a table that is now called "userdata" in an AWS RDS mysql database. In a past migration, the table had a different name, "users". Now, with the new name, I cannot access the data in the table. I get the error >> 1054, "Unknown column 'userdata.password' in 'field list'". Other Stack Overflow posts suggest dropping the table and starting over to fix the problem. Is there a way to fix this problem without dropping the table? Here is my user model, in which I specify the table name "userdata": import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(_("email address"), unique=True) is_premium = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) plan_signup_date = models.DateTimeField(null=True, blank=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) ## default inclusions: id, password, last_login, is_superuser, groups, user_permissions USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() class Meta: db_table = "userdata" def __str__(self): return self.email Thanks. -
How to show several objects with for loop in get_context_data
I have requests_cache and i want to show parsed info from json on my page with get_context_data But it shows only first dict with values and if i place context after for loop it shows second one how to fix that? views.py def get_context_data(self, *, object_list=None, **kwargs): context = super(ShowProjectBudgetList, self).get_context_data(**kwargs) session = requests_cache.CachedSession('project_budget_cache') url = config('REPORT_PROJECT_BUDGET') response = session.get(url=url, auth=UNICA_AUTH).json() for item in response: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) obj = parsed_json.ObjectGUID context['response_json'] = obj return context -
Im getting this error while working in javascript ... Uncaught TypeError: $(...).popover is not a function
When I try to initialize popovers, I am getting the error 'Uncaught TypeError: $(...).popover is not a function.' I have included the Bootstrap 5 links and jquery link, but for some reason, it is still not working. I am unsure why this error is occurring and would appreciate any guidance on how to resolve this issue. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous"></script> **And this is my Html popover button ** <button type="button" class="btn btn-secondary" id="popcart" data-bs-container="body" data-bs-toggle="popover" data-bs-html="true" data-bs-placement="bottom"> Cart(<span id="carting">0</span>)</button> And this is how i initialize my popover //initialize popovers $("#popcart").popover(); updatePopover(bag); function updatePopover(bag) { console.log('We are inside updatePopover'); var popStr = ""; popStr = popStr + "<h5> Cart for your items in my shopping cart </h5><div class='mx-2 my-2'>"; var i = 1; for (var item in bag) { popStr = popStr + "<b>" + i + "</b>. "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 19) + "... Qty: " + bag[item] + '<br>'; i = i + 1; } popStr = popStr + "</div>" console.log(popStr); document.getElementById('popcart').setAttribute('data-bs-content', popStr); $('#popcart').popover('show'); } When I click on the + (plus) or - (minus) button to update my cart, the popover that shows all … -
Django broken pipe during authentication form post
I am trying to develop a website with Django 4, and I am puzzled by my authentication system behaviour. I am trying to develop the sign up feature, and it has not worked yet, my auth_user table is still empty. When I try signing up using Firefox, the POST request generates this error : Broken pipe from ('127.0.0.1', 52245) - when retrying, the numbers inside the parenthesis change, and I don't know the meaning of these and couldn't find it. My request seems to not be handled as the database stays empty. When I try the same thing using Edge, the database stays empty too, but the POST request generates no error. I have read that broken pipe errors were errors on the client part (the client closes the connection without waiting for the server's response), but I can't see where I need to alter things to solve that... I have also read about this happening when using ajax requests, and the way to solve it was to make the input a button type and not a submit type, but this is not an ajax request. I tried doing that because you never know, but having a button instead of … -
How to parse and show info in template with requests_cache
I have several general questions about requests_cache and how is it working and how can i use that How can i get json from 3rd party and parse that in my template? I have some information from api that i dont need to write in model in db and i want just to parse that but need just to show that in parsed info in template views.py def customer_view(request): session = requests_cache.CachedSession('project_budget_cache') session.get('http://someurl.com/api') return render(request, 'customer/customer_home.html', {'context': session}) I can get request with that but i actually dont know how to show my json in template {{ context }} cant help there Another question: How can i synch request every 5 min? Last question: How can i avoide problems with 3rd party api? Like if api is closed or they have problems and i cant get json how can i use previous request that was working? I mean if they have problems and cant accept requests rn i need to use request that was made 5 mins ago -
Change the current structure of Django rest api to a structure that has 2 parent element
i will want create a form app that which users enter their information i want change my api structure. my api structure look like this { "questions": [ { "id": 1, "answers": [ { "id": 2, "answer_title": "I study", "answer_weight": "1.0000", "created_at": "2023-03-16T11:22:48.871716Z", "updated_at": "2023-03-16T12:11:27.525798Z", "answer_type": "2A" }, { "id": 3, "answer_title": "I am working", "answer_weight": "2.0000", "created_at": "2023-03-16T11:22:48.872752Z", "updated_at": "2023-03-16T12:11:27.526798Z", "answer_type": "2A" }, { "id": 4, "answer_title": "Unemployed", "answer_weight": "1.0000", "created_at": "2023-03-16T11:22:48.873752Z", "updated_at": "2023-03-16T12:11:27.527832Z", "answer_type": "2B" } ], "question_title": "Your current occupation:" }, { "id": 2, "answers": [ { "id": 5, "answer_title": "middle", "answer_weight": "1.0000", "created_at": "2023-03-16T12:12:55.097428Z", "updated_at": "2023-03-16T12:12:55.097428Z", "answer_type": null }, { "id": 6, "answer_title": "high school", "answer_weight": "2.0000", "created_at": "2023-03-16T12:12:55.098198Z", "updated_at": "2023-03-16T12:12:55.098198Z", "answer_type": null } ], "question_title": "what is your education?" } ] } but I want to change this structure look like this [ "questions": [ { "id": 1, "answers": { "2A":[ { "id": 2, "answer_title": "I study", "answer_weight": "1.0000", "created_at": "2023-03-16T11:22:48.871716Z", "updated_at": "2023-03-16T12:11:27.525798Z", }, { "id": 3, "answer_title": "I am working", "answer_weight": "2.0000", "created_at": "2023-03-16T11:22:48.872752Z", "updated_at": "2023-03-16T12:11:27.526798Z", } ], "2B":[ { "id": 4, "answer_title": "Unemployed", "answer_weight": "1.0000", "created_at": "2023-03-16T11:22:48.873752Z", "updated_at": "2023-03-16T12:11:27.527832Z", } ] }, "question_title": "Your current occupation:" }, { "id": 2, "answers": [ { … -
The products are not deleting from the shopping cart after ordering in python-django
I am trying to make an e-commerce website. There is 1 problem which has been very hard to fix. The problem: After ordering, products are supposed to be deleted from the shopping cart. But it is not working. There are no syntaxis errors but there is still products remaining after ordering. Here is the part my views.py for it: if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) if cart is not None: del session[settings.CART_SESSION_ID] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_products = OrderProduct.objects.filter(order=order) if order_products: order_product = order_products[0] else: order_product = OrderProduct.objects.create(order=order) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') session = request.session cart = session.get(settings.CART_SESSION_ID) if cart is not None: del session[settings.CART_SESSION_ID] session.modified = True return redirect('product_list') I really hope someone can help me, please. -
How to extend authentication for a C#/.NET web app to Django project?
I have a C#/.NET web site with SAML authentication implemented on it. In a page of this web site, I put a link for another web site, made in Python-Django, and I need to implement the same authentication system. So, it's like I want to extend the same authentication to Django website (same IAM). How can I implement it for the Python-Django web site? -
How to optimize SQL in tree-like comment structure django?
I have posts with tree comments in it. Comments have likes as well. I've managed to optimize SQL queries that usual comments, related to the post itself, don't create new queries, but answers to the other comments still create 3-4 new requests to the data base. Can I somehow reduce number of queries? I've been using prefetch_related for this purpose. My Post model: class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField( max_length=200, null=True, blank=True ) header_image = models.ImageField( null=True, blank=True, upload_to="posts/headers", help_text='Post will start from this image' ) body = CharField( max_length=500 ) post_date = models.DateTimeField( auto_now_add=True ) likes = models.ManyToManyField( User, through='UserPostRel', related_name='likes', help_text='Likes connected to the post', ) def total_likes(self): return self.likes.count() Comment model class Comment(models.Model): user = models.ForeignKey(User, related_name='comment_author', on_delete=models.CASCADE) post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) body = models.TextField(max_length=255) comment_to_reply = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='replies') likes = models.ManyToManyField(User, through='CommentLikeRelation', related_name='comment_likes') created_at = models.DateTimeField(auto_now_add=True) def replies_count(self): return self.replies.count() def total_likes(self): return self.likes.count() def is_a_leaf(self): return self.replies.exists() def is_a_reply(self): return self.comment_to_reply is not None class CommentLikeRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) View that process data def get(self, request, *args, **kwargs): current_user = request.user user_profile = User.objects.get(slug=kwargs.get('slug')) is_author = True if current_user == user_profile … -
how to use values_list in Django to show one column from the table
I have three models user, usecase, and user_assign I have list of users in the database assigned to specific usecase in the user_assign table. I'm trying to show the user names not the emails assigned to specific usecase. Result I'm trying to get: SELECT user_email FROM usecase_assign WHERE usecase_id LIKE 'NN245'; my models: class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') class Usecase(models.Model): usecase_id = models.CharField(primary_key=True, max_length=20) usecase_name = models.CharField(max_length=256) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_type = models.ForeignKey('UsecaseType', models.DO_NOTHING) kpi = models.ForeignKey(Kpi, models.DO_NOTHING) class User(models.Model): user_email = models.CharField(primary_key=True, max_length=100) user_role_id = models.CharField(max_length=20) user_password = models.CharField(max_length=20) user_name = models.CharField(max_length=100) my views.py: @user_login_required def view_usecase_details(request,ucid): usecase_details = Usecase.objects.filter(usecase_id=ucid).all() if request.method == "GET": usecase_assigned = UsecaseAssign.objects.values_list('user_email').filter(usecase_id=ucid).values() context = {'usecase_details': usecase_details, "users": User.objects.all(), 'usecase_assigned':usecase_assigned} return render(request, 'UsecaseDetails.html', context) my template: <div class="card card-body shadow-sm mb-4 mb-lg-0"> <form action="/usecase-details/{{usecase_details.usecase_id}}" method="POST"> {% csrf_token %} <div class="form-row mb-4"> <div class="col-lg-8 mr-f"> <label class="h6" for="user_email">Assign Users:</label> <select name="user" class="custom-select my-1 mr-sm-2" id="user"> <option value="0" selected>Select</option> {% for user in users %} <option value="{{ user.user_email }}">{{ user.user_name }}</option> {% endfor %} </select> </div> </div> <input type="submit" class="btn btn-primary" value="Submit Changes"> </form> <ul class="list-group list-group-flush"> <li class="list-group-item d-flex align-items-center justify-content-between px-0 border-bottom"> <div> <p … -
Restrict access to multiple admin sites per user/group in Django
When using multiple admin sites in Django i want to seperate the depth / complexity of information availabe in different sites. The generally works but a user can still login to the other sites and see more than he is supposed to because he has view permission to a model. Imanine having morve levels between staff and superuser like "is_staff_trainee", "is_staff_junior", "is_staff_senior" and "is_staff_bigboss". They all have their own admin sites. On some models the admin is the same for all of them, so i register the same ModelAdmin to all of the sites. But on some model, let's say "Drinks", they all get their own DrinkAdminTrainee, DrinkAdminJunior, DrinkAdminBigBoss, you get it. A Trainee has most of the fields read only, a Junior can edit most of them on the edit page, a senior gets additional information about e.g. the price calculation an can choose from more expensive ingredients to create his drinks and the Big Boss can also see all the old (long deactivated) Drinks from the Past. That works perfectly. But any Trainee can still login to the Big Boss Admin site if he kows the URL and also use it because he still "is_staff" and has view … -
Lock editing page in django
i have a single page application and a django server with the django rest framework. As an example, I have a resource called House. User 1 is on the /houses/5/edit page and is currently editing the house with ID 5. Now I want to block editing from the house with ID 5 for other users. Only one user should be able to access the editing page of a particular house at a time. All other users should see on the detail page of the house with ID 5 (/houses/5/) that the house is already being edited. Only when user 1 leaves the page /houses/5/edit, another user should be able to edit the house. I want to have this blocking mechanism because otherwise changes to the house could be overwritten by another user. So the mechanism should be similar to the blocking mechanism in Wordpress CMS for blocking a page or post. How can I implement this? I already use django-channels for push notifications. My idea was to use websockets for blocking. Also, I saw that django-redis offers a blocking mechanism. However, I still have no idea how to implement my requirements with it and whether these technologies are the best … -
Understanding and setting the order of Django migrations
I have models that look like: class FubarCategory(models.Model): class name = models.CharField(max_length=32) class FubarScenarioType(models.Model): class name = models.CharField(max_length=32) class FubarProduct(models.Model) category = models.ForeignKey( FubarCategory, on_delete=models.DO_NOTHING, related_name="products" ) scenario = models.ForeignKey( FubarScenarioType, on_delete=models.DO_NOTHING, related_name="products" ) class FubarTransaction(models.Model): product = models.ForeignKey( FubarProduct, on_delete=models.DO_NOTHING, related_name="transactions" ) I expect a brand new migration to look like: Migrations for 'fubar': apps/fubar/migrations/0001_initial.py - Create model FubarCategory - Create model FubarScenarioType - Create model FubarProduct - Create model FubarTransaction Instead, I see this: Migrations for 'fubar': apps/fubar/migrations/0001_initial.py - Create model FubarCategory - Create model FubarProduct - Create model FubarScenarioType - Add field scenario_type to Fubarproduct - Create model FubarTransaction Why is FubarScenarioType being created after FubarProduct instead of before? -
How to authenticate selenium before running `pytest`?
I'm using pytest-django with selenium for testing features. Some features require being logged in. Here's how I create a test user: import sqlite3 import uuid import pytest from django.conf import settings from django.contrib.auth.models import User from django.core.management import call_command from selenium.webdriver import Chrome, ChromeOptions @pytest.fixture(scope='session', autouse=True) def browser(): options = ChromeOptions() options.add_argument('--no-sandbox') options.add_argument('headless') chrome = Chrome(options=options) yield chrome chrome.close() @pytest.fixture(scope='session') def test_user(): return {'username': uuid.uuid4().hex[:10], 'password': uuid.uuid4().hex} @pytest.fixture(scope='session') def django_db_setup(django_db_blocker, test_user): db_path = settings.BASE_DIR / 'test-db.sqlite3' sqlite3.connect(db_name := db_path.as_posix()) settings.DATABASES['default']['NAME'] = db_name with django_db_blocker.unblock(): call_command('migrate', '--noinput') User.objects.create_user( username=test_user['username'], password=test_user['password'], email=f'{test_user["username"]}@test', ) Now that a test user is created, I need to use it with selenium before tests that require logging in. A typical test class looks like: class TestSomeUrl: def test_feature1(browser): ... def test_feature2(browser): ... But I need to login first. What would be the proper way to do so? I tried first to login inside the browser fixture by doing: @pytest.fixture(scope='session', autouse=True) def browser(live_server, test_user): options = ChromeOptions() options.add_argument('--no-sandbox') options.add_argument('headless') chrome = Chrome(options=options) chrome.get(f'{live_server}/login') browser_login(chrome, test_user) yield chrome chrome.close() But I get a Bad Request (400) because live_server seemingly has no started yet, otherwise it should get f'{live_server}/login' without issues. Answers here are outdated and do not work anymore. …