Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JavaScript only works on index.html in a Django web app
I recently started to integrate JavaScript into my Django projects. However, I am facing an issue: Whenever I try to animate an element by clicking on a button it works fine in the index.html but not on other templates that extend the layout.html. I am new to JavaScript so I couldn't trace back the roots of the problem. Here is my code: index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript" src="{% static 'js/script.js' %}"></script> <script type="text/javascript" src="{% static 'js/anime.min.js' %}"></script> <title>Meine Website</title> </head> <body> <div id="ball"></div> <button id="btnwow">Animieren</button> </body> </html> layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript" src="{% static 'js/script.js' %}"></script> <script type="text/javascript" src="{% static 'js/anime.min.js' %}"></script> <title>Layout</title> </head> <body> {% block body %} {% endblock %} </body> </html> thoughts.html {% extends 'website/layout.html' %} {% load static %} {% block body %} <div id="ball"></div> <button id="btnwow">Animieren</button> {% endblock %} script.js (in the same folder with anime.min.js) function animateStart(){ anime({ targets: '#topbar', translateY: [-500, 0], easing: 'easeInOutCirc', opacity: [.1, 1], … -
Question about Django. Assistance for the implementation of registration for the tournament
at the moment there are such models. class Team(models.Model): name = models.CharField('Название', max_length=35, unique=True) tag = models.CharField('Тег', max_length=16, unique=True) about = models.TextField('О команду', max_length=500, null=True, blank=True) logo = models.ImageField('Лого', upload_to="teams_logo/", null=True) game = models.ForeignKey( Game, verbose_name='игра', on_delete=models.SET_NULL, null=True, blank=True ) tournament = models.ManyToManyField('Tournaments', verbose_name='Турниры', blank=True) slug = models.SlugField(unique=True, blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("team_detail", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Team, self).save(*args, **kwargs) class Meta: verbose_name = "Команда" verbose_name_plural = "Команды" class Tournaments(models.Model): name = models.CharField('Название турнира', max_length=50) description = models.TextField('Описание турнира') prize = models.TextField('Призовой') game = models.ForeignKey( Game, verbose_name='Дисциплина', on_delete=models.CASCADE ) author = models.ForeignKey( User, verbose_name='пользователь', on_delete=models.CASCADE, blank=True, null=True ) teams = models.ManyToManyField( Team, verbose_name='Команда', blank=True ) image = models.ImageField('Лого турнира') max_teams = models.PositiveSmallIntegerField('Максимальное количество команд', default=0) count_registration_teams = models.PositiveSmallIntegerField('Количество зарегестрированных команд', default=0) start_date = models.DateTimeField("Дата начала") start_registration_date = models.DateTimeField("Начало регистрации") end_registration_date = models.DateTimeField("Конец регистрации") slug = models.SlugField(unique=True, blank=True, null=True) status = models.BooleanField('Статус активности', default=False) def __str__(self): return self.name def get_absolute_url(self): return reverse("tournament_detail", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify(f'{self.name} - {self.game}') super(Tournaments, self).save(*args, **kwargs) def get_tournament(self): return self.tournamentregistration_set class Meta: verbose_name = "Турнир" verbose_name_plural = "Турниры" class TournamentRegistration(models.Model): tournaments = models.ForeignKey(Tournaments, on_delete=models.CASCADE) teams = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True) user … -
How to implement a generalized uniqueness DB constraint (A,B) and (B,A) in Django?
I want to check the database before an object is created with fields one='a' and two='b', and not create (throw an exception) if the database already has rows with fields one='b' and two='a' (reverse order). That is, guarantee that only one of (one, two) and (two, one) exists. It's like a generalized uniqueness constraint. I'm using Django 3.2. I see CheckConstraint supports a boolean Expression, and one type of expression is an aggregate. So I can imagine testing that the number of rows with (one, two) and (two, one) is at most 1. However, that sounds expensive, and I also don't see examples of how to use a Count in the CheckConstraint. Alternatively, I could implement a pre_save signal that issues a query. This seems better, as I'll have the data in hand to form the query. However, I don't see how to prevent the save using the pre_save signal. Does it have a return value I can use? I don't see that in the docs. I'm open to other ideas as well. -
Using django-hitcount in function-based view
I am trying to implement the logic used HitCountDetailView of django-hitcount module. I've successfully implemented it. My problem now is how can I make it count hit because now it counts one hit for each IP. Example. If I hit an object 5 times, it only counts the first one but I want it to count all. What do I need to overwrite? Below is my function def stats(request, watched_object): object = get_object_or_404(My_model, pk=watched_object.pk) context = {} hit_count = get_hitcount_model().objects.get_for_object(object) hits = hit_count.hits hitcontext = context['hitcount'] = {'pk': hit_count.pk} hit_count_response = HitCountMixin.hit_count(request, hit_count) if hit_count_response.hit_counted: hits = hits + 1 hitcontext['hit_counted'] = hit_count_response.hit_counted hitcontext['hit_message'] = hit_count_response.hit_message hitcontext['total_hits'] = hits return context -
Django filtering over multiple pages
I'm still new to Django and web development, sorry if the question is stupid. I currently have a search bar and a drop down list for a category, which then sends the query set to the results template. The result template also has filters to further refine The search, like price range, condition and for sorting. I was wondering what would be the best way to implement these filters without losing the query set from the previous page. views.py class ProductListView(ListView): model = Product template_name = "products/index.html" context_object_name = 'products' paginate_by = 10 class ProductSearch(ListView): model = Product template_name = "products/ad-list-view.html" context_object_name = "products" def get_context_data(self, **kwargs): context = super(ProductSearch, self).get_context_data(**kwargs) Product_list = super().get_queryset() context.update({ 'filter': ProductFilter( self.request.GET, queryset=Product_list) }) return context def get_queryset(self): search_query = '' if self.request.GET.get('search_query') or self.request.GET.get('category'): search_query = self.request.GET.get('search_query') option = self.request.GET.get('category') category = Category.objects.filter(Name__icontains=option) ducts = Product.objects.distinct().filter( Q(Product_name__icontains=search_query), category__in=category,) return ducts return search_query index.py <div class="container"> <div class="row justify-content-center"> <div class="col-lg-12 col-md-12 align-content-center"> <form method="GET" action="{% url 'Product-search' %}"> <div class="form-row"> <div class="form-group col-md-4"> <input type="text" class="form-control my-2 my-lg-1" id="inputtext4" placeholder="What are you looking for" name="search_query" value="{{search_query}}"> </div> <div class="form-group col-md-3"> <select name="featured" value= "{{featured}}" class="w-100 form-control mt-lg-1 mt-md-2"> <option value= null>Category</option> {% for … -
Debugging Django with VS Code inside a Docker container shuts down the container
I'm following this guide for debugging Django inside a Docker container using VS Code. The only difference I've made was changing ports to 8000 and host to 0.0.0.0 because my docker-compose has it like that. I have no idea why the web container shuts down when I run Django with a breakpoint inside a view because I'm don't really know where the problem is coming from. My only guess is from the vscode/launch.json file that is set up by the following: { "version": "0.2.0", "configurations": [ { "name": "Run Django", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}/app", "remoteRoot": "/usr/src/app" } ], "port": 8000, "host": "0.0.0.0", } ] } Any ideas why this is not working or where the problem is coming from? -
Using django url scheme with Javascript fetch API
I want to use django url scheme when working with fetch API, but it's not understood and i end up with an escaped URL. I followed this tutorial (in french sorry) in which the author achieve it very easily. Demonstrated here Example code : let url = "{% url 'myapp:search_user' %}" const request = new Request(url, {method: 'POST', body: formData}); fetch(request) .then(response => response.json()) .then(result => { console.log(result) }) Which ends up with a console error : POST http://127.0.0.1:8000/myapp/actions/%7B%%20url%20'myapp:search_user'%20%%7D 404 (Not found) Of course my URL is declared in url.py and works well when used in templates. If I replace "url" with relative path it's work well, but that's not django friendly. What I am missing ? -
"We're Sorry, Client not found" FreeIPA, Keycloak setup
I am setting up FreeIPA and Keycloak for user authentication for a django webapp. I have set up the client id and client secret in the .bashrc file and have included my path properly in django (the website loads, just not properly). The error displayed is "We're sorry, Client not found." I figure this may have something to do with setup. What should I do to fix this and make the ipa/keycloak login show the login fields? -
How to get uploaded file size in django
I am uploading a zip file through my form. How I can get the file size i.e in KB / MB so I can display it in my template. -
ValueError: Field 'song_id' expected a number but got 'Remove from Favourites '
ValueError: Field 'song_id' expected a number but got 'Remove from Favourites'. Django Music web App: I have added "Add to Favourite" feature, But Can't add "Remove from Favourite" feature Favourite.html <form action="/music/favourites" method="POST">{% csrf_token %} <input type="hidden" name="video_id" value="{{song.song_id}}"> <button type="submit" class="btn btn-outline-danger">Add to Favourite</button> </form> <form method="post"> {% csrf_token %} <input type="submit" class="btn btn-outline-danger" value="Remove from Favourites" name={{song.id}} > </form> #models.py class Song(models.Model): song_id = models.AutoField(primary_key= True) name = models.CharField(max_length= 2000) singer = models.CharField(max_length= 2000) tags = models.CharField(max_length= 100) image = models.ImageField(upload_to = 'docs') song = models.FileField(upload_to= 'docs') movie = models.CharField(max_length = 150, default = "None") def __str__(self): return self.name class Favourites(models.Model): watch_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) video_id = models.CharField(max_length=10000000, default="") #Views.py def favourites(request): if request.method == "POST": user = request.user video_id = request.POST['video_id'] fav = Favourites.objects.filter(user=user) for i in fav: if video_id == i.video_id: message = "Your Video is Already Added" break else: favourites = Favourites(user=user, video_id=video_id) favourites.save() message = "Your Video is Succesfully Added" song = Song.objects.filter(song_id=video_id).first() return render(request, f"music/songpost.html", {'song': song, "message": message}) wl = Favourites.objects.filter(user=request.user) ids = [] for i in wl: ids.append(i.video_id) preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(ids)]) song = Song.objects.filter(song_id__in=ids).order_by(preserved) return render(request, "music/favourite.html", {'song': song}) This function is … -
Bypassing django-rest-framework APIExceptions
I would like to understand the implications of the following design choice for an application built using DRF. Is it okay if I choose to raise exceptions that are not an instance of APIException in conjunction with a custom_exception_handler that can handle all these exceptions? From what I understand, the handler for a specific request is determined within the rest_framework.views.APIView.dispatch method (source) and the handler gets called within the try...catch.. block in this dispatch method (source). So this way any exceptions that are raised during the execution of the handler are caught within the dispatch method are delegated to the exception handler (default or custom). As we can see here the dispatch method catches not an APIException but any and all Exception. So could I simply raise my own CustomException(s) that are sub-classes of Exception through out my application and simply handle all these exceptions the way I want in the custom_exception_handler? I understand that the ValidationError will be an exception to this, as the serializers and in-built validators all raise ValidationError. If I can override the rest_framework.serializers.Serializer.is_valid in MyCustomSerializer I can catch the rest_Framework.serializers.ValidationError and throw MyOwnCustomValidationError which can be handled by the custom_exception_handler. Something like this: def is_valid(self, … -
How to add many filed in Django
i decided to create movies website with Django , i want to add , for example ** season 1 - series 1 , season 1 - series 2, season 2 - series 1 season 2 - series 1 ** what is best way ? i mean when i add TV shows once and how to add then series and seasons ? this is my model.py class Movie(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=100) year_of_production = models.TextField(max_length=10) view_count = models.IntegerField(default=0) link = models.TextField(max_length=70) def get_absolute_url(self): return reverse('post',kwargs={"post_slug":self.slug}) def __str__(self): return "{} -------------- {}".format(self.title,self.status) -
Python/Django Query to check if Dates Overlap
I'm trying to set up a validation on an API built with Python/Django. I'm using a serializer and would like to do a query filter against the post data to make sure 2 date fields do not overlap. For example: My Post contains: "valid_start": "2021-09-01", "valid_end": "2021-09-15" I would like to an object.filter to check if there are any records in my database with overlapping dates: I want to throw a validation error if the query detects any of the following "valid_start": "2021-09-01", "valid_end": "2021-09-15" "valid_start": "2021-09-02", "valid_end": "2021-09-15" "valid_start": "2021-09-03", "valid_end": "2021-09-10" "valid_start": "2021-08-28", "valid_end": "2021-09-20" I've tried the __range function, gte/lte functions, none really do what I'm trying to achieve. Thanks! -
how create simple many-to-many relations with django rest
i am new in django and migrate from symfony. i want to try create simple relation between 2 model in django-rest-framework and get apiview for them. but i can undrestand why serializers not handle relations between this 2 models. my models in models.py from django.contrib.gis.db import models from django.contrib.gis.geos import Point import uuid class RequestLocation(models.Model): gpslocation = models.PointField(srid=4326, geography=True, default=Point(0.0, 0.0)) gpslocationradius = models.IntegerField(default=5) description = models.TextField(default='#') created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] def __str__(self): return self.id class Shops(models.Model): gpslocation = models.PointField(srid=4326, geography=True, default=Point(0.0, 0.0)) created = models.DateTimeField(auto_now_add=True) requestlocations = models.ManyToManyField(RequestLocation, null=True, blank=True) class Meta: ordering = ['created'] def __str__(self): return self.id and my serializers in serializers.py: from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import RequestLocation, Shops class RequestLocationSerializer(GeoFeatureModelSerializer): class Meta: model = RequestLocation geo_field = 'gpslocation' auto_bbox = True id_field = 'id' fields = ['id', 'gpslocation', 'gpslocationradius', 'description'] class ShopsSerializer(GeoFeatureModelSerializer): requestlocations = RequestLocationSerializer(read_only=True) class Meta: model = Shops geo_field = 'gpslocation' auto_bbox = True id_field = 'id' fields = ['id', 'gpslocation', 'requestlocations'] and views.py: # RequestLocation view @api_view(['GET', 'POST']) def rl_list(request, format=None): if request.method == 'GET': rl = RequestLocation.objects.all() serializer = RequestLocationSerializer(rl, many=True) distance_filter_field = 'geometry' filter_backends = (DistanceToPointFilter) bbox_filter_include_overlapping = True return Response(serializer.data) elif request.method == 'POST': … -
Django: The view didn't return an HttpResponse object. It returned None instead. When Override Form_Valid
I overrode the form_valid method on my RobotDetail view but whenever I try to use the view I get the error The view dashboard.views.RobotDetail didn't return an HttpResponse object. It returned None instead. If anybody knows how to fix this it would be super appreciated! VIEW from django.shortcuts import render from django.views.generic import ListView, DetailView, UpdateView from .models import Robot from .forms import RobotUpdateForm import socket import threading HEADER = 64 PORT = 6060 SERVER = socket.gethostbyname(socket.gethostname()) ADDR = (SERVER, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT!" class RobotDetail(UpdateView): model = Robot form_class = RobotUpdateForm template_name = 'dashboard/robotdetail.html' def form_valid(self, form): self.object = form.save() client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) def send(msg): message = msg.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER - len(send_length)) client.send(send_length) client.send(message) send("Hello World!") send("Hello Andrew") send("Hello") send(DISCONNECT_MESSAGE) MODEL class Robot(models.Model): def fetch_choices(): scope = [REDACTED] creds = ServiceAccountCredentials.from_json_keyfile_name("dashboard/Files/creds.json", scope) client = gspread.authorize(creds) sheet = client.open("tutorial").sheet1 path_names = [] path_name_fetch = sheet.col_values(1) for i in path_name_fetch: if (i, i) not in path_names: path_names.append((i, i)) return path_names name = models.CharField(max_length=200) path_options = models.CharField(choices=fetch_choices(), default=fetch_choices(), max_length=100) status_choices = [('waiting', 'waiting'), ('running', 'running'), ('stuck', 'stuck')] current_status = models.CharField(choices=status_choices, default=status_choices[0], max_length=100) def __str__(self): return self.name + … -
Does YugabyteDB support Django even though the SAVEPOINTS feature is not yet supported?
Have a Django app setup to talk to YugabyteDB, but while running migrations we run into the following error: Traceback (most recent call last): File "/opt/env/lib/python3.6/site-packages/django/contrib/contenttypes/models.py", line 54, in get_for_model ct = self.get(app_label=opts.app_label, model=opts.model_name) File "/opt/env/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/env/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/env/lib/python3.6/site-packages/django/db/models/query.py", line 464, in get_or_create return self.get(**lookup), False File "/opt/env/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/opt/env/lib/python3.6/site-packages/django_prometheus/db/common.py", line 63, in execute return super(CursorWrapper, self).execute(*args, **kwargs) psycopg2.errors.FeatureNotSupported: SAVEPOINT <transaction> not supported yet LINE 1: SAVEPOINT "s140500455238528_x1" ^ HINT: See https://github.com/YugaByte/yugabyte-db/issues/1125. Click '+' on the description to raise its priority Since YugabyteDB does not appear to support SAVEPOINTS today, how can we get around this Django error? [DISCLAIMER: This question was first asked by a YugabyteDB user over email] -
how to filtered 2 Q conditions in query django?
so,i have a List of all mobile phones whose brand name is one of the incoming brands. The desired brand names will be entered. The number of entries is unknown and may be empty. If the input is empty, the list of all mobile phones must be returned. model: class Brand(models.Model): name = models.CharField(max_length=32) nationality = models.CharField(max_length=32) def __str__(self): return self.name class Mobile(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model = models.CharField(max_length=32, default='9T Pro', unique=True) price = models.PositiveIntegerField(default=2097152) color = models.CharField(max_length=16, default='Black') display_size = models.SmallIntegerField(default=4) is_available = models.BooleanField(default=True) made_in = models.CharField(max_length=20, default='China') def __str__(self): return '{} {}'.format(self.brand.name, self.model) query: from django.db.models import F, Q def some_brand_mobiles(*brand_names): query = Mobile.objects.filter(Q(brand__name__in=brand_names) | ~Q(brand__name=[])) return query If the input is empty, the list of all mobile phones will be returned, but i cant use *brand_names to return the list. for example query = Mobile.objects.filter(Q(brand_name_in=['Apple', 'Xiaomi'])) return query It works alone, but it does not check both conditions with the function I wrote. how to fix it ? -
Django: Send current logged in user as JSON
I would like to create a GET endpoint that returns the JSONResponse of the current logged-in user. Ideally, it would look like: { "username": "joe", "email": "joe@plainviewhcp.com", "first_name": "", "last_name": "", "last_login": "2021-09-17T17:11:00.039Z", "is_superuser": true, "is_active": true } (Note that I'm using Django 3.2, not Django REST API) This requires serializing the current user object, but serializing a single object is... opaque in the documentation, and many similar questions have responses from 6 or more years/two major versions ago. -
How does Django know if object exists
Let's say I have two models, for example: class Product: product_name = models.CharField(max_length=40) class ProductPrice(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE) product_price = models.FloatField() Please don't bother why someone might want two different models/tables for such data. That's not the main point here. What's interesting is, when I query a Product I will get a python attr productprice along with the object ONLY IF ProductPrice exist associated with that Product. To make this more clear let's create some dummy data: product1 = Product.objects.create(product_name='first product') product2 = Product.objects.create(product_name='second product') product_price = ProductPrice.objects.create(product=product2, price=10.99) Now try this print(hasattr(product1`, "productprice")) # -> false print(hasattr(product2`, "productprice")) # -> true How does django know that a ProductPrice exist in database? In SQL I am not aware of any way to check this without second query. I am very curious how this works. -
What is a better approach to cache data in django app when running on gunicorn
I have a django application that is running on gunicorn app server. Gunicorn running N wokers. We know that each worker is a separate python proccess. In one of my applications services i have a query to a database that takes long time (10-20 sec). Ok i decided to cache the result, so just simply add django.core.cache and call cache.get(key) if result is not None app returned data from cache if not it called service and stored data in cache using cache.set(key, data, time). But if we have a N workers and first query was addressed to worker 0 app stored result of long running service in cache (process memory) of worker 0 but when simillar (request contains paging option, but i store whole RawDataSet in memory, so every page returns fast) request is addressed to worker 1 cache as expected would't work because this is a different process. So obviously i have to use some cache that could be used by all workers. What approach (i.e. use in memory database or something different) is better to use to solve this issue? -
Django cumulative sum or running sum
I am trying to make a party ledger. which details will show by a date search result. I have a column name balance which will display cumulative data by the date search. I want to view cumbalance column in my table depends on balance column. -------------------------------------- amount payment balance CumBalance -------------------------------------- 10 5 5 5 20 5 15 20 10 15 -5 15 My views.py def partyDetails(request,pk): form = DateRangeForm() if request.method == 'POST': form = DateRangeForm(request.POST or None) if form.is_valid(): cumulative_balance = PurchasePayment.objects.all() .filter(vendor=pk,date__range= (form.cleaned_data['start_date'], form.cleaned_data['end_date'])) .annotate(cumbalance =Sum('balance')) else: return redirect('party_ledger') return render(request, 'purchase/party_details.html', {'dateform':form, 'cumbal':cumulative_balance,'name':pk}) I have also tried .aggregate(Sum('balance')) -
How to make new web page for each unique ID with Django
I have a dataset where each unique ID needs its own webpage with a set of visualizations. I want to generate a new webpage iteratively for each unique ID. I am doing this with Django. Is anyone aware of any examples or guidance on how to do this? -
How to "disable" default primary keys in djongo
I'm getting this error after upgrading to djongo 1.3.6 ERRORS: some_app.Some_Class: (models.E026) The model cannot have more than one field with 'primary_key=True'. this is the class giving the error: # some_app/some_class.py from djongo import models class Some_Class(models.Model): _id = models.ObjectIdField() event_id = models.IntegerField(primary_key=True) league = models.CharField(max_length=512) event_date = models.IntegerField() event_text = models.CharField(max_length=512) event_group_id = models.IntegerField() group_name = models.CharField(max_length=512) as you can see I have only one PK defined, but apparently djongo is creating the another one. Any idea on how to disable this djongo behaviour???? -
filter_fields with DjangoFilterBackend
I have a model called Product class Product(models.Model): id name created_at updated_at price and so on.... i want to filter using all of the above attributes, which will be passed in query_params at this moment i am using DjangoFilterBackends with filter_fields but to support all attributes i have to mention all the attributes in filter_fields like below in views filter_fields = ['id', 'name', 'created_at', 'updated_at', 'price'] its working fine, but in actual model the fields are alot, which is causing code quality degradation. is there any way to include all fields in filter_fields ?? i tried filter_fiels = ['all'], but its not working. -
What options need to be specified in the CACHES variable of Django's settings.py file to connect with an azure vm
My goal is to use a Linux (ubuntu 20.04) azure vm to run a caching service for django. I am running memcached on a Linux (ubuntu 20.04) azure vm. I am using django-pymemcache which extends the pymemcache library and is a wrapper around memcached. settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': '53.171.42.209', 'OPTIONS': {} } } I've tested it while running the memcached service locally and specifying a location of (127.0.0.1:11211) and it works as expected. I know that the memcached service is listening on port 11211 of the azure vm. I've opened up inbound rules on azure to allow connection. But it refuses my connection, I assume because I haven't specified any sort of credentials to connect to it. I can't figure out how to do that piece, and if it's the only thing that I'm missing.