Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: safely store auth token to be share along all django users
I build a Django site wheres requires all users to be authenticated using the standard authentication of Django. In some of the pages django will be doing Request to a third party site which also require authentication. This third party site is not a django site and only has one user, this means that all django users will be sharing that 1 user to retrieve the information. The authentication to this third party site, is with a JWT Flow. We first retrieve an auth token and then we send this token to the desire end point adding the Django user ID, to retrieve that user ID information. I want to avoid all users in django doing multiple request to get the same auth token as this should be the same for all of them. Is there a way in Django to storage this auth Token safely? and perhaps if a user fail due to expiry token, django retrieves a new one and keep it safely store for all users to use? -
Django Rest Framework: 'RelatedManager' object has no attribute 'body' error when using nested serializer
With Django DRF, I am trying to display the comments for a particular post in a blog using a nested serializer. I have run into the following error: 'RelatedManager' object has no attribute 'body' Here is my code: comment model: class Comment(models.Model): #adapted from https://blog.logrocket.com/use-django-rest-framework-to-build-a-blog/ created = models.DateTimeField(auto_now_add=True) body = models.TextField(blank=False) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comments', on_delete=models.CASCADE) post = models.ForeignKey('Posts', related_name='comments', on_delete=models.CASCADE) @property def time_left(self): return self.post.time_left Post model: class Posts(models.Model): title = models.CharField(max_length=100) topic = MultiSelectField(choices=TOPIC_CHOICES) creation_timestamp = models.DateTimeField(auto_now_add=True) expiration_timestamp = models.DateTimeField(default=expiration) body = models.CharField(max_length=255) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #related_name='posts' likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="likes",blank=True) dislikes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="dislikes",blank=True) @property def is_expired(self): #taken from https://stackoverflow.com/questions/41505243/how-to-automatically-change-model-fields-in-django if now() > self.expiration_timestamp: return True return False @property def time_left(self): return self.expiration_timestamp - now() serializers.py: class CommentSerializer(serializers.ModelSerializer): time_left = serializers.ReadOnlyField() class Meta: model = Comment fields = ('created', 'body', 'user_id', 'post','time_left') class PostsSerializer(serializers.ModelSerializer): is_expired = serializers.ReadOnlyField() time_left = serializers.ReadOnlyField() comments = CommentSerializer(source='comments.body',) ########## THIS IS THE PROBLEMATIC LINE ####### class Meta: #make sure that the relevant fields are read only model = Posts fields = ('comments','title','topic','creation_timestamp','expiration_timestamp','body','user_id','likes','dislikes','is_expired','time_left') I believe the problematic line is the following one from serializers.py: comments = CommentSerializer(source='comments.body',) -
I need to customize all requests to have a response for every error can occur besides Making Event object mandatory in ingest event request
example :- GET/admin/clients/reset/{apikey}/{client_name} in this request, we need 2 response if adding apikey wrong or client name is wrong separately with 2 different responses POST/ingest/event { "sessionId": "string", "clientApiKey": "string", "category": "string", "action": "string", "interactive": "boolean", "label": "string", "amount": "double", "eventData": Object } response for each variable and the rest as above -Make Event object mandatory in the ingest event request POST/ingest/event { "sessionId": "string", "clientApiKey": "string", "category": "string", "action": "string", "interactive": "boolean", "label": "string", "amount": "double", "eventData": Object } -
Django reset oneToOneField on Custom User Model
I have a custom User model, which has a one-to-one relationship with a UserProfile model. I want to create a new UserProfile object and switch the existing related UserProfile object with the newly created one. This is essentially what I am trying to do: **views.py** def perform_create(self, serializer): club = serializer.save(created_by=self.request.user) user = self.request.user user.current_userprofile = None user.save() UserProfile.objects.create( user_account=self.request.user, club=club, current_active_userprofile=self.request.user, is_admin=True ) **models.py** class UserProfile(models.Model): user_account = models.ForeignKey(UserAccount, related_name='userprofiles', on_delete=models.CASCADE) club = models.ForeignKey(Club, related_name='club_userprofiles', on_delete=models.CASCADE) current_active_userprofile = models.OneToOneField(UserAccount, related_name='current_userprofile', on_delete=models.SET_NULL, blank=True, null=True) is_admin = models.BooleanField(default=False) However, the perform_create method triggers an integrity error: UNIQUE constraint failed: userprofile_userprofile.current_active_userprofile_id How do I reset the field to NULL so that I can connect it to the newly created object? -
NameError: name *model* is not defined; ManyToManyField/ForeignKey
Here is a relationship I'm aiming for in terms of a User, Question, Bookmark relationship; Bookmark being an intermediary table: A user can bookmark many Questions (topic pages) A Question (topic page) can be bookmarked by several users The keyword here being bookmark(ed), I have created a Bookmark model to show this relationship. However there's a problem of trying to make migrations due to a NameError being raised. Depending where they are defined in the script it's raising either: NameError: name 'Question' is not defined NameError: name 'Bookmark' is not defined How can I get past this error in order to push the Bookmark into the migrations directory with its ForeignKey references? class Question(models.Model): title = models.CharField(unique=True, max_length=40) body = models.TextField() created = models.DateField(auto_now_add=True) likes = models.IntegerField(default=0) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True ) views = models.ManyToManyField( View, related_name="+" ) tags = models.ManyToManyField( Tag, related_name="questions" ) bookmarks = models.ManyToManyField( Bookmark, related_name="+", ) def __str__(self): return self.title class Bookmark(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="+" ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="bookmarks" ) -
Implement f-string like syntax, with Django SafeString support
I implemented a fun little method h() which is Django's format_html() on steroids: It works fine, except the last assert fails, and I am unsure how to implement it: def test_h(): amp = '&' assert h('{amp}') == '&amp;' foo = format_html('<span>{bar}</span>', bar='&') assert h('<div>{foo}</div>') == '<div><span>&amp;</span></div>' assert h('{') == '{' assert h('') == '' name='foo' assert h('{name.upper()}') == 'FOO' assert h('{{}}') == '{}' # <--------------- how to get this working? Implementation: def h(html): """ Django's format_html() on steroids """ def replacer(match): call_frame = sys._getframe(3) return conditional_escape( eval(match.group(1), call_frame.f_globals, call_frame.f_locals)) return mark_safe(re.sub(r'{(.*?)}', replacer, html)) -
How create invalid email in python
I tried to find a function for my django project that creates invalid email, but I didn't find any. I found only functions that create valid emails and validators for them like this: import random import string DOMAINS = ["hotmail.com", "gmail.com", "aol.com", "mail.com", "yahoo.com", "mail.ru"] letters = string.ascii_letters def get_one_random_domain(): return random.choice(DOMAINS) def get_one_random_name(length=7): return ''.join(random.choice(letters) for i in range(length)) def get_random_email(): return get_one_random_name(letters) + '@' + get_one_random_domain() Please advise sites with similar information or links to ready-made solutions -
Nav item links not properly linking to new page
I am using Django to do this, I have a nav list with tabs and I want each tab to go to a new page and new corresponding view, the new pages will all have the same nav list, just with a different active tab. For some reason when I click on the tab, it won't change the page, I'm not sure what I'm doing wrong. Here is my code in the main page with the tabs: <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href="#summary">Summary</a> </li> <li class="nav-item"> <a class="nav-link external" data-toggle="tab" href="{% url 'financials:description' ticker %}">Description</a> </li> </ul> I know the link is correct, because I have tested it outside the nav links and it works fine. When I hover over the tab I see the proper URL at the bottom of page, but when I click nothing happens. I'm not sure if this has to do with javascript (I don't understand javascript yet and got the website template online). Thanks, any help greatly appreciated! -
Django Inline Formset That Allows for Creation of Parent and First Child Object on same page
Looking for examples how to build an inline formset that has the parent and one child model associated. End goal: one page with one form that creates the parent and first child object when the submit button is clicked. I'm struggling to find examples and/or literature explaining how to do this. This is my first complex django project. Thank you. -
Can't send GET request to Django via Postman
I perform request http://167.71.57.114/api/users/list-exercises And receive error User matching query does not exist. How can I fix the error? Found out that reason of the error is that request didn't have any data But you can see that I am sendig the "user_id" My code class WorkoutUserProgramListViewAPI(GenericAPIView): permission_classes = (IsAuthenticated,) serializer_class = WorkoutUserProgramListSerializer def get(self, request): response = {} user = request.data.get("user_id") # user is None user = User.objects.get(pk=user) # Error User matching query does not exist. -
Convenient and simple solution to receive and answer emails in a small Django app
I am developing a Django app which uses Email in some of its components (but not at its core). I am looking for a simple and cheap solution that satisfies the following requirements: Only the custom domain of the app is used (no username@gmail address) Django can send emails programmatically (error reporting, user data from forms) The admin can receive and and answer mails through an email client of their choice Solutions I have considered so far: Using my hosting provider: They understandably don't support custom email accounts for VPS customers Amazon SES: would work for sending email, but received emails would land in a S3 bucket; it is unclear to me how to connect this to an email client Sendgrid: would work for sending email, but the only way to handle inbound mail is to forward it as HTTP POST request to a view Django extensions to read and send email through the admin interface: I can't use my email client Google Workspace: seems like this could work. My issue is that it includes a lot of functionality I don't really need. Does anyone have experience with this? All I really need is to alias a standard email account … -
Approve application [closed]
Hello Django Professionals I am new to Django and I would like to add an approve application function to my project here is my views: def view_application(request, application_id): if request.user.userprofile.is_client: application = get_object_or_404(Application, pk=application_id ,job__created_by=request.user) else: application = get_object_or_404(Application, pk=application_id, created_by=request.user) if request.method == 'POST': content = request.POST.get('content') if content: conversationmessage = ConversationMessage.objects.create(application=application, content=content, created_by=request.user) create_notification(request,application.created_by, 'message',extra_id=application.id) return redirect('view_application',application_id=application_id) return render(request, 'view_application.html', {'application':application}) -
How to Pass Id Here (error put() missing 1 required positional argument: 'request') In form template djagno
urls.py from django.urls import path from . import views app_name = "poll" urlpatterns = [ path('', views.index, name="index"), # listing the polls path('<int:id>/edit/', views.put, name='poll_edit'), ] views.py def put(self, request, id): # print("catching error ") error before this line question = get_object_or_404(Question, id=id) poll_form = PollForm(request.POST, instance=question) choice_forms = [ChoiceForm(request.POST, prefix=str( choice.id), instance=choice) for choice in question.choice_set.all()] if poll_form.is_valid() and all([cf.is_valid() for cf in choice_form]): new_poll = poll_form.save(commit=False) new_poll.created_by = request.user new_poll.save() for cf in choice_form: new_choice = cf.save(commit=False) new_choice.question = new_poll new_choice.save() return redirect('poll:index') context = {'poll_form': poll_form, 'choice_forms': choice_forms} return render(request, 'polls/edit_poll.html', context) edit_poll.html {% extends 'base.html' %} {% block content %} <form method="PUT" > {% csrf_token %} <table class="table table-bordered table-light"> {{poll_form.as_table}} {% for form in choice_forms %} {{form.as_table}} {% endfor %} </table> <button type="submit" class="btn btn-warning float-right">Update</button> </form> {% endblock content %} this is error line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /polls/9/edit/ Exception Value: put() missing 1 required positional argument: 'request' I know that I am not passing argument in html but i dont know how to pass id argument in html please help me any single line of code something like default (context passing by djagno) -
Why can't I use custom slugs for Parent and Children in Django Rest Framework?
I'm trying to use custom slugs for Parent and Child models. Models: # models.py class Parent(models.Model): slug = models.SlugField() class Child(models.Model): parent = models.ForeignKey(Parent) order = models.IntegerField() slug = models.SlugField() class Meta: ordering = ['order', 'pk'] def save(self, *args, **kwargs): self.slug = f"{parent.slug}/{self.order}" super(Text, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("app:child-detail", kwargs={"slug": self.slug}) The Child model will use its order and the Parent's slug in its slug. I can get everything working with the default <int:pk> in the URLs but when I try to swap it to <slug:slug>, I get this error on both List and Detail views: Could not resolve URL for hyperlinked relationship using view name "app:child-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. When I try to call get_absolute_url() on a Child object (where the order is '1' and the parent's slug is 'parent-slug'), I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'child-detail' with keyword arguments '{'slug': 'parent-slug/1'}' not found. 2 pattern(s) tried: ['api/v1/child/(?P[-a-zA-Z0-9_]+)(?P\.[a-z0-9]+/?)$', 'api/v1/child/(?P[-a-zA-Z0-9_]+)$'] URLs: # project urls.py urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/", include("app.urls", namespace="app")), path("api-auth/", include("rest_framework.urls")), # login for Browserable API ] # app urls.py from django.urls import path, include from … -
django: runserver static files not found
I've read some posts on similar topics but none of them are exactly the same. I've a django app (django 2.2.2, python 3.6.12) that works with no problems when served with uwsgi (along with nginx), but has problems of finding static files when served with runserver (python manage.py runserver 0:8000) with error messages like the following: WARNING Not Found: /static/admin/css/base.css WARNING Not Found: /static/admin/js/core.js I have the following settings: BASE_PATH = '/data/webapps/myapp' STATIC_ROOT = os.path.join(BASE_PATH, '_site/static') and in BASE_PATH, I have the following folders which contain all files the system complained about not being found: _site/static/admin/css _site/static/admin/js I even duplicated the two folders _site/static/admin/css and _site/static/admin/js as static/admin/css and static/admin/js respectively in BASE_PATH, but with no effect. static/admin/css static/admin/js Here I want to emphasize that it works with no problems when served with uwsgi with the following command: uwsgi --ini uwsgi.ini and uwsgi.ini contains the following lines: [uwsgi] chdir = %d enable-threads = true max-requests = 5000 file = /data/webapps/myapp/myapp/conf/wsgi.py socket = uwsgi.sock chmod = 666 chmod-socket = 666 uid = myapp gid = myapp and wsgi.py has the following codes: """ WSGI config for mybic project. It exposes the WSGI callable as a module-level variable named ``application``. For more … -
Receiving unregistered task of type Error
Im getting the error [2021-03-27 18:36:43,996: ERROR/MainProcess] Received unregistered task of type 'orders.tasks.order_created'. The message has been ignored and discarded. Here all the associated system files. performancerealm.com |---orders | | __init__.py | |-tasks.py | |-views.py | |---speedrealm | |- __init__.py | |- celery.py | |- settings.py | |---manage.py |--- # other apps orders.py from celery import shared_task from django.core.mail import send_mail from .models import Order @shared_task def order_created(order_id): pass speedrealm.init.py from .celery import app as celery_app __all__=("celery_app",) speedrealm/celery.py import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'speedrealm.settings') app = Celery('speedrealm') app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() speedrealm.settings.py CELERYD_NODES="w1" CELERY_BIN="/home/bulofants/.local/share/virtualenvs/performancerealm.com-8nBM01mn/bin" CELERY_APP="speedrealm" CELERYD_CHIR="/home/bulofants/performancerealm.com" CELERYD_OPTS="--time-limit=300 --concurrency=8" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_USER="bulofants" CELERYD_GROUP="bulofants" CELERYD_LOG_LEVEL="INFO" CELERY_CREATE_DIRS=1 CELERY_IMPORTS = [ 'orders.tasks' ] CELERY_TIMEZONE='US/Eastern' This error only occurs with celery multi start w1 -A speedrealm -l DEBUG. My goal is that the task is going to run in the back grtound. I've tired running in different dirs (top-=level and app_dir), and I have also tried commenting/uncommenting CELERY_IMPORTS. Im not sure if this is needed but here is the conf.d also. /etc/systemd/system/celery.service [Unit] Description=Celery Service After=network.target [Service] Type=forking User=bulofants EnvironmentFile=/etc/default/celeryd/celeryconfig.py WorkingDirectory=/home/bulofants/sites/performancerealm.com ExecStart=/home/bulofants/.local/share/virtualenvs/performancerealm.com-8nBM01mn/bin/celery multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS} ExecStop=/home/bulofants/.local/share/virtualenvs/performancerealm.com-8nBM01mn/bin/celery ${CELERY_BIN} multi stopwait ${CELERYD_NODES} --pidfile=${CELERYD_PID_FILE} ExecReload=/home/bulofants/.local/share/virtualenvs/performancerealm.com-8nBM01mn/bin/celery ${CELERY_BIN} multi … -
Venv stops working as supposed after opening a branch in git
I had a project set up within VS-Code together with a venv (setup via "python -m venv venv") in it. Everything was working fine: Git worked and my venv did also do its job, e.g. opening python via the terminal while the venv was active would open the right python interpreter within the venv and thus find the correct libraries. I decided to open a new branch via the git command : "git checkout -b eel_replacement" and wanted to install Django afterwards via "pip install django"(while my venv was active). Installation succeded and I wanted to verify that by opening the python interpreter and trying "import django"(I also tried "import Django"), which did not work, resulting in the error: Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'django' If I type in pip list, then this is the output: pip list output There are 2 things that really got me confused right here: It does show all packages, not only the ones I installed within my venv. This normally indicates that my venv is not active! Nonetheless you can see it still shows the "(venv)" line before my command prompt, which normally indicates that … -
check password always returns false django
I work with django and store user passwords as hashed values created with make_password. When I run check_password, I always get a false return and I am out of ideas how to solve this. Any help would be much appreciated. My user registration looks like this: def user_reg_view(request): form = UserForm(request.POST or None) if form.is_valid(): password = hashers.make_password(form.cleaned_data.get('password')) fname = form.cleaned_data.get('first_name') lname = form.cleaned_data.get('last_name') email = form.cleaned_data.get('email') company_id = form.cleaned_data.get('company') User.objects.create_user( email = email, password=password, first_name = fname, last_name = lname, username = email, company_id = company_id) form = UserForm() var = {'form': form} return render(request, 'user_registry.html', var) And my login function part that fails looks like so (assume the user exists and password entered is always the same): def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') user = User.objects.get(username=username) password = form.cleaned_data.get('password') encoded_password = user.password print(hashers.make_password(password) == user.password) #returns false print(hashers.check_password(password=password, encoded=hashers.make_password(password), setter=None)) #returns true print(hashers.check_password(password=password, encoded=encoded_password)) # returns false I do not get how the first print differs from the second, of course the password hash generated differs each time for the same string but shouldn't check_password be able to process that? In case the error might be in the register form values passed, … -
POST a list of jsons in Django
i am beginner at the Django and have a problem. I make a REST API? and I want take as POST a list of JSON, like this POST /orders { "data": [ { "order_id": 1, "weight": 0.23, "region": 12, "delivery_hours": ["09:00-18:00"] }, { "order_id": 2, "weight": 15, "region": 1, "delivery_hours": ["09:00-18:00"] }, { "order_id": 3, "weight": 0.01, "region": 22, "delivery_hours": ["09:00-12:00", "16:00-21:30"] } ] } My serializers.py from rest_framework import serializers from rest_framework.decorators import api_view from .models import Courier, Order class CourierSerializer(serializers.ModelSerializer): class Meta: model = Courier fields = '__all__' class CourierCreateUpdateSerializer(serializers.ModelSerializer): class Meta: model = Courier fields = ('courier_id', 'courier_type', 'regions', 'working_hours',) def create(self, validated_data): return Courier.objects.create(**validated_data) def update(self, instance, validated_data): instance.courier_id = validated_data.get('courier_id', instance.courier_id) instance.courier_type = validated_data.get('courier_type', instance.courier_id) instance.regions = validated_data.get('regions', instance.courier_id) instance.working_hours = validated_data.get('working_hours', instance.courier_id) instance.save() return instance class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' def create(self, validated_data): return Order.objects.create(**validated_data) def update(self, instance, validated_data): instance.order_id = validated_data.get('order_id', instance.order_id) instance.weight = validated_data.get('weight', instance.weight) instance.region = validated_data.get('region', instance.region) instance.delivery_hours = validated_data.get('delivery_hours', instance.delivery_hours) instance.save() return instance @api_view(['POST']) def enroll(request): serializer = CourierCreateUpdateSerializer(data=request.data) serializer.is_valid(raise_exception=True) And my views.py from rest_framework.generics import get_object_or_404, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, \ ListCreateAPIView from Courierapp.serializer import CourierSerializer, CourierCreateUpdateSerializer, OrderSerializer from Courierapp.models import Courier, Order class … -
How to return relative to request django
In my django project, I built a little like-button. The problem is, that I had it only when I take a detailed view on a post, and now want to put it on the home page, where multiple posts are shown. The problem the Like Function of the button returns to the detailed page, but I want to make the return dependent from the url where the like came from, so that I can just scroll ahead on the home page or what ever page am on, without being returned to another page. So here is my views.py Like function: def PostLike(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) return HttpResponseRedirect(reverse('post-detail', args=[str(pk)])) So in a nutshell: how could I change my Like function so that I am returned to the page I liked from? -
Ошибка базы данных django + Mongo DB через djongo [closed]
I am making a site in django. I used djongo to work with the library. File settings.py from pathlib import Path import urllib # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '1u5ekr9oub%dtl)ew_!d)@&40447(#ktw71n=tde!m=iw1z!3(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'testapp', 'import_export', 'rest_framework', 'corsheaders', 'users' ] 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', 'corsheaders.middleware.CorsMiddleware' ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://localhost:8000', 'http://localhost:8080', ] ROOT_URLCONF = 'server.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'server.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'django_mongodb', } } # DATABASES = { # "default": { # 'ENGINE': 'djongo', # "name": 'api', # "host": 'mongo', # "port": 27017 # }, # } # DATABASE = { # 'default': { # 'ENGINE': 'djongo', # 'NAME': 'your-database-name', # 'CLIENT': … -
How do I use product image in html background url of a div?. Django
enter image description here Hello dear friends, I don't know how I can display a product-image inside my template. The image needs to go inside a background-url of a div, using static isn't a option, cause then its not coming form models. Please give me a awnser if you know how to do this? see image for more info -
Avoid querying related tables in Django
The model: class RegistrationSlot(models.Model): event = models.ForeignKey(verbose_name="Event", to=Event, related_name="registrations", on_delete=CASCADE) hole = models.ForeignKey(verbose_name="Hole", to=Hole, null=True, blank=True, on_delete=DO_NOTHING) registration = models.ForeignKey(verbose_name="Registration", to=Registration, blank=True, null=True, on_delete=SET_NULL, related_name="slots") player = models.ForeignKey(verbose_name="Player", to=Player, blank=True, null=True, on_delete=DO_NOTHING) starting_order = models.IntegerField(verbose_name="Starting order", default=0) slot = models.IntegerField(verbose_name="Slot number", default=0) status = models.CharField(verbose_name="Status", choices=STATUS_CHOICES, max_length=1, default="A") class Meta: ordering = ("hole", "slot") constraints = [ UniqueConstraint(fields=["event", "player"], name="unique_player_registration") ] objects = RegistrationSlotManager() In the manager I declare that I always want the player: class RegistrationSlotManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related("player") The primary access pattern for this data is to query by an event id, so the view filter looks like this: def get_queryset(self): queryset = RegistrationSlot.objects.all() event_id = self.request.query_params.get("event_id", None) if event_id is not None: queryset = queryset.filter(event=event_id) return queryset And what my UI wants is very simple. The serialized json object does not include related objects other than the player: { "id": 5798, "event": 344, "hole": 1, "registration": 9996, "starting_order": 0, "slot": 0, "status": "R", "player": { "id": 353, "first_name": "John", "last_name": "Dough" } } So while trying to optimize my api, this query should be one of the fastest, but it's not. The Django ORM is generating 1000+ queries that I do not want. The register_registrationslot query … -
Migrations Applied Locally but not in production
I have a django app in docker. The local setup is identical to the production one. However, the migrations are applied in the local setup but not in production. Local Setup Dockerfile . . . # copy entrypoint.sh COPY ./entrypoint.sh /web/entrypoint.sh # copy project COPY . /web/ # run entrypoint.sh ENTRYPOINT ["/web/entrypoint.sh"] entrypoint.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py flush --no-input echo "Apply database migrations" python manage.py makemigrations echo "Migrating" python manage.py migrate echo "Build static files" python manage.py collectstatic --no-input exec "$@" Production Dockerfile.prod . . . # copy project COPY . /web/ # run entrypoint.sh ENTRYPOINT ["/web/entrypoint.prod.sh"] entrypoint.prod.sh #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi echo "Apply database migrations" python manage.py makemigrations echo "Migrating" python manage.py migrate echo "Build static files" python manage.py collectstatic --no-input --clear exec "$@" Now, if I run ./manage.py showmigrations for local, I get accounts [X] 0001_initial [X] 0002_userprofile [X] 0003_userprofile_gender [X] 0004_userprofile_country [X] 0005_user_otp_mobile [X] 0006_user_mobile_veified [X] 0007_auto_20200506_0716 [X] 0008_auto_20201004_0642 [X] 0009_auto_20201021_1054 … -
How to handle nullable field with SubFactory of factoryboy in django?
I want to make nullable store attribute of StoreFactory. If I give store name, I want to that it return existing store object. but, It raised error. How can I get EventFactory instance with existing store object? # events/models.py SELL_DIRECT = "SD" ORDER_PRODUCT = "OP" SEND_PRODUCT = "SP" SETTLE_SALE = "SS" LEAVE_STORE = "LS" DEFECT_PRODUCT_IN_STORE = "DS" DEFECT_PRODUCT_IN_HOME = "DH" EVENT_TYPE_CHOICES = ( (SELL_DIRECT, "개인판매"), (ORDER_PRODUCT, "제품발주"), (SEND_PRODUCT, "입점처 입고"), (SETTLE_SALE, "판매내역정산"), (LEAVE_STORE, "입점처 퇴점"), (DEFECT_PRODUCT_IN_STORE, "불량:입점처"), (DEFECT_PRODUCT_IN_HOME, "불량:집"), ) EVENT_TYPES_ABOUT_STORE = set( [SEND_PRODUCT, SETTLE_SALE, LEAVE_STORE, DEFECT_PRODUCT_IN_STORE] ) class Store(TimestampedModel): """ 입점처 """ name = models.CharField(_("이름"), max_length=50, unique=True) description = models.TextField(_("설명")) class Event(TimestampedModel): """ 재고 변화 내역 """ event_type = models.CharField( _("재고 변화 타입"), choices=EVENT_TYPE_CHOICES, max_length=2 ) store = models.ForeignKey( "Store", verbose_name=_("입점처"), on_delete=models.CASCADE, blank=True, null=True, ) description = models.TextField(_("설명")) # events/factories.py import factory from events.models import ( EVENT_TYPES_ABOUT_STORE, EVENT_TYPE_CHOICES, ) class StoreFactory(factory.django.DjangoModelFactory): class Meta: model = "events.Store" django_get_or_create = ("name",) name = factory.Sequence(lambda n: f"store_{n}") description = factory.Sequence(lambda n: f"description_{n}") class EventFactory(factory.django.DjangoModelFactory): class Meta: model = "events.Event" event_type = factory.Faker( "random_element", elements=[choice[0] for choice in EVENT_TYPE_CHOICES] ) description = factory.Sequence(lambda n: f"event_{n}") @factory.lazy_attribute def store(self): if self.event_type in EVENT_TYPES_ABOUT_STORE: return StoreFactory() return None In [20]: Store.objects.last() Out[20]: <Store: store_10> In …