Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django User matching query does not exist on foreign-key relation
I am trying to create a system in django by which user will login through phone number. Used AbstractBaseUser to use the number as user id. Now I am trying to create a foreign key relation of every transaction with the number. While I try to push a transaction it says "User matching query does not exist". I am getting where I made mistake. User model: class User(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField("Phone number", max_length=100, unique=True, error_messages={ 'unique': ("number_existsssss"), }) name = models.TextField("Name") time_stamp = models.DateTimeField("Time-Date", auto_now=True) request_type = models.CharField(max_length=100, default="check" is_staff = models.BooleanField(verbose_name=('staff status'), default=False) is_active = models.BooleanField(verbose_name=('active'), default=True) Transaction Model: class TransactionModel(models.Model): trxID = models.CharField(max_length=15, null=True, unique=True) User = models.ForeignKey(to=User, to_field="phone_number", related_name='transaction', on_delete=models.DO_NOTHING, default=1) time = models.DateTimeField(auto_now=True, null=True) amount = models.CharField(max_length=5, null=True) pay_method = models.CharField(max_length=10, null=True) amountReceivedFrom = models.CharField(max_length=26, null=True) transactionStatus = models.CharField(max_length=15, null=True, default='False') I think I made some mistake on foreign key relation. the error shows: raise self.model.DoesNotExist( user_signup.models.User.DoesNotExist: User matching query does not exist. [04/Sep/2021 18:44:22] "POST /add-cash/b-kash HTTP/1.1" 500 20728 -
How to update a different models instance based on a PATCH request of a different model in django rest framework?
I have two models, one Master model which stores information coming from batch and trial models. Now what I need is when I perform a PATCH request on the batch I want the Master entries for that batch to be updated as well. But the catch is that I have overridden the save method in a way that whenever I call the save method, all info goes on to the Master model, same goes for trial as well. How can I achieve this? -
Word count in a row
3 larg email messag render slowli 3 profil manag xml pars error 4 click sidebar tab set focu sidebar Suppose this is my txt file dataset in a short form. I want to count every word in a row and replace that word into that word count no. But i can't. In python how to do that code. -
django add parents to field valurs
I have a Product model that has a ManyToMany to Category. Category has a ForeignKey to itself named parent. I want to add all parents of selected category to category field. example for category: digital appliance->None __ Mobile->digital appliance __ Samsung->Mobile and... when choose Samsung for category of a product, I want to add Mobile and digital appliance to category it's my models, the save method doesn't do anything Class Product: class Product(models.Model): STATUS_CHOICES = ( ('s', 'show'), ('h', 'hide'), ) title = models.CharField(max_length=150) slug = models.SlugField(max_length=170, unique=True) category = models.ManyToManyField(Category) thumbnail = models.ImageField(upload_to='images/products', default='images/no-image-available.png') image_list = ImageSpecField(source='thumbnail', processors=[ResizeToFill(400, 200)], format='JPEG',options={'quality': 75}) image_detail = ImageSpecField(source='thumbnail', processors=[ResizeToFill(1000, 500)], format='JPEG',options={'quality': 100}) description = models.TextField() inventory = models.IntegerField() features = models.ManyToManyField(Feature) status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='s') def __str__(self): return self.title class Meta: verbose_name = "product" verbose_name_plural = "products" def save(self, *args, **kwargs): for cat in self.category.all(): if cat.parent: self.category.add(cat.parent) return super(Product, self).save(*args, **kwargs) objects = ProductManager() Category and CategoryManager: class CategoryManager(models.Manager): def no_parent(self): return self.filter(parent=None) def get_parent(self, parent): return self.filter(parent=parent) class Category(models.Model): parent = models.ForeignKey('self', default=None, null=True, blank=True, on_delete=models.SET_NULL,related_name='children') title = models.CharField(max_length=40) slug = models.SlugField() status = models.BooleanField(default=True) -
How to change the Django admin filter to use a dropdown instead of list that can also be searched?
Before you mark this as Duplicate, I have read the solutions to this question. In Django Admin I have lots of values. The team that works on that data, currently can use CTRL+F to atleast find the required field. To fix the UI I have the Dropdown rendering option available in the solution of the question tagged above. But, as I said I need it to be searchable. -
Why would someone set primary_key=True on an One to one reationship (OneToOneField)?
I was watching a video on django-orm and the instructor stated that: We should set primary_key=True to prevent a Model from having duplicate rows in a OneToOne relationship (Ex: Prevent a user from having multiple profiles). I know this statement is wrong! AFAIK, an OneToOne field is just a ForeignKey with unique parameter set to True. But I got curious and looked-up the Django documentation, Sure enough they are using primary=True in their example. class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(models.Model): place = models.OneToOneField( Place, on_delete=models.CASCADE, primary_key=True, ) So, why would someone set primary_key=True on an OneToOne relation? My guess is that it's just reasonable to have that field as a primary key and there is no technical background behind it. -
In Django project method authenticate returns None
I have a problem with authenticate() method. It always returns None. I checked all my arguments and they are not empty. In models i have USERNAME_FIELD = 'username', in settings i have AUTH_USER_MODEL = 'account.User'. I really cant understand why it's not working. Help please models.py class User(AbstractBaseUser): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='id') email = models.EmailField() username = models.CharField(max_length=25, unique=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) education = models.CharField(max_length=100, blank=True) date_of_birth = models.DateField(blank=True, null=True) name = models.CharField(max_length=25, blank=True) last_name = models.CharField(max_length=25, blank=True) objects = UserManager() USERNAME_FIELD = 'username' views.py class UserLoginView(ObtainAuthToken): serializer_class = UserLoginSerializer serializers.py class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(required=True) password = serializers.CharField(required=True) def validate_username(self, username): if not User.objects.filter(username=username).exists(): raise serializers.ValidationError('User wasn\'t found') print(User.objects.get(username=username).password) return username def validate(self, data): # authentications request = self.context.get('request') username = data.get('username') # test_name password = data.get('password') # newpassword11 if username and password: user = authenticate(username=username, password=password, request=request) print(user) if not user: raise serializers.ValidationError('Invalid password') else: raise serializers.ValidationError('You have to type you\'re mail and password') data['user'] = user return data -
How to access Heroku config variables inside Django settings
I am trying to push my code on Heroku, I have hidden my secret key using environ package but now Heroku is not able to access it since I have ignore my .env files using gitignore, I have read about config vars in Heroku but I am having trouble understanding how do I make Django access those values import os import environ # from .secret import key env = environ.Env() environ.Env.read_env() SECRET_KEY = env('KEY',default=env('SECRET_KEY')) -
How can I order only some specific objects randomly in django?
I have a model with is_random_sortable boolean field and position integer field, I want to sort queryset randomly when is_random_sortable is true, otherwise, I want to order by position field. Imagine I have an object with is_random_sortable=False and position=3. I want to have sorted results like this: (numbers are positions) [15, 6, 9, 3, 11, 7, 10,...] object with position 3 always is on index 3 of the list. And other objects with is_random_sortable=True are sorted randomly. -
Safe way to validate file extension in serializer Django
I created an application where I can store images of products. In the database I store just directions to images which are held in designated folder. In my serializer I need to validate the files names and check if the extensions are photo extensions. I wrote something like this below, is it the best way to checking it? Is there maybe more safe method? ALLOWED_IMAGE_EXTENSIONS = ["png", "jpg", "jpeg", "bmp", "gif"] class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = [...] class ProductSerializer(serializers.ModelSerializer): images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = [..., 'images'] def create(self, validated_data): ... for file in self.context['request'].FILES.getlist('images'): validate_extension(file.name) ... return item def validate_extension(filename): extension = os.path.splitext(filename)[1].replace(".", "") if extension.lower() not in ALLOWED_IMAGE_EXTENSIONS: raise serializers.ValidationError( (f'Invalid uploaded file type: {filename}'), code='invalid', ) -
How to remove loading logo in elastic search?
I add my project an elastic-search <iframe>. When page reloads there are a logo and a loading elastic sentence appears. How can I remove it? -
Django REST Framework, Serializers: Additional data?
Good day, I would like to ask, if there's a possibility to gain additional data inside my serializers? These are my models... models.py class Chair(models.Model): name = models.CharField(max_length=100, null=False, blank=False, unique=True) bookable = models.BooleanField(default=False) user_created = models.CharField(max_length=100) date_created = models.DateField(auto_now_add=True) class Booking(models.Model): chair = models.ForeignKey(Chair, on_delete=models.CASCADE) day = models.DateField() user_name = models.CharField(max_length=100) user_created = models.CharField(max_length=100) date_created = models.DateField(auto_now_add=True) and these my serializers... serializers.py class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = '__all__' class ChairSerializer(serializers.ModelSerializer): class Meta: model = Chair fields = '__all__' When making a request inside js like this... views.py @api_view(['GET']) def bookings_by_date(request, pk): bookings = Booking.objects.filter(day=pk) serializer = BookingSerializer(bookings, many=True) return Response(serializer.data) script.js let url = '...here's my url for Booking...'; fetch(url) .then((resp) => resp.json()) .then(function(data) { // do something here }); ...I would like to get not only the id of the Chair (models.Foreignkey), but also it's name. My first thought was doing something like this... class ChairSerializer(serializers.ModelSerializer): class Meta: model = Chair fields = [ ... 'chair', 'chair__name', ... ] ...but this doesn't seem to work! Does anyone know a solution for my problem? Thanks for all your help and have a great weekend! -
Should i continue learning django i reached intermediate and go with docker and kubernetes or should i start learning react (i am beginner)
What should i learn Learning django with more than a year and made several projects in django. should I continuing django and dig deep into it or should i start learning react as it is emerging. to meet standard -
Django SMTP Send Email Configuration
I already setup the email. It was working perfectly but after sometime it is not working and sending the mail. I don't know where the problem was created. Can someone help me out with this?? EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypass' this is my email function code: def my_email(): order = Order.objects.filter(createdAt__gt=Now()-timedelta(minutes=1)) p = str(settings.BASE_DIR) with open(p + '/templates/email.html') as f: order_message = f.read() for o in order: print(o._id) email = EmailMultiAlternatives(subject='Thank you', body=order_message, from_email='laksura.com.bd@gmail.com', to=['sohanur.shanto@northsouth.edu'] ) html_template = get_template('email.html').render() html_template = render_to_string('email.html', {'name': o.user, 'order_id': o._id, 'total': o.totalPrice, 'created': o.createdAt}) email.attach_alternative(html_template, "text/html") email.send() I am getting this error new_conn_created = self.open() File "C:\Python39\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Python39\lib\smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "C:\Python39\lib\smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python39\lib\smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File "C:\Python39\lib\socket.py", line 843, in create_connection raise err File "C:\Python39\lib\socket.py", line 831, in create_connection sock.connect(sa) TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has … -
Python passing dynamic value to decorator arguments
Is there a way to pass a dynamic value on the decorator's argument from the function that decorates? For example, @cached_property_with_ttl(ttl=authenticate['expires_in']) def authenticate(self): response = requests.post( self.token_url, data={ "client_id": self.__client_id, "client_secret": self.__client_secret, "audience": self.audience, "grant_type": self.grant_type, }, ) return response.json() I want to get the JSON response from the authenticate() function and pass the "expires_in" from the JSON as a value to the decorator's ttl argument which decorates the authenticate function. -
postgis.control is not found on github actions
In my github actions yml, it can't find postgis.control. But, if find /usr -name postgis.control did, it can find postgis.control. I don't know why test can't find postgis.control.. Any idea? name: Django CI on: push jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.7] services: postgres: image: postgres:12 ports: - 5432:5432 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: ghostlabs_localhost options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: psycopg2 prerequisites run: | sudo apt-get update && sudo apt remove -y postgis* postgresql* && sudo apt-get install -y libpq-dev gdal-bin postgresql-12 postgresql-12-postgis-3 postgresql-12-postgis-3-scripts postgresql-contrib-12 echo "-----" find /usr -name postgis.control - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements/localhost.txt - name: Run Tests run: | python manage.py migrate && python manage.py test Log shows ----- /usr/share/postgresql/12/extension/postgis.control But, test has Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.7.11/x64/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedFile: could not open extension control file "/usr/share/postgresql/12/extension/postgis.control": No such file or directory -
Serverside debug Django "Not Acceptable"
When calling an URL on my Django API it returns: [04/Sep/2021 08:14:47] WARNING [django.request:224] Not Acceptable: /api/calendar/test.ics Calling the same URL from PostMan (or curl) returns a simple iCal file so the URL is valid and returning. What I found was that the cause is the "Accept" headers sent by the client. The problem is that the request never actually hits my view so I cannot inspect request.META for the value of the received accept header. How can I discover, serverside, what headers were sent and what their values are? -
Django Rest Framework Permissions with firebase auth
I have backend with django-rest-framework, and frontend with react. And I have one endpoint which returns all users list. I want only admin be able to see all users list, so I put permission_classes = [IsAdminUser] in my view. I tested it with browsable api and everything works fine. Authentication system is with firebase in frontend, so every time when I send get request to server it returns authentication credentials were not provided because I don't use DRF endpoint to login, I use firebase login instead. So my question is how can I make only admin user see the data? -
How to create multi logins in django
How to create multiple user logins with different users with same browser address with different devices only using login page on django. I want all templates and pythons files. -
Django form - what's the right form/template to create a many to many object inline
I have to two models Directors and JobProject. A JobProject can have multiple directors through a many-to-many relationship. Currently, when I create a new JobProject I choose from the directors I have saved who the director will be. However, I am trying understand how can I code a form/view for creating a JobProject where I can also create a director in-line (in case I don't have the director already saved in the DB). Ideally the users'flow would be: 1) Start entering a JobProject details. 2) If the director already exist in the DB, pick it. 3) If the director doesn't exist, allow users to enter the details of a new director object in-line 4) Users go ahead and finish entering JobProject details. 5) Users click save and the BE first save the new director and then save the new project with director pointing at the newly created director. I basically have 1,2,4,5 figured out but I can't understand how to do 3. Any help? These is my code right now. Model class Director(models.Model): ... name_surname = models.CharField(max_length=60) class JobProject(models.Model): ... director = models.ManyToManyField(Director, blank=True, ) Form class DirectorForm(forms.ModelForm): class Meta: model = Director fields = '__all__' exclude = ('id', 'owner', … -
How to add block ip functionality to Django Website?
i'm trying to add block user IP functionality to my website. So if user is declined after registration, i have a choice to block user ip. I wrote a code which shows me the user IP. But could not figure out how to write a block user ip function. I am very new to Python/Django. Thanks in advance. -
How to detect lack of specific parameter in payload and go to except in Django?
I have a method like this: @csrf_exempt def my_method(request): if request.method == 'POST': try: name = payload['name'] return HttpResponse("YES", content_type='text/json') except payload['name'].DoesNotExist: return HttpResponse("NO", content_type='text/json') But i have getting several errors. Please help me to fix this as well i receive better way. -
Django NoReverseMatch at /services/ 'services' is not a registered namespace
I'm trying to display a group of images classified by category. When the user clicks on a category name, the page should display the images that belongs to that category. I'm getting the the next browser error: NoReverseMatch at /services/ 'services' is not a registered namespace . . . Error during template rendering The models belongs to different apps, one (that contains the Category model) works fine, and this other (That contains the Services model) just works if I delete the html content that I need. Help me please. Here are my files: home_app/models.py from django.db import models from django.urls import reverse class Category(models.Model): name=models.CharField(primary_key=True, max_length=50) slug=models.SlugField(unique=True, blank=True, null=True) image=models.ImageField(upload_to='category_home') description=models.CharField(max_length=100) content=models.TextField(max_length=500, default="Service") created=models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('services:services_by_category', args=[self.slug]) services_app/models.py from django.db import models from home_app.models import Category class Services(models.Model): category=models.ForeignKey(Category, on_delete=models.CASCADE) title=models.CharField(max_length=50) completed=models.DateField(auto_now_add=False, null=True, blank=True) content=models.CharField(max_length=50, null=True, blank=True) image=models.ImageField(upload_to='services_services') created=models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Service' verbose_name_plural = 'Services' def __str__(self): return '%s de %s' % (self.category, self.title) services_app/views.py from django.shortcuts import render, get_object_or_404 from .models import Services from home_app.models import Category def service_list(request,category_slug=None): category = None categories = Category.objects.all() services = Services.objects.all() if category_slug: category = get_object_or_404(Category,slug=category_slug) … -
Filtering multiple models in Django
I want to Filter across multiple tables in Django. q = json.loads(request.body) qs = Search.objects.filter(keyword__icontains=q['q']).all() data = serialize("json", qs, fields=('keyword', 'user')) That's one, secondly, the user field is returning an integer value (pk) instead of maybe the username. -
why cant import Celery from celery
When i putted my project on production even with runserver test this error did not raised but when i used gunicorn --bind for test this happens import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sqh.settings.dev') app = Celery('sqh',broker_url = 'redis://localhost:6379/0') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() #@app.task(bind=True) #def debug_task(self): # print(f'Request: {self.request!r}') ImportError: cannot import name Celery