Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
on opening filefield(contains mp4 video) url , it denies access to it. but only videos not other types like image
my get request in django rest framework returns a url which containes a file(mp4 video) but when i open the url it deny access .but only files which have videos not other types like image or any file(my api is deployed on cpanel host) . but why? how can i fix it?) here is my code: models.py class Videos(models.Model): title = models.CharField(max_length=100, null=True) video = models.FileField(upload_to='videos', null=True) i created a filefield here and i uploaded a video with mp4 format in django admin serializers.py class VideosSerializer(serializers.ModelSerializer): class Meta: model = Videos fields = ('id', 'title', 'video') and this is my views: views.py from rest_framework.generics import ListAPIView from rest_framework.permissions import AllowAny from .serializers import VideosSerializer from .models import Videos class VideosView(ListAPIView): permission_classes = (AllowAny,) serializer_class = VideosSerializer queryset = Videos.objects.all() and in the end urls urlpatterns = [ path('videos', VideosView.as_view(), name='videos') ] when i call the request it gives me the url and it works fine . but when i open the url link it denies access with a 403 forbbiden error and i didn't use any authentication or user . cause i just want to give the url.i don't need authentcation classes . as i told before this happens on … -
How to achieve the Spotify API's authorization code flow with Django and React/Redux?
I have a React/Redux/Django app that I want to integrate with Spotify. Specifically I want to give my app access to the user's playlists and also change the playback in the user's Spotify app or embedded player. I imagine this would be enabled by a "connect to Spotify" button somewhere on the user's profile page, which begins the Authorization flow as stated by the Spotify API. However, I have no idea how I would even begin this process. I tried an axios request as seen in some tutorials, but that just gave me CORS errors. Then I tried a plain old link and now there's a code in my url bar that I have no idea what to do with. Has anyone implemented something similar that I can take a look at or have any advice? Note that I have already done my googling and read all the medium articles, please do not share those with me. -
Unable to find/ import .py file in the same directory Visual Studio Code
I have been all over the internet and spent hours trying to fix this. It may be something pretty straight forward so please cut me some slack. This is my first time using Visual Studio Code. I have already tried the solutions presented in the links below: VS Code - pylinter cannot find module vscode import error for python module Can't get VSCode/Python debugger to find my project modules https://code.visualstudio.com/docs/python/environments My folder structure looks like this: I am trying to run the urls.py file which tries to import the views file using- from . import views But I get the following error: Traceback (most recent call last): File "c:/Users/abc/projects/telusko/calc/urls.py", line 7, in from . import views ImportError: cannot import name 'views' I have tried all possible combinations, and currently my launch.json file looks like this: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal" }], "env": {"PYTHONPATH": "c:/Users/abc/projects/telusko/test/Scripts/python.exe"}, "python.pythonPath": "c:/Users/abc/projects/telusko/test/Scripts/python.exe" } I am using a virtual env to run this project, the env is located at - "c:/Users/abc/projects/telusko/test/" And … -
<audio></audio> tag displays error in Safari and doesn't allow skip in Google-Chrome
I'm using a Django based web application that plays music from a database using the tag in HTML5. This has worked successfully on Firefox, but plays on Google Chrome without allowing any ability to skip through the song, and does not allow any play whatsoever on Safari. Anytime I try, I receive the error below from the audio section. Image from website loaded on safari <div id="beat{{forloop.counter}}"> <img class="image" src="{{beat.artwork.url}}" style="width:100%;" alt="Card image"/> <div class="middle" style="height:100%; top:50%"> <p class="text-white font-weight-bold" style="margin-bottom:0%;">{{beat}}</p> <p class="text-white" style="margin-bottom:0%;">The Island Prince</p> <div style="margin-top:0%; margin-bottom:0%; margin-left:5%; width:90%;"> <audio controls src="{{beat.beatFile.url}}" type="audio/mpeg" style="width:100%;"></audio> </div> <p class="text-white" style="text-align:left; margin-bottom:0%;"> Tags: {% for tag in beat.tag.all %} {{tag}} {% endfor %} </p> <p class="text-white font-weight-bold" style="text-align:center;margin-bottom:0%;">Purchase Today</p> <button type="button" data-product="{{beat.id}}" data-action="add" style="padding-bottom: 10px;" class="btn-lg btn-dark btn-block update-cart">Add To Cart</button> </div> </div> -
Django: Submit button gets triggered twice
Hi, I am making currently a form where the user can edit his profile image. I am trying to delete the profile image that the user had before, after he changes his profile image to a new one. I made so far the scripts, but by the print commans I found out, my submit button(my script) get's triggered twice. Some Informations: I am using Django 3.1 - Python 3.7.2 - JS,Bootstrap from CDN html site code {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Informazioni sul profilo</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Aggiorna</button> </div> </form> <!--form here--> </div> {% endblock content %} models.py from django.db import models from django.contrib.auth.models import User from PIL import Image, ImageChops import os import time # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() # path = 'media/profile_pics/' media_pics = os.listdir(path) img = Image.open(self.image.path) for imgm in media_pics: … -
Time mismatching in admin section
I am buiding an app in Django, it is hosted on Heroku. It gets some data via API and then saves it into a model, with the time and date of the record. This model shows the time and date in its objects name. Last_update_time = models.DateTimeField(blank=False, null=False, default=timezone.now ) def __str__(self): return "%s --- [ %s ]" % (self.Target_area_input_data.Name, datetime.strftime(self.Last_update_time, "%H:%M:%S %d-%m-%Y") ) The information is then displayed in a template. The time displayed in the template is correct (it corresponds to the time displayed by my pc clock, 22:33 in the example), but when I access my model in Django admin, it is two hours earlier (20:33 in the example). The strange thing is that when I access the object fields view, the time is right (22:33 in the example). What could be the problem? In my settings I have: TIME_ZONE = 'Europe/Berlin' USE_TZ = True I tryed to change USE_TZ = False only resulting in the time in the object fields view being two hours earlier (20:33 in the example), like the others, and the message "you are 2 hours ahead from the server time" appearing. It seems that the problem started after I had to reset … -
Change queryset based on query_param
I'm using django-filters, but I've been having some issues using it alongside an annotation. The use case here is that I want the /streams viewset to return only Stream objects with at least 1 ManyToMany to a Tag. class StreamViewSet(viewsets.ModelViewSet): queryset = Stream.objects.annotate(num_tags=Count("tags")).filter(num_tags__gt=0) serializer_class = StreamSerializer filterset_class = StreamFilterSet def filter_queryset(self, queryset): filter_backends = (filters.DjangoFilterBackend,) for backend in list(filter_backends): queryset = backend().filter_queryset(self.request, queryset, view=self) return queryset @action(detail=True, methods=["patch"]) def add_tags(self, request, pk): tag_names = request.data["tags"] stream = Stream.objects.get(pk=pk) for tag_name in tag_names: tag = Tag.objects.get(name=tag_name) stream.tags.add(tag.id) stream.save() return Response(f"Added {len(tag_names)} tags to {stream.id}.") if query_param tagless is False or not provided I'd like to use num_tags__gt=0, but if tagless is True, I'd like to use Stream.objects.all(). I can't seem to figure out how to achieve this result. Any help in the right direction is appreciated. -
What is the difference between the fields associated with choice and to in the django model?
What is the difference between the fields associated with choice and to in the django model? eg what is the difference between frontal and number_of_rooms field What is the difference between defining choice and creating a model and defining the domain of another model? thanks in advance #django models.py class Advertise(models.Model): owner = models.ForeignKey(to="advertise.User", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100) description = models.TextField(max_length=500) price = models.PositiveIntegerField(default=0) square_meter = models.PositiveIntegerField(default=0) number_of_rooms = models.PositiveIntegerField(choices=NumberOfRoomsChoices.CHOICES) building_age = models.PositiveIntegerField(choices=NumberOfBuildingAgeChoices.CHOICES) floor = models.PositiveIntegerField(choices=NumberOfFloorChoices.FLOOR_CHOICES) number_of_floors = models.PositiveIntegerField(choices=NumberOfFloorChoices.FLOORS_CHOICES) number_of_bathrooms = models.PositiveIntegerField(choices=NumberOfBathroomsChoices.CHOICES) heating = models.PositiveIntegerField(choices=HeatingChoices.CHOICES) balcony_exists = models.BooleanField(default=False) using_status = models.PositiveIntegerField(choices=UsingStatusChoices.CHOICES) fee = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.PositiveIntegerField(choices=AdvertiseStatusChocies.CHOICES) visibility = models.PositiveIntegerField(choices=AdvertiseVisibilityChoices.CHOICES) # collections frontal = models.ManyToManyField(to="advertise.Frontal") interior_feature = models.ManyToManyField(to="advertise.InteriorFeature") exterior_feature = models.ManyToManyField(to="advertise.ExteriorFeature") locality = models.ManyToManyField(to="advertise.Locality") transportation = models.ManyToManyField(to="advertise.Transportation") landscape = models.ManyToManyField(to="advertise.Landscape") sutiable_for_disabled =models.ManyToManyField(to="advertise.SuitableForDisabled") def __str__(self): return f"{self.title}" -
my django 3 project is shwoing 'ModelForm has no model class specified'
i am a beginner django developer, "ModelForm has no model class specified. " is given on my project , what i can do pls help, i will be greatfull to you if you solve my problem models.py from django.db import models class product(models.Model): name = models.CharField(max_length=50) forms.py from django.forms import ModelForm from .models import product class productform(ModelForm): class Meta: model:product fields: '__all__' views.py from django.shortcuts import render from formt.forms import productform def index(request): form = productform() context = { 'form' : form } return render(request, 'index.html' , context ) index.html <h1>form model</h1> <form action=""> {% csrf_token %} {{form}} <input type="submit" text="submit"> </form> -
Django Rest Framework: Creating a custom create method for a writable nested presentation
I'm trying to create a custom create method for a hyperlinked model serializer in Django Rest Framework. I'm following the documentation on how to create said method. The issue I'm having is that none of the data from the foreign key relation is being validated. The data itself is coming through (I can check this by printing self in the serializer), but in the validated data "Skills" ends up being an empty ordered dict. I'll show an example of this below, after presenting my models, serializers, views and urls. Here's my model. It's modeling a work experience entry in a resume: class WorkExperience(models.Model): title = models.CharField(max_length=256, default="Title") description = models.TextField(default="Description of the work") organization = models.CharField(max_length=256, default="Acme Inc.") start_date = models.DateField(null=True) end_date = models.DateField(null=True) skills = models.ManyToManyField(Skill, related_name="work") owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) resume = models.ForeignKey( Resume, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) def __str__(self): return f"{self.owner.email} work experience as {self.title}." class Meta: ordering = ["id"] My Serializer for the model looks like this: class WorkExperienceSerializer(serializers.HyperlinkedModelSerializer): skills = SkillSerializer(many=True) class Meta: model = WorkExperience fields = [ "title", "description", "start_date", "end_date", "organization", "skills", ] def create(self, validated_data): print("print self: ", self) # Here I'm printing self print("print … -
Nginx not serving staticfiles correctly on docker?
I want nginx to act as a reverse proxy and serve static files for django (api). docker-compose.yml: version: '3' services: api: build: api container_name: api volumes: - static_volume:/home/admin/api/static ports: - "8000:8000" env_file: - ./config/api/.env depends_on: - db db: image: postgres:latest container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./config/api/.env-db nginx: image: nginx:latest container_name: ngx volumes: - static_volume:/home/admin/api/static - ./config/nginx:/etc/nginx/conf.d ports: - "80:80" depends_on: - api volumes: postgres_data: static_volume: config/nginx/default.conf: upstream refridge { server api:8000; } server { listen 80; location / { proxy_pass http://refridge; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { autoindex on; alias /home/admin/api/static/; } } After spinning them up with docker-compose up -d --build and running django's migrate and collectstatic command, I see the following logs when trying access django's admin page: docker logs api Waiting for postgres... PostgreSQL started [2020-08-17 20:26:04 +0000] [1] [INFO] Starting gunicorn 20.0.4 [2020-08-17 20:26:04 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2020-08-17 20:26:04 +0000] [1] [INFO] Using worker: sync [2020-08-17 20:26:04 +0000] [30] [INFO] Booting worker with pid: 30 [2020-08-17 20:26:04 +0000] [31] [INFO] Booting worker with pid: 31 [2020-08-17 20:26:04 +0000] [32] [INFO] Booting worker with pid: 32 Not Found: /static/admin/css/responsive.css Not Found: /static/admin/css/login.css Not Found: /static/admin/css/base.css … -
ModuleNotFoundError: No module named 'profiles.url'
Can anyone tell why it's showing ,my code is correct. view.py from django.shortcuts import render from django.http import HttpResponse def test_view(request): string = "hello world" return HttpResponse(string) url.py from django.urls import path from .views import test_view app_name = 'profiles' urlpatterns = [ path('',test_view, name ='test-view-1') Two errors first error is `ModuleNotFoundError: No module named 'profiles.url'` second error is [1]: https://i.stack.imgur.com/LfY0J.png -
Django - override existing data, after admin approval?
I have been tasked with adding some new functionality to an existing view. Basically, on user signup if the company is already in the database, I am sending an email to an admin, saying "User wants to claim company". If admin approves, that user will be added to the company, and I want to override the previous info (address, phone, etc.) with the info this user put in at registration. I thought the best way to do this was to add a field to the Account model, called is_approved and set it to False, and when the admin approves, they will set it to True and the new info will be stored, overriding the existing data. I have a Company model, and a Pending_Companymodel, both with the same exact info. My view... company_obj = Company.objects.filter(I am filtering the DB here) if not company_obj: """If no company match, create new one""" new_company = Company.objects.create( name=company.title(), zip=int(zip_code), primary_email=email, website=website, phone_no=phone_no, street=street, city=city, state=state, ) new_company.owner.add(user) else: """Add employee to company, send email to admin for approval, if approved, update company instance with new data.""" # If DEBUG = True send_mail('Test Subject', 'Test message', 'test@gmail.com', ['testemail@gmail.com', ], fail_silently=False) pending_company = PendingCompanyDetail.objects.create( name=company.title(), zip=int(zip_code), … -
vscode devcontainer causes "The folder you are executing pip from can no longer be found."
I have a docker containerized Django project. I also use vscode devcontiners. If I don't start vscode with its associated devcontainer I am able to run management commands from the terminal like this: docker-compose run manage migrate But if I open vscode and start programing within the devcontainer the next time I try to run the management command I get this error: The folder you are executing pip from can no longer be found. The odd thing is that I am still able to run other docker commands from the terminal without issue such as this: docker-compose run --rm tests Of note this was not always the case. I say it probably started around 3 months ago. The only other time I've heard about this error happening before when a container is started with "delegated" volumes. I’m not sure if vscode uses delegated volumes or not. May be able to add more files to this post if nessisary. -
Django DRF calculated fields check
I want to check if the computational values coming from the frontend to the price table are correct. E.g; The discount added to this by giving the Sales Price, the early booking discount is reduced to CostPrice. The difference between CostPRice and SalesPrice gives profiRate. The webFakePrice is calculated by calculating the salesPrice * webFakePriceRate for the price to be fake on the web. I want to check if these FrontEnd are calculated correctly. I could not find a keyword for it. How should I loop this since there are multiple record in one? Model.py salesPrice = models.FloatField (blank = True, null = True) costPrice = models.FloatField (blank = True, null = True) commissionRate = models.FloatField (blank = True, null = True) discountRate = models.FloatField (blank = True, null = True) earlyBookingRate = models.FloatField (blank = True, null = True) totalCommission = models.FloatField (blank = True, null = True) profitRate = models.FloatField (blank = True, null = True) webFakePriceRate = models.FloatField (blank = True, null = True) webFakePrice = models.FloatField (blank = True, null = True) view.py def create (self, request, * args, ** kwargs): many = True if isinstance (request.data, list) else False serializer = PriceSerializer (data = request.data, … -
Getting the post instance in Django class based views
I currently use a function based view to let users write comments on posts, but I'm trying to convert it to class based views Function views.py def comment(request, pk): form = CommentForm(request.POST) # Post instance post_instance = get_object_or_404(Post, pk=pk) if request.method == 'POST': if form.is_valid: obj = form.save(commit=False) obj.commenter = request.user obj.post = post_instance obj.save() return redirect('/') else: messages.error(request, 'Comment Failed') return render(request, 'comment.html', {'form': form}) Class views.py class CommentView(FormView): template_name = 'comment.html' form_class = CommentForm success_url = '/' def get_object(self): pk = self.kwargs.get('pk') post_instance = get_object_or_404(Post, pk=pk) return post_instance def form_valid(self, form): obj = form.save(commit=False) obj.commenter = self.request.user obj.post = post_instance obj.save() return super().form_valid(form) I'm trying to implement the same logic for saving the comment but I get the error: name 'post_instance' is not defined get_object() is returning the 'post_instance' variable but I can't access it. Could you guys show me where I'm doing a mistake, thanks in advance! -
Which SQL paradigm to use when grouping counts by type?
Let's say I have a database with data from a pizza shop in it. I keep track of customers and their orders via two tables: customer and orders. orders has a FK to customer so that I can easily see which orders belong to which customer. I can count all of the customer's orders like this: SELECT c.id, COUNT(o.id) AS order_counts FROM customers AS c, JOIN orders ON c.id = o.customer_id GROUP BY c.id Which gives me something like this: results = [ { “customer_number”: 1, “order_counts”: 5 }, { “customer_number”: 2, “order_counts”: 10 }] However, what if I want to "explode" the order_counts results to show me all the individual pizza types, and then count those types? I would add a new table called pizzas which has a name column, and then get my results to look like this: results = [ { “customer_number”: 1, “counts”: { “Hawaiian”: 2, “Meat Lovers”: 2, "Four Cheese": 1 } }, { “customer_number”: 2, “counts”: { “Hawaiian”: 5, “Meat Lovers”: 5, "Four Cheese": 0 } }] Which SQL principals/paradigms would I need to leverage to achieve this? I suspect I need a subquery and/or a nested GROUP BY statement. Bonus Question: is this … -
Getting 'RelatedObjectDoesNotExist' error in Django when I edit a field in my admin page
I am trying to create dynamic detail pages for my ecommerce website in django. I added a slug field in my models.py file and migrated it. However, when I edit my slug field in the admin page I get the follwoing error. [Error.] [1]: https://i.stack.imgur.com/EMu9U.gif [code for models.py] https://i.stack.imgur.com/SZVj0.png Is there a step I missed? -
given a date start and date end, give me the duration in an array of 24 values corresponding to hours of the day
I am very new to Django rest framework and stack overflow even, I was struggling with finding a title so please feel free to give a better alternative. I have a set of jobs that get posted to a database. the jobs are now grouped per machine and per given hour. For now I am only displaying the total count of jobs per hour. My API end point looks like this now : Api end point Here's where I am struggling: I need to get the duration of the job separated by hour. I have a Datetime when it started and a Datetime when it ended. I also have a total of the duration. For example: suppose a job starts at 11h15 and ends at 12h15. this would mean that for hour 11 the total duration is 45 minutes. For hour 12, the duration is 15 minutes. I thought of getting the time passed between 11h15 and 12h00 and then the time passed between 12h15 and 13h00. But I am not exactly sure how i could do this. also note that some jobs go for more than an hour and some even more than a day. I am sure there … -
Django .create() for each item in queryset? Like: Reporter.objects.all().article_set.create(...)
https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_one/, Taking Django's Reporter/Article as a comparable example for my real problem, i need to create one new article for each reporter in my queryset. My approach now is as follows: reporters = Reporter.objects.filter(...) for reporter in reporters: article = Article() article.reporter = reporter ... article.save() The problem is that i have 25k "reporters", so it takes too long to process the request and raises timeout. I wonder if there is a better method for that, sort of like: Reporter.objects.filter(...).article_set.create(...) -
django postgresql timestamp on entry creation is not ordered in the database
I am quite new to django and I have a small app, with the following models: class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class SomeModel(TimeStampedModel): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) some_json = JSONField(blank=True,default=dict) def __str__(self): return self.uuid I now make some requests to a webserver and write the return value of the request to the database via model forms like so: data = requests.get(BASE_URL) form_data=collections.OrderedDict() form_data[ "some_json" ] = data.json() form = SomeModel (form_data) if form.is_valid(): form.save() logger.debug( "***** GOOD: form saved from %s", data.json() ) else: logger.debug("** form not valid because: %s ", form.errors) pass It seems to work fine, but when I inspect the database I see that the timestemps are not ordered :( So, the top 5 entries on the database look like so (for the created_at field): 2020-08-17 19:59:14.377394+01 2020-08-17 19:58:31.017813+01 2020-08-17 20:00:33.302018+01 2020-08-17 19:59:57.626536+01 2020-08-17 19:59:07.671274+01 I am baffled as to how the database can write in non-ascending time stamps.. Am I missing something here? Shouldnt the database contain ordered values for the created_at field? My naive thinking leads me to think: [1] I make the rerquest and get data [2] write data to database this process should create … -
Django ORM uses wrong string searching for foreign object
I have two models: Account and SourceDocument (posted below). When I create a SourceDocument, I first get the correct Account, set it to the SourceDocument.account field and then save SourceDocument. The expected result is for SourceDocument.account to be the same as the Account object I queried. However, it's using the wrong string to search for the object during .save() and the ORM is trying to search using Account.code. The string used to find the object was correct a couple of weeks ago. It has since changed. At first, I thought there was an issue with Postgres. I did REBUILD TABLE accounting_account and REBUILD DATABASE with no change. Originally, the Account.code field was unique so I removed the index with no change. Using the helpful debugsqlshell command from django-debug-toolbar, I've found the issue likely lies within the Django ORM, but I'm not sure where. Here's the debugsqlshell testing I did: >>> from accounting.models import * >>> a = Account.objects.get(is_receivable=True) SELECT "accounting_account"."id", "accounting_account"."code", "accounting_account"."name", "accounting_account"."description", "accounting_account"."type", "accounting_account"."is_payable", "accounting_account"."is_receivable", "accounting_account"."is_bank", "accounting_account"."allow_payments" FROM "accounting_account" WHERE "accounting_account"."is_receivable" LIMIT 21 [1.99ms] >>> a.pk 11 >>> a.code '1210' >>> s = SourceDocument() >>> s.account = a >>> s.save() SELECT "accounting_account"."id", "accounting_account"."code", "accounting_account"."name", "accounting_account"."description", "accounting_account"."type", "accounting_account"."is_payable", "accounting_account"."is_receivable", "accounting_account"."is_bank", … -
How to pass variable to TabularInline admin template?
I need to add a few custom rows (which are different model) to admin inline so that everything looks seamlessly as one table. My idea was to include admin/edit_inline/tabular.html in new template and add a custom table below. Then I'd create a custom admin view that would handle saving etc. My issue is that I cannot find a way to pass any variable to InlineModelAdmin template - I thought any variable at top level in class is available in template via {{ variable }} tag - this way I could pass my table structure to template and generate it there. -
Django App deployed to EB Could not translate host name
I tried to send an email after an user object gets created. I use celery to perform the task. My application was deployed to AWS Elastic Beanstalk (Linux2 Python3.7). I have one RDS configured for my environment. Whenever I created a new user, my celery worker got the same error as follow: This is the error I got in celery-worker.log [2020-08-17 10:51:20,667: INFO/MainProcess] Received task: account.tasks.send_user_email_when_user_created_by_admin[0c202693-43b7-44b7-a9b9-0362bc38afac] [2020-08-17 10:51:20,675: WARNING/ForkPoolWorker-1] Sending email for new usr [2020-08-17 10:51:20,693: ERROR/ForkPoolWorker-1] Task account.tasks.send_user_email_when_user_created_by_admin[0c202693-43b7-44b7-a9b9-0362bc38afac] raised unexpected: OperationalError('could not translate host name "aa1rm1r9klym9tk.ce9nktrqundw.us-west-2.rds.amazonaws.com" to address: Name or service not known\n') Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/var/app/venv/staging-LQM1lest/lib64/python3.7/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "aa1rm1r9klym9tk.ce9nktrqundw.us-west-2.rds.amazonaws.com" to address: Name or service not known This is the code I used for sending an email to user @receiver(post_save, sender=User) def create_profile_handler(sender, instance, created, **kwargs): if created: profile = models.Profile(user=instance) profile.save() transaction.on_commit(tasks.send_user_email_when_user_created_by_admin.delay(instance.id)) I don't know where this host name came from as I couldn't find such rds under my account. I did the nslookup aa1rm1r9klym9tk.ce9nktrqundw.us-west-2.rds.amazonaws.com 8.8.8.8 and … -
Django rest api custom class implementation
I have created a class for retrieving data about a specific food product from farsecret API. In class I have created 3 functions for: *obtaining authorization *getting id of item, for which we are looking *download data of item class IngredientImport(APIView): def get_authorization_token(self): request_token_url = "https://oauth.fatsecret.com/connect/token" consumer_key = os.environ.get('NTS_Client_ID') consumer_secret = os.environ.get('NTS_Client_Secret') data = {'grant_type':'client_credentials', "scope":"basic"} access_token_response = requests.post( request_token_url, data=data, verify=False, allow_redirects=False, auth=(consumer_key, consumer_secret) ) return access_token_response.json()["access_token"] def get_list_by_name(self, name, access_token): api_url = "https://platform.fatsecret.com/rest/server.api" params={ "method":"foods.search", "search_expression":name, "page_number":1, "max_results":1, "format":"json" } header = {"Authorization":access_token} api_call_headers = {"Authorization": "Bearer " + access_token} response = requests.get( api_url, params=params, headers=api_call_headers ) items = response.json()["foods"] try: return response.json()["foods"]["food"]["food_id"] except KeyError: return None def import_item(self, item_id, api_token): if item_id == None: return None api_url = "https://platform.fatsecret.com/rest/server.api" params={"method":"food.get", "food_id":item_id, "format":"json"} api_call_headers = {"Authorization": "Bearer " + access_token} response = requests.get( api_url, params=params, headers=api_call_headers ) item = response.json()["food"]["servings"]["serving"] item_name = response.json()["food"]["food_name"] if type(item) == list: item = item[0] try: portion_size = float(item["metric_serving_amount"]) carbs = round(float(item["carbohydrate"]) / portion_size * 100, 2) fats = round(float(item["fat"]) / portion_size * 100, 2) proteins = round(float(item["protein"]) / portion_size * 100, 2) except KeyError: return None How can I implement this class in my aplication to avoid creating 3 different paths in …