Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery can't connect to aws RDS and instead using 127.0.0.1
I have a django app running on Elastic beanstalk with celery and redis. The celery task that is failing is to process a photo and save some results in the database (which is a postgres RDS) and it's failing because it's trying to connect to the database on localhost:5432. I have a debug task which doesn't interact with the database and I can see that it is received and executed. My settings file has the following ALLOWED_HOSTS = [ "localhost", "127.0.0.1", ".elasticbeanstalk.com", ] if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'woodpecker', 'USER': os.environ.get("DB_USER"), 'PASSWORD': os.environ.get("DB_PASS"), 'HOST': 'localhost', 'PORT': '', } } CELERY_BROKER_URL = 'redis://localhost' celery config file from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') # DON'T FORGET TO CHANGE THIS ACCORDINGLY # os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1') app = Celery('myapp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I'm still having a problem running celery with supervisord so for now I do the following to start celery after logging to the ec2 instance source /opt/python/run/venv/bin/activate cd /opt/python/current/app/ celery worker -A myapp --loglevel=DEBUG a … -
TypeError in Diffie Hellman using Django and JQuery
I'm trying to develop Diffie Hellman using Django and JQuery, not a full-fledged website, but just to practice and demonstrate Diffie Hellman. Here is my HTML/Javascript code. function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } var BigInt1 = window.bigInt; var x = BigInt1(getRandomInt(17)); var prime = BigInt1('{{ prime_num }}'); var base = BigInt1('{{ base_num }}'); console.log("Prime:" + prime.value + "\n", "Base: " + base.value + "\n", "Private Key:+" + x + "\n") // Diffie Hellman $(function(event) { var level1KeySelf = base.modPow(x, prime); console.log("Level1 " + level1KeySelf.value); var key; $.ajax({ type: 'GET', url: "{% url 'Shenzen:diffiehellman' %}", data: { step: 'calcval', level1: level1KeySelf }, success: function(data, status, xhr) { var level1KeyOther = BigInt1(data['firstkey']); key = level1KeyOther.modPow(x, prime); $("#keyid").attr("keyval", key); }, error: function(xhr, status, e) { console.log("error"); }, async: true, datatype: 'json' }); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="keydiv" id="keyid" keyval="" hidden></div> Here is my Django View: def diffiehellman(request): bytes_y = os.urandom(32) y = int.from_bytes(bytes_y,'little') if request.method == 'GET': step = request.GET['step'] if step == 'calcval': level1KeySelf = pow(base_num,y,prime) level1KeyOther = request.GET['level1'] key = pow(level1KeyOther,y,prime) return JsonResponse({'firstkey':level1keySelf}) elif step == 'success': return JsonResponse({'success':'success'}) return HttpResponse('') else: return HttpResponse('failed! require a GET request.') I get the following TypeError in Firefox signin is a view … -
Django: TypeError Missing 1 required positional argument
So I am working on my first python project using django. It's a simple first project that shows methods of POST, GET, PUT, and DELETE. I've gotten the methods of POST and PUT down. But PUT is not working out the way I thought it would work. So I have a database of information with simple info like first name, last name, and a e-mail. I have two functions in my views with one that renders a page of the database of information and one that links to a page that "updates/edits" that one specific instance of info. So here is my model: class Information(models.Model): """Placeholder code that the viewer will be seeing.""" info_id = models.AutoField(primary_key=True,unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) e_mail = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return information.""" return f"Info ID: {self.info_id}, First Name: {self.first_name}, Last Name: {self.last_name}, E-mail: {self.e_mail}" Here is my urls: # Page(s) that shows the viewer an example of PUT. path('PUTData/', views.put_data, name='put_data'), # Page that shows all info. path('PUT/', views.put, name='put'), Here is my views with the two functions: def put_data(request): put_data = Information.objects.order_by('date_added') context = {'put_data': put_data} return render(request, 'just_projects/put_data.html', context) def put(request, info_id): info = Information.objects.get(id=info_id) if request.method != … -
What is the significance of numbers written in django server along with GET?
I am building a django website and i noticed that within my server there often occur several lines like - [28/Jul/2019 22:52:24] "GET /media/images/product_images/Q0jsuTaUwKhgOhhO.jpg HTTP/1.1" 200 2981629 In lines like these what does the number 200 and 2981629 signify? Also, does printing of these lines in my command line slow my server? -
How to get the path to a FieldField considering the upload_to() function
I am making an app with Django and I am working with an ImageField. I have this function as the upload_to argument: def group_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/group_<id>/time/<filename> return 'Groups/group_{0}/{1}/{2}'.format(instance.id, get_time(), filename) However, I want to resize the group image, so I need to access the group.photo ImageField FieldFile. My problem is that when try to get the FieldFile path with group.photo.path, I get /media/429760_490645240984035_288529563_n.JPG but I there is no file in this directory, because the file is in /media/Groups/group_2/2-3-2019-23-54/429760_490645240984035_288529563_n.JPG instead. How do I get the right file path? -
I make tags to articles, but they do not appear on the page
I have a function that processes the request by tags and sorts articles with similar tags and displays them in a template. But for some reason, they simply do not appear on the page. I fill them in the model using TaggableManager PS tags should appear on the article and when I click on them, the request should be processed and execute the post _search function and sent to the page with articles with similar tags. models.py class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value") tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') view = models.IntegerField(default='0') datesArticle = models.DateTimeField(auto_now=True) class Meta: ordering = ['-datesArticle'] def __str__(self): return self.title views.py def ArticleDetailView(request, pk): Articles.objects.filter(pk=pk).update(view=F('view') + 1) Articles.objects.all() article_details = Articles.objects.filter(pk=pk).first() if request.method == 'POST': comment_form = Comments(request.POST) comment_form.save() else: comment_form = Comments() commentss = CommentModel.objects.all() return render(request, 'news/post.html', {'article_details': article_details, 'comment_form': comment_form, 'comments': commentss, }) def tags_list(request, tag_slug=None): object_list = Articles.objects.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first … -
how to add two class as ForeignKey at a time in one fiield in django?
In models: team_player = models.ManyToManyField(FirstTeamPlayer and SecondTeamPlayer, blank=True, related_name="team_player_set") why don't it possible?? I only get SecondTeamPlayer this queryset data. how can i get these two class in here?? -
How correct initialize a class instance using kwargs
I try to initialize a class with ihertitance structure. I already read a lot of questions here, but still can't figure out how should I do this. My model: class BaseCrudEntity(models.Model): pass class Meta: abstract = True class Person(BaseCrudEntity): Name = models.CharField(max_length = 255) def __init__(self, *args, **kwargs): if args: self.Name = args super().__init__(self, *args) pass And here I call it: p = Person("Test2") p.save() As a result I have an error: int() argument must be a string, a bytes-like object or a number, not 'Person' Here my traceback: http://dpaste.com/2BJFF38 How should I initialize class instance? Why in shell I see None: >>> from person.models.person import * >>> p = Person('Tttt') >>> p <Person: Tttt None> What am I doing wrong? -
static Invalid block tag inside template file
I'm having the invalid block tag issue while trying to reference the styles.css file from my app file structure, even having configured everything as the django documentation (and several other answers here in stack overflow) . I'm using django 2.2.3 in a python3.6 venv along with pureCSS lib. Here's an overview of my project's files and configuration regarding the templates and the static dir/files: 1- settings.py INSTALLED_APPS and STATIC_URL definition: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pyonlinecourses.core', ] ... STATIC_URL = '/static/' 2- settings.py TEMPLATES definitions: TEMPLATES_DIR = os.path.join(BASE_DIR, "pyonlinecourses/core/templates/") TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], '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', 'django.core.context_processors.static', ], }, }, ] 3- Django project directory structure: - pyonlinecourses - core - migrations - static - css - templates - home **(issue located in this file)** 5- static tag definition and reference in html file <!doctype html> {& load static &} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="PyOnline Courses - Simple distance education virtual learning environment" /> <title>PyOnline MOOC</title> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css"> <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> </head> I'm at a loss trying to identify the source of the … -
How can I nest a serializer before it is being defined?
I have these serializers class OrderItemSerializer(serializers.ModelSerializer): product = ProductSerializer(read_only=True) order = ??????????????? class Meta: model = OrderItem exclude = ['id'] class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True, read_only=True) url = serializers.HyperlinkedIdentityField( lookup_field='slug', view_name='api:order-detail') class Meta: model = Order fields = '__all__' I need to use OrderSerializer inside the OrderItemSerializer but if I do so it doesn't work because of the OrderSerializer did not get defined yet. right now I get this result when I query for the Order item. { "price": "334.00", "quantity": 1, "order": 1 } and the wanted behavior is to get the serialized order object instead of the primary key but without losing the order_items inside of the OrderSerializer -
merge/remove elements from a ManyToMany relationship (using through table) when saving model
I'm developping an app to manage commands for a restaurant. as the commands can evolve through the diner, for more clarity, I want to merge the command's lines that contain the same product. For instance, if you command 2 buckets of chicken, then later another one, I want the final Command model instance to contain only one line (bucket of chicken, 3) instead of two. I have a function (fusion_atoms) which detects similar lines and merge them. I tried to call it in the save method of Command model, and also during pre_save and post_save signals. It doesn't work. I'm quite a noob in python and django, and I think I'm not doing this the right way. models.py: class Command_Atom(models.Model): command = models.ForeignKey("Command", on_delete=models.CASCADE) produit = models.ForeignKey(Produit, on_delete=models.CASCADE) quantite = models.PositiveSmallIntegerField(default=1) @property def total(self): return self.produit.prix * self.quantite class Command (models.Model): client = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) table = models.PositiveSmallIntegerField(default=0) produits = models.ManyToManyField(Produit, through="Command_Atom") @property def atoms(self): return Command_Atom.objects.filter(command_id=self.id) def fusion_atoms(self): lines = self.atoms.all().order_by('produit','prod_options') i = 1 current_line = lines[0] to_be_deleted = [] while i < len(lines): if current_line.produit == lines[i].produit: print('merge') current_line.quantite += lines[i].quantite current_line.save() to_be_deleted.append(lines[i]) else: current_line = lines[i] i += 1 for l in to_be_deleted: l.delete() def save(self): … -
TypeError at /api/register/ argument should be a bytes-like object or ASCII string, not 'InMemoryUploadedFile'
I am trying to upload an image in my project and I am trying a solution for it. I have made some changes in the views.py but I am continuously getting the above error. What is wrong in my code? Please help as I am new to rest. class UserCreate(generics.ListCreateAPIView): serializer_class = UserProfileSerializer queryset = UserProfile.objects.all() parser_classes = (FormParser,MultiPartParser) def post(self, request): print(request.data) serializer= UserProfileSerializer(data=request.data) if serializer.is_valid(): imgstr64=serializer.validated_data['avatar'] imgdata = base64.b64decode(imgstr64) fname = '/tmp/%s.jpg'%(str(Userprofile.id)) with open(fname,'wb') as f: f.write(imgdata) imgname = '%s.jpg'%(str(Userprofile.id)) UserProfile.avatar.save(imgname,File(open(fname,'r'))) os.remove(fname) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Cannot reset migrations in Django project?
What I did: Delete db.sqlite3 file. Delete all files in migrations folder (including init file) Then command in cmd: python manage.py makemigrations No changes detected python manage.py migrate Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK But migrations folder is still empty. I have some models in models.py, also tried to add new row to some of them, but result was the same. What I'm doing wrong? -
Using regrouped variable of django template in javascript
From my view function, I have sent some data to django template. In the template, data are grouped using regroup method. {% regroup data|dictsort:"month" by month as data_month_list %} Is there any way to use the data_month_list in javascript? -
TypeErrorat /blog/21- detail() got an unexpected keyword argument 'blog_id'
I'm making a tool for my project. My final object is this:When I type a title, body in new.html page, it works through create.html and finally, gets all of information from new.html in detail.html page. I created two apps, each good(writing works) and account(sign in works). But I faced with "detail() got an unexpected keyword argument 'blog_id'" problem and can't find any solutions. I run this in Visual studio code and I'm now trying to insert def detail(request): details = get_object(Good, pk= blog_id) return redner(request, 'detail.html', {'details':details}) what I have to do after this if it's right? home.html {% extends 'base.html' %} {% block contents %} <body> </body> {% endblock %} urls.py from django.contrib import admin from django.urls import path import good.views import account.views urlpatterns = [ path('admin/', admin.site.urls), path('', good.views.home, name="home"), path('login/', account.views.login, name="login"), path('signup/', account.views.signup, name="signup"), path('new/', good.views.new, name="new"), path('create/', good.views.create, name="create"), path('blog/<int:blog_id>', good.views.detail, name="detail"), ] models.py from django.db import models class Good(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') body = models.TextField() def __str__(self): return self.title admin.py from django.contrib import admin from .models import Good admin.site.register(Good) views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Good from django.utils import timezone def home(request): return render(request,'home.html') def new(request): … -
Form doesn't save but returns 200
I want to create an object of item and save it to the database through a form i wrote. Right now I'm able to update it from my form also admin panel works i can create item from there. However, create form not saving. When i click the button, it refreshes the page, returns 200 in terminal but doesn't save it. I'm putting every part of it, i checked a lot but not seeing any error. This is my model. class Item(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='items') name = models.CharField(max_length=50) description = models.TextField(max_length=250) price = models.FloatField() picture = models.ImageField(upload_to='item_pictures') is_available = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, related_name='category') slug = models.SlugField(unique=True, null=True, blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) return super(Item, self).save(*args, **kwargs) def __str__(self): return self.name My url path('item/create/', ItemCreateView.as_view(), name='item-create'), My view class ItemCreateView(LoginRequiredMixin, CreateView): model = Item fields = ['name', 'description', 'price', 'picture', 'is_available', 'category', 'slug' ] template_name = 'item/item_update.html' success_url = '/' Success url return home page, but form only refreshes And form class ItemCreateForm(forms.ModelForm): class Meta: model = Item fields = ['name', 'description', 'price', 'picture', 'is_available', 'category', 'slug'] Lastly template just in case {% extends "base.html" %} {% … -
How to override PasswordResetConfirmView? (django.contrib.auth.views)
I tried: class CustomPasswordResetConfirmView(PasswordResetConfirmView): form_class = CustomSetPasswordForm but it raises TypeError:__init__() takes 1 positional argument but 2 were given -
How to address to app url in django URL field?
I want to make a dynamic toolbar for a website, this toolbar can have custom websites urls and also should have links to same website's apps. for example there is a search app in django project. website url is not fixed, so like how django uses urls names in HTML file (like : {% url 'name' %}), I want to use same name in model field to access to the apps. This is my toolbar menu object class main_menu_item(models.Model): name = models.CharField(max_length=10,default=None) url = models.URLField(default=None) text_color = models.CharField(max_length=7,default=None) background_color = models.CharField(max_length=7,default=None) def first_letter(self): return self.name[0].upper() -
How can I redirect to use the new context not the origin context with django?
I use a decorator to check whether the user is logged in, and redirect to the login page and remind the user. I want to use context parametric rendering template. How can I write the code? def check_login(func): def wrapper(request, *args, **kwargs): if request.session.get("unique_id"): return func(request, *args, **kwargs) else: context = {'title': 'login', 'not_login': 1} return redirect(reverse('login'), context=context) return wrapper # view.py def login(request): context = {'title': 'login', 'not_login': 0} return render(request, 'login.html', context) The code like this. If user get the login page, templates use not_login=0, if the request is from redirect, templates use not_login=1. -
Cannot apply makemigrations to model after modifying
I implemented a model for my Django app in models.py. Everything worked fine. Then I tried adding a new property to the class. If I now run "makemigrations" I get the error "table movieapp_movie_class has no column named show_movie". I thought that running makemigrations was the command to add this column to the table. I've tried deleting db.sqlite3 and the migration-folder in the app-folder which did not work. from django.db import models # Create your models here. class movie_class(models.Model): show_movie = models.CharField(max_length=100) # this is the new property I wanted to add movie_id = models.CharField(max_length=100) title = models.CharField(max_length=100) rating = models.CharField(max_length=100) poster = models.CharField(max_length=100) -
Django Rest Framework - issue with DELETE - CSRF not found
I'm using Django Rest Framework with CSRF. POST and PUT methods work as expected, but DELETE is giving error 403 with - following message "{"detail":"CSRF Failed: CSRF token missing or incorrect."}. It appears that frontend application (Angular) is doing a proper POST and PUT requests. I'm not getting any issues with CSRF nor CORS. Example: DELETE Request: Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,pl;q=0.8 Cache-Control: no-cache Connection: keep-alive Cookie: _ga=GA1.1.1418236812.1564012825; _gid=GA1.1.747517255.1564126213; sessionid=zho7t6c8vbot46uuwka8ufh53pkanein; _gat_gtag_UA_127399308_1=1; X-XSRF-TOKEN=hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp Host: 127.0.0.1:4200 http-x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp Origin: http://127.0.0.1:4200 Pragma: no-cache Referer: http://127.0.0.1:4200/cost_center/form/e503dbfd-8eae-49e4-becc-4aa60016b996 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp DELETE Response headers: HTTP/1.1 403 Forbidden X-Powered-By: Express access-control-allow-origin: http://127.0.0.1:4200 date: Sun, 28 Jul 2019 14:36:12 GMT server: WSGIServer/0.2 CPython/3.7.3 content-type: application/json vary: Accept, Origin, Cookie allow: GET, PUT, DELETE, HEAD, OPTIONS x-frame-options: SAMEORIGIN content-length: 58 access-control-allow-credentials: true connection: keep-alive DELETE Response: Request URL: http://127.0.0.1:4200/api/cost_center/e503dbfd-8eae-49e4-becc-4aa60016b996 Request Method: DELETE Status Code: **403 Forbidden** Remote Address: 127.0.0.1:4200 {"detail":"CSRF Failed: CSRF token missing or incorrect."} Then, when I do for example "PUT" request, it is executed without any issue: PUT Request: Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,pl;q=0.8 Cache-Control: no-cache Connection: keep-alive Content-Length: 82 Content-Type: application/json Cookie: _ga=GA1.1.1418236812.1564012825; … -
Aggregation of a related object does not output as expected
I have a related model to this one : class Node(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') name = models.TextField(blank=True, null=True) Which is this one : class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.related_tree.name What i want to do is to filter the Node objects with a search keywords that the user will type, and within the result i want to show the number of the visits for each objects so this is the view that i have written so far, if search_text_imported != '': filter = Q() cases = {} get_result_list = [x for x in search_text_imported.split() if x != ''] for i, keyword in enumerate(get_result_list): filter |= Q(name__icontains=keyword) filter |= Q(Tags__icontains=keyword) cases['keyword_match_{}'.format(i)] = Case( When(name__icontains=keyword, then=1), default=Value(0), output_field=models.IntegerField(), ) result = Node.objects.filter( filter, tree_type='root', published=True ).annotate( **cases ).annotate( total_views=Sum('related_views__views_count'), num_bookmarks=Count('bookmarked_by'), keywords_matched=reduce(add, (F(name) for name in cases)) ).order_by('-keywords_matched', '-num_bookmarks').annotate( ) context = { 'tree_result': result } Within the template this what i have {% if tree_result %} {% for tree in tree_result|slice:":14" %} {{ tree.total_views }} {% endfor %} {% endif %} Everything seems to work perfectly except one thing is in … -
Invalid interpolation format for "environment" option in service "web": "SECRET_KEY=
I am working on online book store project. I am trying to setup environment variables in dockercompose.yml project_folder/settings.py SECRET_KEY = os.environ.get('SECRET_KEY') The code inside dockercompose.yml file version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - SECRET_KEY=my_secret_key - DEBUG=1 db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: I am getting the following error when I ran the command $docker-compose down ERROR: Invalid interpolation format for "environment" option in service "web": "SECRET_KEY=my_secret_key" -
Django: How to follow ForeignKey in unique_together constraint?
I have three Django Models: a Property Model, most importantly having a slug field; a Collection Model; and a PropertyCollectionRelationship Model. The last model models a ManyToMany relationship between the other two and is used as an explicit through of a ManyToManyField. from django.db import models class Property(models.Model): slug = models.SlugField() collections = models.ManyToManyField('Collection', blank=True, through='PropertyCollectionRelationship') # ... other unimportant stuff omitted ... class Collection(models.Model): pass # ... lots of stuff omitted ... class PropertyCollectionRelationship(models.Model): prop = models.ForeignKey(Property, on_delete=models.CASCADE) coll = models.ForeignKey(Collection, on_delete=models.CASCADE) I would like to add a uniqueness constraint which ensures that each collection has at most one property with any given slug. I tried to express this via a unique_together option in the Model Meta: class PropertyCollectionRelationship(models.Model): class Meta: unique_together = [['coll', 'prop__slug']] prop = models.ForeignKey(Property, on_delete=models.CASCADE) coll = models.ForeignKey(Collection, on_delete=models.CASCADE) This resulted in the following System Check Error: SystemCheckError: System check identified some issues: ERRORS: myapp.PropertyCollectionRelationship: (models.E012) 'unique_together' refers to the nonexistent field 'prop__slug'. How, if at all, can I achieve such a constraint? -
How do I query the database for all the points that are within a certain radius from a users location?
I am trying to get all the points from the database that are with a certain radius from the users location(e.g 10km). So basically I would like the user to input a location, which would then be converted to lat and lng using the google maps api and have the application search for and return all the stores in the database that are within a 10 km radius of the users location. I have tried Haversines formula but can't seem to get that to work since I do not have a strong understanding of how to filter search results from the database. Could anyone please explain to me how best to query the database for results within a 10km radius using Haversines formula? models.py: class Detail(models.Model): name = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=300, blank=True) lat = models. DecimalField(max_digits=9, decimal_places=6) lng = models.DecimalField(max_digits=9, decimal_places=6) views.py: def feed(request): latitude = request.session['lat'] longitude = request.session['lng'] radius = 20000 unit = 6371 # Distance unit (kms) radius = float(radius) / 1000.0 # Distance radius convert m to km lat = float(latitude) # Central point latitude lng = float(longitude) # Central point longitude print(lat,lng,radius) limit = 1000 My views .py is returning to lng and …