Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Google log-in/sign up not working even though django-oauth
Following this guide to add google sign-in/sign-up to my django app. Added all the code and it all seemed to be working until the very end when I got this error. Error 400: redirect_uri_mismatch The redirect URI in the request, http://127.0.0.1:8000/accounts/google/login/callback/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/.... However, i visit my credential screen I do see the url correctly reported. What am i doing wrong? -
Gunicorn does not handles connections on Elastic Beanstalk AL2
My gunicorn does not accepts connexion. I'm currently launching gunicorn manually to test why it fails to accept connexion. $ gunicorn --bind :8080 --workers 1 config.wsgi:application --log-level=debug [2021-07-23 16:48:20 +0000] [7943] [INFO] Starting gunicorn 20.1.0 [2021-07-23 16:48:20 +0000] [7943] [DEBUG] Arbiter booted [2021-07-23 16:48:20 +0000] [7943] [INFO] Listening at: http://0.0.0.0:8080 (7943) [2021-07-23 16:48:20 +0000] [7943] [INFO] Using worker: sync [2021-07-23 16:48:20 +0000] [7946] [INFO] Booting worker with pid: 7946 [2021-07-23 16:48:20 +0000] [7943] [DEBUG] 1 workers bash: /opt/python/current/env: No such file or directory This /opt/python/current/env stuff seems to come from old AL1 config but I don't know where it come from. Gunicorn continue to work but without accepting connexions. Here is the output from curl: * Empty reply from server * Connection #0 to host test.skippair.com left intact curl: (52) Empty reply from server * Closing connection 0 -
Database considerations when writing a Django app for personal use only in a local server
I am a Django developer for a startup. The project is about to finish and I will start looking for a new job soon. I would like to use my skills do write a simple app to keep my job search organised and I would like to keep my database running on my localhost. I don't want to spend money and effort hosting the website online as I can simply run it with a local database. The problem is that as I develop my apps I usually nuke my database when some migration didn't go as planned or sometimes when PostgreSQL acts out (as in updates). So I would like to know what are the best options for developing and app with a development database while I have an actual database with valuable data that I don't want to lose. If anybody ever faced this problem I would like to know possible solutions. Thanks! -
Why static files are served locally and not from AWS s3 in my Django project?
I have Django application and I want to serve static and media files from AWS s3 bucket but after configuration only media files are served from s3 and static files are served locally. When I collect static all static files are collected in local staticfiles folder. No files are send to AWS s3 bucket. I had to copy them manually to s3. I use Django==2.1.4, boto3==1.18.3, django-storages==1.11.1 Below I show the configuration in settings.py (some irrelevant parts are removed and I comment STATIC_URL and MEDIA_URL values that I have tried) I tried for example what was advised in this topic Django and S3 Bucket AWS Admin Static files. import os from decouple import config import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['yogahouse-ap.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'yogahouse.urls' IMAGEKIT_URL = config('IMAGEKIT_URL') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = 'eu-central-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_STATIC_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'yogahouse.storages.MediaStorage' AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com" AWS_IS_GZIPPED = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL … -
How to keep a message within a string instead of showing it on CMD ? python
What does the channel.basic_consume' function return? how i can access to message using variable i want consumed message and show it in browser? i build django application send message to rabbitmq and consume messsage from it to show message in browser like chat import pika, sys global message def consume(room,username): credentials = pika.PlainCredentials('admin', 'admin') parameters = pika.ConnectionParameters('192.168.1.14',5672,'/', credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.exchange_declare(exchange='topic_exchange', exchange_type='topic') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue arr= [room,username] binding_key ='.'.join([str(i) for i in arr]) channel.queue_bind(exchange='topic_exchange', queue=queue_name, routing_key=binding_key) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body)) channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True) global message #message = channel.start_consuming() return message -
Djngo Signals How to find duplicate in queryset and appoint theme for sender and receiver?
I am using django post_save signals in my BlogComment model and creating duplicate of each object. I want to appoint first duplicate for my sender and second duplicate for my receiver. How to do that in queryset? This queryset for my sender: notifications = Notifications.objects.all().filter(sender=user).order_by('-date') This queryset for my reciver: notifications = Notifications.objects.all().filter(receiver=user).order_by('-date') here is my BlogComment model which creating Notifications objects: class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) #my others fileds #here signals stating def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user commnet_notes = comment.rejected_comment_notes comment_text = comment.comment if sender != blog.author and comment.is_published == "pending": notify = Notifications(blog=blog, sender=sender, receiver=comment.blog.author,text_preview=comment_text[:250], notification_type="New Comment") notify.save() #want appoint this object for receiver in queryset notify2 =Notifications.objects.create(blog=blog, sender=sender, receiver=comment.blog.author, text_preview=comment_text[:250], notification_type="New Comment") notify2.save() #want appoint this object for sender in queryset post_save.connect(BlogComment.user_comment, sender=BlogComment) here my notifications model: class Notifications(models.Model): blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE,blank=True,null=True) blogcomment = models.ForeignKey('blog.BlogComment',on_delete=models.CASCADE, blank=True,null=True) globalnotifications = models.ForeignKey('blog.GlobalNotifications',on_delete=models.CASCADE,blank=True,null=True) NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved'), ('Comment Rejected','Comment Rejected'),('pending post','pending post'),('post approved','post approved'),('post rejected','post rejected'),('global_noti','global_noti')) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250,default="New Comment") text_preview = models.CharField(max_length=500, blank=True) help_notes = models.TextField(max_length=1000,default="",blank=True,null=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) is_seen_author_noti = models.BooleanField(default=False) def __str__(self): return … -
Django Admin Selection by Related Tables
I have models named School, Class and Student List. When adding to the student list, there is a class selection. I want to filter these classes by choosing school name and only show classes belonging to that school. How can I do that? When I add on the admin page, only the class selection field comes up. My admin.py file is default for now. How can I filter during this insertion process? Example scenario -> When the add page opens School: "Empty" Class: "Empty because no school has been selected yet" Child: "List of children" -> When a school selected School: "Example School" Class: "Class list of selected school" Child: "List of children" School Model class School(AbstractSchoolBaseModel): city = models.ForeignKey( "country.City", on_delete=models.DO_NOTHING, related_name="city_schools", verbose_name=SchoolStrings.SchoolStrings.city_verbose_name) name = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.name_verbose_name) address = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.address_verbose_name) website = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.website_verbose_name) Class Model class Class(AbstractSchoolBaseModel): school = models.ForeignKey( "school.School", on_delete=models.CASCADE, related_name="classes_school", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( "account.InstructorProfile", on_delete=models.CASCADE, related_name="instructors_school", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) Student List Model class StudentList(AbstractSchoolBaseModel): school_class = models.ForeignKey( "school.Class", on_delete=models.CASCADE, related_name="student_list_class", verbose_name=SchoolStrings.StudentListStrings.school_class_verbose_name ) child = models.ForeignKey( "account.ChildProfile", on_delete=models.CASCADE, related_name="children_class", verbose_name=SchoolStrings.StudentListStrings.child_verbose_name) -
Django couldn't display context in template when the conetxt contain path
Usually I can display any variable present in my context, it works. But here when i want to display in template a variable context containing a path it does not work. My path is in the context variable because i can print him in my console. I only encounter this problem with context variables with a path view.py def step0(request): context = {} if request.method == 'POST': context['GV.Levels_m0'] = GV.Levels_m[0] print(context['GV.Levels_m0']) else : None return render(request,"template.html",context) template: {% if export_process_done %} <div class="alert alert-success"><b>Done</b>.The files are exported to {{ GV.Levels16 }} </div> {% endif %} my console : C:\Users\exex\Documents\name\WebApp\Application\media\projectname\process rendering -
how to add a none existing language to django
i tried to add a my language (kurdish - (arabic character)) which is not in the list of languages in django ,i've read several questions and answers but still i get the same error ?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting. i add ku folder extension into my /django/conf/locale/ but not worked , i also add this into my settings.py ..... from django.conf import global_settings gettext_noop = lambda s: s LANGUAGES = ( ('ku', gettext_noop('Kurdish')), ) EXTRA_LANG_INFO = { 'ku': { 'bidi': True, # right-to-left 'code': 'ku', 'name': 'Kurdish', 'name_local': u'\u0626\u06C7\u064A\u063A\u06C7\u0631 \u062A\u0649\u0644\u0649', }, } import django.conf.locale LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI + ["ku"] -
Django images from s3 bucket result in NoSuchBucket error
All of my images were working, then after editing settings.py (not touching AWS variables), the images no longer show and I get this error. <Error> <Code>NoSuchBucket</Code> <Message>The specified bucket does not exist</Message> <BucketName>gym-workout-files</BucketName> <RequestId>ME2V5DFD368RT8XX</RequestId> <HostId>9VG9pz5/SJ9VryDCkA4FPU5KnTIcqDDT1NG2Blbc2j36A+IwYJcp6zIOR8Z0qUrn0lZcf5qHdRQ=</HostId> </Error> This is how I access the AWS bucket from settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I can clearly check that the bucket name DOES match, and is in all lower-case. I've also tried updating the region directly in settings.py, but that had no effect. Block public access with my bucket is set to OFF, so I'm very confused why the images cannot be accessed. When I try to click on a link from one of my images on AWS, like this one https://gym-workouts-files.s3.amazonaws.com/workout_pics/greatest.jpg, I get an error of AccessDenied. -
How to run cronjobs with dynamic timing
We have course creation platform, in that admin can assign a course to learner in future. So, on the particular time i need to trigger an mail and notification function. Django celery-beat, we can run cron periodically. But i don't want run periodically, i need to run the function based on admin specified time like Netbanking future payments. -
How to wrap every request in additional json object?
I want to separate json object by data and links for easy use. I searched through web but I am unable to find any tutorials or guidance. My current request is this: { 'fieldname': '<data>', 'another_fieldname': '<data>', 'field_with_relation': { 'child_field': '<data>', 'a_child_field': '<data>', }, 'link': '<data>', 'page' : '<data>' } I want this type of JSON Structure: { 'data':{ 'fieldname': '<data>', 'another_fieldname': '<data>', 'field_with_relation': { 'child_field': '<data>', 'a_child_field': '<data>', } }, 'links':{ 'link': '<data>', 'page': '<data>' } } I specifically asking for request it doesn't matter if it is a post, get, update or delete request. I want all my data to follow this specific structure. -
Django - best way to manage existing, auto increment fields with existing data?
This is still in dev, so I am relatively flexible in how to approach this. So I'm importing data (via fixtures, the import works fine) from an existing database into a django application. The source data is not uniformed in how it manages ID & primary keys. Some tables use what seems to be an auto-increment (similar to what django would produce by default). Others use some sort of integers. The relationships in the data dump are established based on those fields. Seems I can keep on using auto-increments in all cases. They are conveniently not named uniformly: id, pk, pk_sometablename, etc. The fixtures I use to import look like this (I generated them using a script based on the datadump, so this can be changed if needs be): { "model": "admin_account.client", "pk": "168", "fields": { "pk_client": "168", My django model: class Client(models.Model): pk_client = models.IntegerField(verbose_name='Pk_client', blank=True, null=True) I need to be able to import the data in such a way that this field, the pk_client field is used as the primary key (it can still remain as an auto-increment). So I tried to change to this: class Client(models.Model): pk_client = models.AutoField(primary_key=True, verbose_name="pk_client", default=-9999) However if I try this migration … -
How to annotate a QuerySet adding row numbers groupped by a field?
I have two models: Model books [id, title, author_id] Model authors [id, name] I need to query books ordered by author name and title: result = Books.order_by('author__name', 'title').value_list('author__name', 'title') But I also need to add a counter to each row which will reset with each new author. The results of the query should be: title name position ----------------------------------------- book1 Dan Brown 1 book2 Douglas Adams 1 book3 Douglas Adams 2 book4 Douglas Adams 3 book5 Douglas Adams 4 book6 Ernest Hemingway 1 book7 Ernest Hemingway 2 book8 Ernest Hemingway 3 book9 John Steinbeck 1 book10 John Steinbeck 2 Is it possible to implement this position field with Django ORM? -
How to POST multiple data in DRF and React with Axios
I have 2 models named Recipe and Step.. I have serialized both to make an API for GET request.. I want to know is there a way to create for POST request so that I can send both the data (steps and recipe) in the same request? models.py: from django.db import models class Recipe(models.Model): title = models.CharField( max_length=50) uuid = models.CharField( max_length=100) def __str__(self): return f'{self.uuid}' class Step(models.Model): step = models.CharField(max_length=300) uuid = models.ForeignKey(Recipe, on_delete=models.CASCADE) def __str__(self): return f'{self.step} - {self.uuid}' serializers.py: from rest_framework import serializers from .models import * class RecipeSerializer(serializers.ModelSerializer): class Meta: model = Recipe fields = ['title', 'uuid'] class StepSerializer(serializers.ModelSerializer): class Meta: model = Step fields = ['step', 'uuid'] views.py: from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import * from .models import * @api_view(['GET']) def apiOverview(request): api_urls = { 'List':'/recipe-list/', 'Detail View':'/recipe-detail/<str:pk>/', 'Create':'/recipe-create/', 'Update':'/recipe-update/<str:pk>/', 'Delete':'/recipe-delete/<str:pk>/', 'Steps' : '/steps/<str:pk>' } return Response(api_urls) @api_view(['GET']) def recipeList(request): recipes = Recipe.objects.all() serializer = RecipeSerializer(recipes, many=True) return Response(serializer.data) @api_view(['GET']) def recipeDetail(request, pk): recipe = Recipe.objects.get(uuid=pk) recipe_serializer = RecipeSerializer(recipe, many=False) steps = Step.objects.filter(uuid=pk) steps_serializer = StepSerializer(steps, many=True) return Response({ 'recipe' : recipe_serializer.data, 'steps' : steps_serializer.data }) How can I create a view for POST and handle … -
How can i compare two strings in a template of django?
I am new to Django and i am trying to make a blog website where user first login to create their post. They can update their existing post later. but the problem is other logged in user can also interfere with the post of this user. so i was trying this logic, {% if post.author == user.username %} in my post_detail.html file. i.e. if person who has just logged (user.username) in is the same person who has written this post (post.author) then he is allowed to edit or remove this post. if not then option of edit & remove won't be visible to them on browser. Plz tell me if anything wrong in this if statement as its not working! below are my models.py and other files. #models.py from django.db import models from django.contrib.auth.models import User from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.conf import settings from django.utils import timezone # Create your models here. class user_entry(models.Model): # models.Model means that the Post is a Django Model, so Django knows that it should be saved in the database. user = models.OneToOneField(User, on_delete=models.CASCADE) # name = models.CharField(max_length=30) # email = models.EmailField(max_length=254,unique=True) # … -
How to save form data from base.html in django?
In my app, I have created a context_proccessors.py to show the form to base.html file. I am able to show the form in the base.html file. But the problem I am facing is I have no idea how to save that form data from base.html since there is no view for the base.html. Below is my code: models.py class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_posts') post_pic = models.ImageField(upload_to='post_pic', verbose_name="Image") post_caption = models.TextField(max_length=264, verbose_name="Caption") created_date = models.DateTimeField(auto_now_add=True) edited_date = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user.username}" forms.py from django import forms from post_app.models import Posts class PostForm(forms.ModelForm): class Meta: model = Posts exclude = ('user',) context_proccessors.py from post_app.forms import PostForm def post_form(request): form = PostForm return { 'post_form': form, } I want the form to be displayed on every page so that the user can submit data from anywhere -
Trying to use a Model method in a Django View
So I'm working on this project (an Inventory app). I have this model method I am trying to use in my View. I'm trying to call it in my view. But I'm always getting an error: 'TransactionView' object has no attribute 'deduct_quanity' Here is my model: class Product(models.Model): business = models.ForeignKey(Business_Account, on_delete=models.CASCADE) product_name = models.CharField(max_length=50) price = models.DecimalField(max_digits=50, decimal_places=2) image = models.ImageField(upload_to=None) current_product_stock_available = models.IntegerField() def __str__(self): return f'{self.product_name} ({self.business})' def can_reduce_product_quanity(self, quantityToBeRemoved): amount = int(quantityToBeRemoved) return self.current_product_stock_available >= amount def deduct_quanity(self,quantity): if self.can_reduce_product_quanity(quantity): amount = int(quantity) self.current_product_stock_available -= amount self.save() return True return False generate_ref_no = str(uuid.uuid1()) class Transaction(models.Model): business = models.ForeignKey(Business_Account, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) amount = models.FloatField() productSold = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quanties_of_product_sold = models.IntegerField() transaction_date = models.DateTimeField(auto_now_add=True) payment_method = models.CharField(choices=PAYMENT_METHOD, max_length=50) reference_num = models.CharField(max_length=50, editable=False, default=generate_ref_no) def __str__(self): return f'{self.customer} ' My View: class TransactionView(generics.GenericAPIView): def get(self,request, business=None): query = Transaction.objects.filter(business=business) serializer = TransactionSerializer(query, many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) def post(self,request, business=None): serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.save() getTransaction = Transaction.objects.filter(reference_num=serializer.data['reference_num']) getTransaction_serializer = TransactionSerializer(getTransaction, many=True) Product.deduct_quanity(serializer.validated_data['quanties_of_product_sold']) #deduct the quantities sold from the particular product in stock_available return Response(data=serializer.data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_404_NOT_FOUND) I'm trying to call the 'deduct_quanity' method from the Product model in … -
How do i update user email with email verification in django allauth?
I am using django allauth for user authentication but I want to the user also update his email with email verification how can I do this? -
specifying output types for functions in python
I have this function def only_str() -> str: return None print(only_str()) Although None is not str but it's not giving me errors and everything works! Why is that? How can I specify output type for functions? -
Does Django's select_for_update method work with the update method
The Django ORM's select_for_update method allows the creation of locks on certain rows of certain tables within a database transaction. The documentation for Django 2.2, which I'm using, gives the following example: from django.db import transaction entries = Entry.objects.select_for_update().filter(author=request.user) with transaction.atomic(): for entry in entries: ... Using this approach, one would presumably mutate the model instances assigned to entry and call save on these. There are cases where I'd prefer the alternative approach below, but I'm unsure whether it would work (or even make sense) with select_for_update. with transaction.atomic(): Entry.objects.select_for_update().filter(author=request.user).update(foo="bar", wobble="wibble") The documentation states that the lock is created When the queryset is evaluated, so I doubt the update method would work. As far as I'm aware update just performs an UPDATE ... WHERE query, with no SELECT before it. However, I would appreciate it if someone more experienced with this aspect of the Django ORM could confirm this. A secondary question is whether a lock even adds any protection against race conditions if one makes a single UPDATE query against the locked rows. (I've entered this train of thought because I'm refactoring code that uses a lock when updating the values of two columns of a single row.) -
How can I create a model that represents a spreadsheet?
I am trying to build a table style app to allow tracking items in a spreadsheet that can be added to a branded website. My table would look something like this if using a spreadsheet: Customer Name Customer Address Producer Mark 233 Main St Greg Company Date Ordered Rep Date Received Cost Quote Number A 7/20/21 John 7/25/21 500 JDHP B 7/20/21 Mary C 7/23/21 John 7/25/21 1500 584D D 7/18/21 Mary 7/22/21 400 J5HP Effectively the idea is that I'd have a model that houses each Customer's different quotes. I have 2 categories of companies (public and private) that would each be tracked so I'm envisioning a large form that houses these three small forms (customer info, private company quotes and public company quotes). I would be including every company in every sheet whether we reach out to them for a quote or not so we know what options are still available if the customer requests more quotes. I've been looking at the django formsets as a possible option but don't fully understand how they work. I watched some tutorials and read through the documentation but it seems like those will simply add a blank input after all complete … -
how to debug password authentication failed with django postgres and docker-compose
How do you solve the problem below Not sure how i messed up my postgresql configuration (role + password etc...) I am using docker-compose django postgres13.3 db | 2021-07-23 13:05:23.221 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db | 2021-07-23 13:05:23.222 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db | 2021-07-23 13:05:23.222 UTC [1] LOG: listening on IPv6 address "::", port 5432 db | 2021-07-23 13:05:23.226 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db | 2021-07-23 13:05:23.233 UTC [27] LOG: database system was shut down at 2021-07-23 12:59:50 UTC db | 2021-07-23 13:05:23.252 UTC [1] LOG: database system is ready to accept connections db | 2021-07-23 13:05:27.817 UTC [34] FATAL: password authentication failed for user "postgres" db | 2021-07-23 13:05:27.817 UTC [34] DETAIL: Password does not match for user "postgres". db | Connection matched pg_hba.conf line 99: "host all all all md5" db | 2021-07-23 13:05:34.672 UTC [35] FATAL: password authentication failed for user "postgres" db | 2021-07-23 13:05:34.672 UTC [35] DETAIL: Password does not match for user "postgres". db | Connection matched pg_hba.conf line 99: "host all all all md5" ... backend | Traceback (most … -
how to make a field unique based on another filed in django models?
I want to make a field unique based on another field in the same model, this is my model: class Shop(models.Model): name = models.CharField(max_length=50) class Product(models.Model): name = models.CharField(max_length=50, unique=True) shop = models.ForignKey(Shop, on_delete=models.CASCADE) I want the product's name to be unique only based on Shop, for example, if we have the product a from shop a, shop a can not make another product with the name a but shop b can make a product with name a. for example we have name = models.CharField(unique_for_date=date_field) in models, which make the name unique for the date at date_field. is there anything like unique_for_date? can I handle this operation in models or I should try to handle it in view or form? -
Display the fields of a ForeignKey relation in the template
I need help to display the fields of a table that is a ForeignKey relationship in a Template. models nome = models.CharField (max_length=25,null=False, blank=False) revisao = models.CharField (max_length=20,null=True, blank=True) pit = models.ForeignKey(PIT, related_name='pit', on_delete=models.CASCADE, verbose_name= 'PIT - Plano de Inspeção e Teste') class PIT(models.Model): nome = models.CharField(max_length=50, null=False, blank=False) fluido = models.ManyToManyField(Fluido, related_name='fluido', blank=True, unique=False) In the IEIS Class I have the PIT field as FK. I need to display in the IEIS view template, some fields from the PIT class. views ieis = IEIS.objects.get(pk=pk) especs = ieis.especificacao.all() fluidos = ieis.fluido.all() pits = PIT.objects.get(pk=pk) return render(request, 'ieis/view.html', {'ieis': ieis, 'especs': especs, 'fluidos': fluidos, 'pits': pits,}) ieis.html </tr> </thead> <tbody> <tr> {% for pit in ieis.pits.all %} {{ pit }} {{ pit.nome }} {% endfor %} </tr> </tbody> Thank you in advance for all your attention, suggestions and dedicated help!