Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allauth - get SocialAccount.id after successful login/connect/signup
After the user connects their social account (which can be any of Google, Microsoft and even custom providers) and is redirected to /some/redirect/url, I need to get the ID of the account (SocialAccount model). A very simple example would be: user clicks on accounts/google/login/?process=connect&next=/some/redirect/url After successful connection (no matter if already exists or not), user is redirected to /some/redirect/url The page says "Your newly connected SocialAccount.id is 45" I could theoretically get all SocialAccount objects of this user and return the newest one but I want this to work also when the user just doesn't realize they already connected their account. How can I do that? EDIT: I'm also open to using cookies as a messenger for this ID. -
Why am I being told that temp_list is not defined when it is when I check if a word of list are in string [closed]
I’m on Django and I try to get subject of mail and check if a certain word are in the subject. For that I do : (all code here) def decode_str(word): h = make_header(decode_header(word)) s = str(h) return s class HomeAppView(TemplateView): template_name = "app_manager/index.html" # Déclarations des variables utiles. Ne pas toucher encoding = 'utf-8' final_list = [] ras = erreur = 0 lstSubjectRAS = [] lstSubjectError = [] # Listes des mots de RAS lst_RAS = [ "ras", "RAS", "réussi ", "terminée", "terminé" ] # Liste des mot d'erreurs lst_ERREUR = [ "error", "erreur", "échoué" ] # Déclarations attendu = 10 date = (datetime.date.today() - datetime.timedelta(30)).strftime("%d-%b-%Y") msg_from = '"Name"' # Tri result, data = m.search(None, '(FROM {msg_from} SENTSINCE {date})'.format(date=date, msg_from=msg_from)) ids = str(data[0], encoding) # Création d'une liste de message par ids id_list = ids.split() for emailid in id_list: temp_dict = {} result, data = m.fetch(str(emailid), "(RFC822)") email_body = data[0][1] mail = email.message_from_bytes(email_body) temp_dict['Sender'] = mail["From"] temp_dict['Date'] = mail["Date"] s = mail["Subject"] temp_dict['Subject'] = decode_str(s) if any(word in temp_dict['Subject'] for word in lst_RAS): ras = ras + 1 final_list.append(temp_dict) manque = attendu - (ras + erreur) Details : Firstly I declare a list of word which I will then … -
ERROR: Template does not exist / Used: Django + React + heroku
I created a simple note with django & react app. And I am trying to deploy to Heroku. I tried heroku open at terminal, but this error page came out. enter image description here Here is my environment and things i've tried for 2 days. File structure) project-folder api env frontend (my React app) build index.html public src package.json mynote (my Django main app) settings.py manage.py Procfile requirements.txt runtime.txt requirements.txt) asgiref==3.5.2 dj-database-url==0.5.0 Django==4.0.5 django-cors-headers==3.13.0 djangorestframework==3.13.1 gunicorn==20.1.0 psycopg2-binary==2.9.3 pytz==2022.1 sqlparse==0.4.2 tzdata==2022.1 whitenoise==6.2.0 runtime.txt) python-3.10.0 Procfile) web: gunicorn mynotes.wsgi --log-file - settings.py) """ Django settings for mynotes project. """ from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # for heroku deploy SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '~') # for heroku deploy DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) ) ALLOWED_HOSTS = [ '[here is my project name!].herokuapp.com', '127.0.0.1' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'api', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ALLOW_ALL_ORIGINS = True ROOT_URLCONF = 'mynotes.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], '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 = 'mynotes.wsgi.application' … -
Django: ERROR (EXTERNAL IP): Invalid HTTP_HOST header ... - Correct host but spam queries?
Sometimes I get a wave of errors like this: [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'app.mysite.com'. You may need to add 'app.mysite.com' to ALLOWED_HOSTS. The thing is, app.mysite.com is the correct host, and it definitely is already in allowed host. However, the requests that are getting blocked are spam, sending: Post requests to '/uncensored' Requests to '/query?dns=DUIBAAA...' (long string of letters) Requests to '/doh/family-filter?dns=....' (long string) All have CONTENT_TYPE = 'application/dns-message' It makes sense that the queries are blocked, but it doesn't make sense that it's an invalid HTTP_HOST header error. Does HTTP_HOST check against something else in addition to allowed_hosts? -
Export selected rows in CSV with django-tables2
I'm using django-tables2 to create a table. I have added a CheckBoxColumn and it works fine in my form when sending data (i.e. upon form submit, it sends a list of all the checkboxes that I've ticked). My question is how can I use that to export ONLY the selected rows in CSV? I want to avoid using JS, as this way I'm afraid I lose the functionality that comes with TableExport. thanks in advance. -
Assign child field to parent when create with help of django-mptt
The question, is how can I create with help of django-mptt, a new sub with parent name (that is already in DB) ? like new product>account but with already FK for subs parent(by his name for example) Models: class Product(models.Model): account = models.OneToOneField( Account, primary_key=True, related_name='product', on_delete=models.CASCADE, ) class Account(models.Model): subs = models.ForeignKey( Subs, related_name='accounts', on_delete=models.CASCADE, ) class Subs(models.Model, MPTTModel): name = models.CharField(max_length=255) parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='subs') Serializers: class ProductCreateSerializer(CreateModelSerializer): subs = serializers.PrimaryKeyRelatedField(queryset=Subs.objects.all()) account = serializers.PrimaryKeyRelatedField(queryset=Account.objects.all()) class Meta: model = Product fields = "__all__" def create(self, validated_data): subs = validated_data.pop("subs") account = Account.objects.create( subs=subs, account=account, name=validated_data['name'] ) validated_data["account"] = account return super().create(validated_data) -
With an existing Django site, can I write a script that returns raw output, kind of like and API but simpler?
I have a very simple django site running on pythonanywhere.com; I'd like now add on a script that does something not directly related to the website. Specifically I'd like to run a script that takes a URL such as www.mysite.com/GetLatLong/V95AE16 In this case the V95AE16 is a postcode The url would execute the script GetLatLong.py using V95AE19 as input and then return raw data in the format 52.46723, -8.23564 This is to be used by a different application (nothing to do with python) which will just use my script like an API, just simpler, no CRUD, just giving a single value and getting some values in return Many thanks / Colm -
Django connect to a particular database based on the user
I have a scenario where each user has a separate database(about 100 customers). What could be best possible way of connecting to the database as per user ? including all the database connection names doesn't make sense because every time I want to add a user I need to modify the settings file again. I am new to Django. Can someone help me with this ? -
Django rules with abstract base class throw error after addition
Trying to add Django-rules to my Django project I am encountering the following issue: I have an abstract base class, which I am using to add a couple of common keys. Now I want to add default permissions to the abstract class, and overwrite them, if needed. Below are my abstract base class and an example of a subclass. class BaseModel(RulesModelBaseMixin): company_id = models.ForeignKey('company.Company', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey( 'user.User', on_delete=models.SET_NULL, null=True, blank=True) class Meta: abstract = True rules_permissions = { "can_create": can_create_in_company | is_superuser, "can_view": can_view_in_company | is_author | is_superuser, "can_edit": can_change_obj | is_author | is_superuser, "can_delete": can_delete_obj | is_author | is_superuser, } class Ticket(RulesModelMixin, BaseModel, metaclass=RulesModelBase): name = models.CharField(max_length=512, null=True, blank=True) description = models.TextField(blank=True, null=True) After adding this abstract base, I now get a seemingly unrelated error message from Django: Traceback (most recent call last): File "REPO_PATH/.venv/lib/python3.10/site-packages/django/utils/module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "REPO_PATH/.venv/lib/python3.10/site-packages/django/utils/module_loading.py", line 15, in cached_import import_module(module_path) File "/opt/homebrew/Cellar/python@3.10/3.10.4/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module … -
An image classification error type while using django-rest and react axios
I'm working on a classification image project with django rest framework and react using axios and 've got an error that kept me from manipulating my images As an api model.py from django.db import models from keras.utils import img_to_array, load_img import numpy as np from keras.applications.vgg16 import preprocess_input class PicUpload(models.Model): imagefile = models.ImageField(upload_to = 'pic_upload') car_Check=models.CharField(max_length=4,blank=True) damage=models.CharField(max_length=4,blank=True) location=models.CharField(max_length=10,blank=True) severity=models.CharField(max_length=10,blank=True) cost=models.CharField(max_length=20,blank=True) uploaded=models.DateTimeField(auto_now_add=True) def __str__(self): return 'Image classified at {}'.format(self.uploaded.strftime('%Y-%m-%d %H:%M:%S')) def save(self,*args,**kwargs): try: print(self.imagefile) print('xxxxxxxxxxxxxxxxxx') img =load_img(self.imagefile, target_size=(224, 224)) x = img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) except Exception as e: print('classification failed',e) super().save(*args,**kwargs) As a setting STATIC_URL = 'static/' STATICFILES_DIRS=[STATIC_DIR,] #PIC OR MEDIA PIC_ROOT=PIC_DIR PIC_URL='/pic_upload/' #PIC_DIR = os.path.join(BASE_DIR, 'pic_upload') #BASE_DIR = Path(__file__).resolve().parent.parent # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' This is what I get for response System check identified no issues (0 silenced). June 10, 2022 - 13:48:59 Django version 4.0.4, using settings 'cardamage.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. karhba.jpeg xxxxxxxxxxxxxxxxxx classification failed path should be path-like or io.BytesIO, not <class 'django.db.models.fields.files.ImageFieldFile'> [10/Jun/2022 13:49:13] "POST /api/PicUpload/ HTTP/1.1" 201 182 Knowing that I got this in my console data: {…}, status: 201, statusText: 'Created', headers: {…}, config: {…}, …} config: … -
django update boolean field in a signal (pre_save)
I've tried .update() and .save(updated_fields=list(kwargs.keys())) but it doesn't save the changes it looks good when stepping through it in debug mode then it reverts back for the test. Am I working on a separate copy or is caching a thing that I should be checking? in tests/test_status_model.py def test_status_set_tag_info_obsolete(self): """ check to see if the creation of a statusInfo object which runs a pre_save signal changes the soon_to_be_obsolete_tag to is_obsolete=True """ self.assertFalse(self.soon_to_be_obsolete_tag.is_obsolete) self.main_status_info = StatusInfoFactory( affected_tag=self.soon_to_be_obsolete_tag, status="o", # obsolete by=self.new_replacement_tag, ) self.assertTrue(self.soon_to_be_obsolete_tag.is_obsolete) # fails in status/models.py @receiver(pre_save, sender=StatusInfo) def status_change_modification(sender, instance, *args, **kwargs): """ Changes tags and concepts to be obsolete or deprecated. if a tag is obsolete or deprecated, all of the tag's concepts are obsolete or deprecated """ assert hasattr(instance.affected_tag, "id") # set up variables kwargs = {} if instance.status == "d": kwargs["is_deprecated"] = True elif instance.status == "o": kwargs["is_obsolete"] = True if instance.affected_tag_or_concept == "t": # Yes this works inner_tag_status_change(instance, **kwargs) def inner_tag_status_change(instance, **kwargs): """ update the is_updated fields for status_info kwargs is either: kwargs = {'is_obsolete': True} # or {'is_deprecated': True} """ affected = Tag.objects.filter(id=instance.affected_tag.id).first() affected.__dict__.update(**kwargs) affected.save(update_fields=list(kwargs.keys())) I think this is the smallest info I can get in here to make the problem make sense. Let … -
Django Dictionary Issue With API
I have a DJANGO dictionary that I am trying to send via API to another service, however when specifying the keys, I get an error in DJANGO. TypeError: list indices must be integers or slices, not str. Here is the output of my dictionary. "receipt_details": [ { "product__name": [ { "product__name": "Pokemon 25th Anniversary", "quanity": 1, "product__point_price": 100.0, "order_id": 32 }, { "product__name": "Minecraft - Nintendo Switch", "quanity": 1, "product__point_price": 100.0, "order_id": 32 } ], Here is my code on my view, dictionary creation, and API. @login_required def checkoutcomplete(request): customer = request.user order = Order.objects.get(customer= customer , complete = False, ) favorites = Favorite.objects.filter(customer = customer.id) today_date = datetime.datetime.today() today_date_strf = datetime.datetime.strftime(today_date,"%m/%d/%Y" ) items = order.orderitem_set.all() data = items.values("product__name","quanity","product__point_price", "order_id") data_list = list(data) receipt_details = { } for count, data in enumerate (data_list): receipt_details = data_list print(receipt_details) <-- This is at this point a dictionary after the for loop. try: student = Student.objects.get(email = customer.email) counselor = User.objects.get(id = student.counselor_id) points = K8RunningPoints.objects.filter(student_ps = student.studentpsid).aggregate(Sum("running_total"))['running_total__sum'] #POST MARK API url = "https://api.postmarkapp.com/email/withTemplate" payload = json.dumps({ "From": "", "To": "", "TemplateId": 28132290, "TemplateModel": { "counselor_name": "Fellow Counselor", "student_name": student.student_name, "receipt_id": str(order.transaction_id), "date": today_date_strf, "points": order.get_cart_total, "receipt_details": [ { "product__name": receipt_details['product__name'], <-- This … -
Django's DateTimeField is None in serializer
I use DRF and i have Bid model, i have DateTimeField which has auto_now_add and when i send data from Postman accordingly i do not send time. and then i want to validate this time in serializer's validate function but when i call that time, it's None. what i can that receive time in serializer? i send data like this { "user": 12, "product": 5 } this is my code -> class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=_('მომხმარებელი')) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('პროდუქტი')) price = models.IntegerField(default=0) time = models.DateTimeField(auto_now_add=True, verbose_name=_('დრო')) def __str__(self): return self.product.name def save(self, *args, **kwargs): if self.price == 0: self.product.current_price += 1 self.product.save() self.price = self.product.current_price else: self.product.current_price += self.price self.product.save() super(Bid, self).save(*args, **kwargs) view class BidView(generics.ListCreateAPIView): serializer_class = BidSerializer queryset = Bid.objects.all() def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) serializer class BidSerializer(serializers.ModelSerializer): class Meta: model = Bid fields = '__all__' def validate(self, data): all_bids = Bid.objects.filter(product=data.get('product').id).last() print(data.get('price')) <--- this is None if data.get('price'): if data.get('product').current_price > data.get('price'): raise ValidationError({"price_error": "შენი შეთავაზება მიმდინარე ფასზე ნაკლებია"}) return data -
cannot adapt type when using custom field in django admin panel
I'm trying to add custom field to the actor admin panel to show the movie counts each contributed in admin panel.. from django.contrib import admin from actors.models import Actor @admin.register(Actor) class ActorAdmin(admin.ModelAdmin): search_fields = ('actor_name',) list_filter = ('gender',) list_display = ['actor_name', 'age', 'gender', 'movies_count'] readonly_fields = ['movies_count'] def movies_count(self, obj): count = 0 for mv in Actor.objects.raw('select * from movies_movie_actors ' 'where actor_id=' '(select id from actors_actor where actor_name="%s")', [obj]): count += 1 return str(count) movies_count.short_description = 'movie count' but I get error Exception Type: ProgrammingError Exception Value: can't adapt type 'Actor' what does the error mean, why is it show and how to solve it (different approach with the same goal is acceptable) maybe relevant actor model : from django.db import models GENDER_LIST = [('male', 'male'), ('female', 'female')] class Actor(models.Model): actor_name = models.fields.CharField(verbose_name='Name', max_length=25, unique=True) gender = models.CharField(verbose_name='Gender', choices=GENDER_LIST, max_length=6, default='male') age = models.IntegerField(default=0) create_time = models.TimeField(verbose_name='Created at', auto_now=True) update_time = models.TimeField(verbose_name='Updated at', auto_now=True) def __str__(self): return f'{self.actor_name}' movies model : from django.db import models from django.db.models import CASCADE from director.models import Director class Movie(models.Model): movie_name = models.fields.CharField(verbose_name='movie name', max_length=25, unique=True) production_year = models.IntegerField(verbose_name='production year') actors = models.ManyToManyField('actors.actor') director = models.ForeignKey(Director, on_delete=CASCADE, related_name='movies') create_time = models.TimeField(verbose_name='Created at', auto_now=True) update_time … -
DJANGO Dictionary/ JSON
I have a DJANGO dictionary that I am trying to send via API to another service, however when specifying the keys, I get an error in DJANGO. TypeError: list indices must be integers or slices, not str. Here is the output of my dictionary. "receipt_details": [ { "product__name": [ { "product__name": "Pokemon 25th Anniversary", "quanity": 1, "product__point_price": 100.0, "order_id": 32 }, { "product__name": "Minecraft - Nintendo Switch", "quanity": 1, "product__point_price": 100.0, "order_id": 32 } ], Here is my code on how I am creating the dictionary. @login_required def checkoutcomplete(request): customer = request.user order = Order.objects.get(customer= customer , complete = False, ) favorites = Favorite.objects.filter(customer = customer.id) today_date = datetime.datetime.today() today_date_strf = datetime.datetime.strftime(today_date,"%m/%d/%Y" ) items = order.orderitem_set.all() data = items.values("product__name","quanity","product__point_price", "order_id") data_list = list(data) receipt_details = { } I know it's looking for me to specify an index however, I have multiple items I want to send. So what do I do to over come this? Thanks Here is the API info I'm sending. #POST MARK API url = "https://api.postmarkapp.com/email/withTemplate" payload = json.dumps({ "From": "", "To": "", "TemplateId": 28132290, "TemplateModel": { "counselor_name": "Fellow Counselor", "student_name": student.student_name, "receipt_id": str(order.transaction_id), "date": today_date_strf, "points": order.get_cart_total, "receipt_details": [ { "product__name": receipt_details['product__name']['product__name'], <-- Wants me to … -
I want to make a comilation cutter in the browser using only 1 ffmpeg feature
I want to make a website where people can put in compilations and get them automatically cut in to different scenes. This is already possible with PySceneDetect. But the process looks really "back-end-y" I want a process for the frontend where people can drop a file, the file gets processed with PySceneDetect then all the seperate clips get spit out and people can add titles tags and feedback to them so they get sorted and posted on my website. Can someone tell me if this is possible and how? I am not experienced. -
Django better way to avoid KeyError?
I was building a simple weather app with Django. This app allows the user to enter a city name and it will give the weather details of that city. I am using an API to fetch the data. I wanted to avoid KeyError when an user enters an empty string or misspelled a city. I kinda achieved my goal, but I wonder if there is a much easier way to do this. Here is my code: from django.shortcuts import render import requests from datetime import datetime import geonamescache # Used for match checking def home(request): # Checks for legitimate cities if 'search-city' in request.POST: gc = geonamescache.GeonamesCache() while request.POST['search-city'] != '': cities = str(gc.get_cities_by_name(request.POST['search-city'])) if request.POST['search-city'] in cities: city = request.POST['search-city'] break elif request.POST['search-city'] not in cities: city = 'Amsterdam' break while request.POST['search-city'] == '': city = 'Amsterdam' break # Call current weather URL = 'https://api.openweathermap.org/data/2.5/weather' API_KEY = 'c259be852acd2ef2ab8500d19f19890b' PAR = { 'q': city, 'appid': API_KEY, 'units': 'metric' } req = requests.get(url=URL, params=PAR) res = req.json() city = res['name'] description = res['weather'][0]['description'] temp = res['main']['temp'] icon = res['weather'][0]['icon'] country = res['sys']['country'] day = datetime.now().strftime("%d/%m/%Y %H:%M") weather_data = { 'description': description, 'temp': temp, 'icon': icon, 'day': day, 'country': country, 'city': city … -
Does Django 1.9.5 support PostgreSQL 11?
The end-of-life for Postgres 10 on Heroku is closer and closer, but I still have a legacy project on Django 1.9 using it there. Is it possible to migrate to Postgres 11 without troubles? -
How to convert this mysql query to django queryset
I dont know how to do ranking in queryset of ordered by different criterias. How can i convert this sql to queryset ? SELECT t.user_id, t.country_id, t.score, RANK() OVER (PARTITION BY t.country_id ORDER BY t.score DESC) AS countryRank, RANK() OVER (ORDER BY t.score DESC) AS globalRank FROM ( SELECT user_id, country_id, score FROM user_scores WHERE standard = 5 ) AS t LIMIT 50 OFFSET 50; -
classification failed path should be path-like or io.BytesIO, not <class 'django.db.models.fields.files.ImageFieldFile'>
i'm trying to build an image classifier using django and react, here i've build and a drop zone for images and i've got this a dropzone data trasfer in rest my code -
Unable to access the S3 bucket with django: ValueError: Invalid endpoint
I'm trying to integrate S3 Bucket with my django application. But always getting this error. raise ValueError("Invalid endpoint: %s" % endpoint_url) ValueError: Invalid endpoint: <bucket_name>.s3.amazonaws.com These are my settings.py configurations AWS_ACCESS_KEY_ID = config('STATIC_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('STATIC_SECRET_KEY') AWS_S3_REGION_NAME = config('AWS_REGION') AWS_STORAGE_BUCKET_NAME = config('STATIC_BUCKET_NAME') AWS_S3_ENDPOINT_URL = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = 'public-read' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) I have referred the answers here, ValueError: Invalid endpoint: https://s3..amazonaws.com Region is set correct. -
Sync data from api to wagtail
I was wondering if there is an example of how to create or update wagtail page? I would like to sync data from /api/ endpoint to wagtail page. I made an example how create, and it works, but with update I have to change some logic. I tried to add a different primary key and use it to save the id from api but i got an error: Attempted to add a tree node that is already in the database def get_some_data(): products = some_api_endpoint() product_page_content_type = ContentType.objects.get_for_model(Product) language_en = Language.objects.get(code="en") home_page_en = HomePage.objects.get(language=1) product_index_page_en = ProductsPage.objects.descendant_of( home_page_en ).first() for level_1 in products: for level_2 in level_1["general"]: # product_en, _ = Product.objects.update_or_create( # id=level_2["id"], # ) # product_en.language = level_2["id"] # product_en.title = level_2["name"] # product_en.draft_title = level_2["name"] # product_en.code = level_2["id"] # product_en.content_type=product_page_content_type, product_en = Product( # id=level_2["id"], # won't work, must be incremental language=language_en, title=level_2["name"], draft_title=level_2["name"], code=level_2["id"], content_type=product_page_content_type, ) product_index_page_en.add_child(instance=product_en) product_en.save() class Command(BaseCommand): def handle(self, *args, **options): get_some_data() -
How to get current user data in django
I'm trying to get logged user data but I get an only username I try these codes user= User.objects.get(id=user_id) user= User.objects.filter(id=emp_data.user_id).first() user =request.user this 3 query returns username how can i get user details -
How to use multiple SMTP in django_mail_admin (Gmail & Outlook)
We are using django_mail_admin in our project to send and receive emails. Our requirement is to send email on both accounts Gmail and Outlook. 1- Gmail Account will send E-mail to Gmail account using Gmail SMTP 2- Outlook Account will send E-mail to Outlook account using outlook SMTP. NOTE: Switch SMTP is a function to change SMTP according to Gmail and Outlook. Use of single Gmail account :- Gmail is sending Email to Gmail account, Sender and Receiver both from Gmail, working fine. Use of single Outlook account :- Outlook is sending Email to Outlook account, Sender and Receiver both from Outlook, working fine. Use of Gmail and outlook together When we use Gmail and outlook together and we Switch SMTP Gmail to Outlook, then we are facing issue (Sender not changing, Gmail Receive email from Gmail but Outlook Receive email from Gmail) -
Signals don't work when outside MQTT script inserts data to database
I have django project and I have signals in model.py file. I created demo just to show what problem is def func(sender, instance, created, **kwargs): try: if created: print("WORKED") except BaseException as e: import traceback print(traceback.format_exc()) post_save.connect(func, sender=MyTable, dispatch_uid="IDDD") When I insert data from admin panel, everything is OK, it prints,however, when I use simple script which inserts to MyTable, signal does not work, but data is saved to the table.