Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apply an update to a queryset involving a foreign key
Lets say I have something like the code below, where I can nicely apply the update method to change the engine type of the cars contained in the query set vintage_cars. Is it possible to use update in a similar fashion for the code using the for loop, where a foreign key is involved? class Driver(Model): name = CharField() licence = CharField() class Car(Model): driver = models.ForeignKey(Owner) status = CharField() type = CharField() engine = CharField() vintage_cars = Car.objects.filter(type="vintage") vintage_cars.update(engine="gas") for c in vintage_cars: driver = c.driver if driver and driver.licence not in VALID_LICENCES: c.driver = None c.status = "IMPOUNDED" d.save() I'm thinking I need to apply a second filter involving this clause: if driver and driver.licence not in VALID_LICENCES: to vintage_cars, but I'm not sure if that makes sense in terms of efficiency. -
I can access Django server directly despite nginx reverse proxy
I have a Django Rest Framework server running with Gunicorn with this command : gunicorn --bind 0.0.0.0 --forwarded-allow-ips="*" partyapp.wsgi:application --access-logfile - --error-logfile - --log-level debug I have Nginx as a reverse proxy with the following configuration: server { listen 80; server_name 162.19.70.85; location /static/ { root /var/www; } location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://localhost:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } It is working well: I can access the service with http://{IP} but also with http://{IP}:8000 which hits Django server directly. I don't think it is a good behavior and I want people to be "forced" to go through the reverse proxy. How can I do that ? Thanks. -
Uneven and unfair fight against JavaScript
Hey i need a help in JS organization. I working on project in Django and now i have moment that i can't jump at all. I have a site where the form of inputs is on many sites one after another. For now i have some JS written in witch i can move on sites but the real problem IS: I need to take data ('Categories') from checkbox in first step and this decide what data will show on step three where should show up only Institutions which have the same categories. Then in step 4 i user give the adress etc. and in step 5 (Summary) data from steps before should shown on screen. In step 5 is a button confirm to send data back to Django Please help my mental health Models from django.db import models from django.contrib.auth.models import User FUNDATION_TYPE = ( (1, 'Fundacja'), (2, 'Organizacja pozarządowa'), (3, 'Zbiórka lokalna'), ) class Category(models.Model): name = models.CharField(max_length=64) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Institution(models.Model): name = models.CharField(max_length=128) description = models.CharField(max_length=256) type = models.IntegerField(choices=FUNDATION_TYPE, default=1) categories = models.ManyToManyField(Category) class Meta: verbose_name_plural = "Institutions" def __str__(self): return self.name class Donation(models.Model): quantity = models.IntegerField() categories = models.ManyToManyField(Category) … -
Django HTML Select not loading correct option
Im having some trouble at my first Django project. I have a ListView in which I have several comboboxes (select) to filter data in a table. Im using Foundation for my site The problem I´m having is that once I establish the "filters" for the queary in my comboboxes, data is presenting fine, but after loading the table, one of the selects is not loading the correct option(last lookup) This is my ListView code: class ListSales(LoginRequiredMixin, ListView): template_name = "sales/list.html" context_object_name = 'sales' login_url = reverse_lazy('users_app:user-login') paginate_by = 5 def get_queryset(self): client = self.request.GET.get("clientselect", "") payment_method = self.request.GET.get("paymentselect", "") date1 = self.request.GET.get("date1", '') date2 = self.request.GET.get("date2", '') product = self.request.GET.get("productselect", '') if date1 == '': date1 = datetime.date.today() if date2 == '': date2 = datetime.date.today() queryset = Sale.objects.get_sales_list( date1, date2, client, payment_method) qty_total_product = 0 if product != '0' and product != '': print(Product.objects.get(id=product).full_name) print(queryset) for querysale in queryset: print(querysale) for query_sale_detail in querysale.sale_details(): print(query_sale_detail.product.full_name + " " + str(query_sale_detail.count)) if str(query_sale_detail.product.id) == product: qty_total_product += query_sale_detail.count print(qty_total_product) obj_sales_list_filter, created_obj_sales_list_filter = SalesListFilters.objects.get_or_create( id=1, defaults={ 'datefrom': date1, 'dateTo': date2, 'client': Client.objects.search_id(client), 'payment_method': PaymentMethod.objects.search_id(payment_method) }) if not created_obj_sales_list_filter: obj_sales_list_filter.datefrom = date1 obj_sales_list_filter.dateTo = date2 obj_sales_list_filter.client = Client.objects.search_id(client) obj_sales_list_filter.payment_method = PaymentMethod.objects.search_id( payment_method) obj_sales_list_filter.save() … -
Using a DRF JSONField as a Serializer
I have a custom JSONField which I would like to use as a serializer. Serializers provide a bunch of extra functionality that you don't get with a Field. Serializers are Fields but not the other way around. As an example, consider a field which has some complex dynamic data and needs to be validated manually: from rest_framework.serializers import JSONField, Serializer class MetadataField(JSONField): def to_internal_value(self, raw_data): data = super().to_internal_value(raw_data) # lengthy validation logic which is calling other methods on the class return data class ItemSerializer(Serializer): metadata = MetadataField() To keep this field reusable and to prevent bloating the ItemSerializer class we move the logic out into its own MetadataField. However, as a consequence, we no longer have access to things like self.instance, nor can we directly instantiate this class like a serializer and pass it some data. Generating a dynamic schema is not an option, and I would like if at all possible to keep the validation logic out of ItemSerializer. -
Universal method to merge duplicate objects in Django
I want to write a universal class to merge duplicate entries in django reassigning all many-to-one and many-to-many references from old to new object. Something like this: def form_valid(self, form): new_object = self.model.objects.get(id=form.cleaned_data['inst'].id) old_object = self.model.objects.get(id=self.kwargs['pk']) for obj in old_object.machine_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.contact_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.partquote_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.trip_set.all(): obj.company = new_object obj.save(update_fields=['company']) for obj in old_object.address.all(): new_object.address.add(obj) for obj in old_object.email.all(): new_object.email.add(obj) for obj in old_object.phone_number.all(): new_object.phone_number.add(obj) if not new_object.website and old_object.website: new_object.website = old_object.website new_object.save(update_fields=['website']) if not new_object.comments and old_object.comments: new_object.comments = old_object.comments new_object.save(update_fields=['comments']) return redirect(new_object.get_absolute_url()) But I don't want to hard-code it manually for all related fields. Instead I want to do something like this: def form_valid(self, form): new_object = self.model.objects.get(id=form.cleaned_data['inst'].id) old_object = self.model.objects.get(id=self.kwargs['pk']) for related_object in self.model._meta.related_objects: for obj in related_object.SOMEHOW_GET_QUERYSET(): // Assuming the field we are looking for is lower case model name SOMEHOW_GET_FIELD_FROM_SELF_MODEL = new_object obj.save(update_fields=['SOMEHOW_GET_FIELD_FROM_SELF_MODEL']) for related_object in self.model._meta.many_to_many: for obj in related_object.SOMEHOW_GET_QUERYSET(): new_object.SOMEHOW_GET_FIELD_FROM_RELATED_OBJECT.add(obj) Is it posssible to do something like that? -
How to create multiple models from a single endpoint w/ Django
I want to have an single endpoint that accepts a POST request and creates an "Order" that can be one of two types. The User should be able to submit an order (of either type) as JSON, and create a new Order. Behind the scenes, two models are created. One "Base Order" Model that describes some common characteristics, and one "Type A Order" or "Type B Order" that describes the characteristics specific to that order. The actual order types and their fields will be vastly more complicated so here are just described as A and B with a few charFields. The general idea though is that the same endpoint is used to create two models, a BaseOrder model, and a model of a type determined by the order_type field submitted. I think the conditional part of this (which order to make) should not be too difficult. But I'm unsure how to create two separate models from the same endpoint, even if it was always of the same type. Models: class BaseOrder(models.Model): name = models.CharField(max_length=80) timestamp = models.DateTimeField(null=False) class OrderType(models.TextChoices): TYPEA = "A", "Placeholder A" TYPEB = "B", "Placeholder B" order_type = models.CharField( max_length=16, verbose_name="Order Type", choices=OrderType.choices, ) class TypeAOrder(models.Model): a_field1 … -
How do I fix Django returning 'self' not defined NameError on queryset filtering of ModelChoiceField?
I have 2 models, Type and Measure. Each Measure object has a typeid ForeignKey field that refers to the id field of a Type object. Each Type is viewed on it's own page where the id is passed through URL. urls.py urlpatterns = [ path('type/<int:id>', views.type, name='type'), ] The view had been working with this as it is before I added the ModelChoiceField to the form. views.py def type(request, id): mytypes = Type.objects.all().values() mytype = Type.objects.get(id=id) mymeasures = Measure.objects.filter(typeid=id) template = loader.get_template('type.html') if request.method == 'GET': form = ConvForm(request.GET) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: if request.from_type != None: redir = f"/type/{id}" # create a form instance and populate it with data from the request: return HttpResponseRedirect(redir) # if a GET (or any other method) we'll create a blank form else: form = ConvForm(id) context = { 'form' : form, 'mytype': mytype, 'mytypes' : mytypes, 'mymeasures' : mymeasures } return HttpResponse(template.render(context, request)) It is once it imports the form that it runs into a problem with the following code. forms.py class ConvForm(forms.Form): from_value = forms.DecimalField(label='From Value', max_digits=256, decimal_places=255) from_measure = forms.ModelChoiceField(queryset=Measure.objects.none()) class __init__(self, … -
Django admin panel: select a group in many to many list
I have 3 models as follows: class ColorGroup(models.Model): name = models.CharField(max_length=255) class Color(models.Model): color_group = models.ForeignKey(ColorGroup) name = models.CharField(max_length=255) class Item(models.Model): colors = models.ManyToManyField(Color) For my project, I need to add/remove colors in the admin panel for my items. Currently I have to add them one by one. But in many occasion I want to set all the colors from a ColorGroup at once (and maybe select other colors also). Example: I want my item to be orange, yellow and all colors of group blue (including teal, navy blue etc.) Is there a way to display both colors and group of colors in the ManyToMany list, and if I select a Group it auto select all the colors of this group ? I checked this question but the smart_select doesn't seems to allow both color and group color selection. Edit: The solution I have in mind for now is to add a field 'color group' in item and let user select the group on another list. Then handle logic in the back end. But I would like to avoid adding complexity and redundancy to the DB -
Need to write some tests for OrderDetailView
Need to write test_order_details method to verify receipt of the order: 1)make sure that the order address is in the response body; 2)make sure that there is a promo code in the response body; 3)make sure that the response context is the same order that was created before the test (compare by primary key). This is model: class Order(models.Model): delivery_address = models.TextField(null=True, blank=True) promocode = models.CharField(max_length=20, null=False, blank=True) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.PROTECT) products = models.ManyToManyField(Product, related_name="orders") This is view: class OrderDetailView(DetailView): queryset = ( Order.objects .select_related("user") .prefetch_related("products") ) This is tests.py: from django.contrib.auth.models import User, Permission from django.test import TestCase from django.urls import reverse from .models import Order class OrderDetailViewTestCase(TestCase): @classmethod def setUpClass(cls): cls.user = User.objects.create(username='test', password='qwerty') permission_order = Permission.objects.get(codename='view_order') cls.user.user_permissions.add(permission_order) @classmethod def tearDownClass(cls): cls.user.delete() def setUp(self) -> None: self.client.force_login(self.user) self.order = Order.objects.create( delivery_address='ul Verona, d 13', promocode='SALE_123', user=self.user) def tearDown(self) -> None: self.order.delete() def test_order_details(self): response = self.client.get(reverse( 'shopapp:order_details', kwargs={'pk': self.order.pk}) ) self.assertContains(response, self.order.delivery_address) self.assertContains(response, self.order.promocode) I don't know how to make sure that the response context is the same order that was created before the test (compare by primary key). Can you help me please? -
Redmine returned internal error, check Redmine logs for details (Only from Webserver)
I build a Webinterface for Redmine for a better looking experience. Everything works just fine on the virtual development server from django. But when the application runs on my Webserver (IIS) the Python Redmine API seems to have a problem to establish a connection to Redmine. Redmine is installed on the same Server with the help of the Bitnami Redmine Stack. server = Redmine('http://10.0.121.245:81/redmine/', username='user', password="password") server.issue.create( ..... ) This code for the Python Redmine API works just fine on my virtual Server when building the Application, but when published on the Webserver the connection seems to be failing. The Redmine Logs do not show this error. For me it seems to be a problem with the url. Also tried with localhost, but still the same problem. Any idea why this is happening ? -
How to make a default value in ForeignKey using User
I was going through "Django for Beginners", there is a project that make posts with title, author and body fields, u can add posts via admin where in author field u choose either -- or the admin itself, what I'd like to do is if this field is not edited then then its value would be a string that i can pass (i. e. in that case 'anon') . I've found a way to make a default for ForeignKey but without models.User so how to do it in that case? from django.db import models from django.urls import reverse def anon(): return 'User.username="Anon"' class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( "auth.User", on_delete=models.CASCADE, default=anon ) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) Firstly I've tried to plainly type in author = models.ForeignKey("auth.User", on_delete=models.CASCADE, default='anon'). Then to make a function that would return the desired string, then looked up models.User fields and found username field, tried to return it in anon() but only got SyntaxError: expression cannot contain assignment, perhaps you meant "=="? when entered makemigrations command -
How to merge two JSONField fields
Postgres allows merging/concatenating two JSONB fields into one. Quoting the relevant Postgres docs: jsonb || jsonb → jsonb - Concatenates two jsonb values. As far as I can see, the Django ORM does not provide an operator for this type of concatenation. django.db.models.expressions.Combinable does not have a || operator. django.contrib.postgres.search.SearchQueryCombinable has a || operator, but this class does not seem to apply here. -
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.