Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- How to get element index in a queryset by using F expression
I have following models: class Topic(models.Model): title = models.CharField(max_lenght=32) # Some other fields. class Thread(models.Model): topic = models.ForeignKey(Topic, related_name=threads', on_delete=models.CASCADE) # some other fields class Message(models.Model): thread = models.ForeignKey(Thread, related_name='messages', on_delete=models.CASCADE) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I want to calculate index of each element in each Thread, in the queryset by F(). For example If in the Thread 1 I have 5 messages, I want to messages have indexes as 1 to 5. my code doesn't work. code comes in the following: from django.models import Count, Q, F messages = Message.objects.all().annotate( index=Count('id', filter=Q(thread_id=F('thread_id'), created__lt=F('created'))) + 1 ) This return same index for all elements. For example this returns index=5 for all items in queryset. How can I calculate index of elements in the queryset? -
Django Rest: How to update fields of a foreign key object from the related object API endpoint
I have the following two models with a ForeignKey relationship: models.py class DataModel(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) name = models.CharField(max_length=1000,unique=True,) class DataPoint(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) name = models.TextField() unit = models.ForeignKey(Unit,related_name='+',on_delete=models.PROTECT) data_model = models.ForeignKey(DataModel,on_delete=models.PROTECT,related_name='data_points') With the following respective serializers serializers.py class DataPointSerializer(serializers.ModelSerializer): unit = serializers.CharField(source="unit.unique_key") class Meta: model = models.DataPoint fields = ['id', 'name', 'unit'] class DataModelSerializer(serializers.ModelSerializer): dataPoints = DataPointSerializer(source='data_points', many=True) class Meta: model = models.DataModel fields = ('id', 'name', 'dataPoints') read_only_fields = ('id',) Then I have an API endpoint /api/v1/data-models/ where I can GET all the DataModels and POST to create a new one. Then on api/v1/data-models/{id}, I can edit the name of the DataModel object or add more DataPoints by passing a name and unit. What I want to do now is through the api/v1/data-models/{id} endpoint, edit (PATCH) DataPoints that are already linked to the DataModel, so I can change their name or unit given it's id like so: { "dataPoints": [ { "id": "6eb3878d-ea5b-47b9-b9e5-7a606d3596ff", "name": "Test DataPoint", "unit": "V" } ] } views.py class DataModelViewSet(viewsets.ModelViewSet): queryset = models.DataModel.objects.all() serializer_class = DataModelSerializer permission_classes = (IsAuthenticated, ) def update(self, request, pk=None, **kwargs): dm = get_object_or_404(self.get_queryset(), pk=pk) serializer = self.serializer_class(dm, data=request.data, partial=True) if not serializer.is_valid(): return Response(serializer.errors, … -
django save method dosen't fire up post_save signal
I'm struggling with post_save signal with django model , my project works at first time with signals without any problems , now even the save() method save record to database without any exceptions ( save method without override), post_save signal are not triggered but when I used admin panel to save record the result is good all suggestions are welcomes -
Django - disable a system check for a specific management command
I have a circular problem with a system check in django: $ python manage.py search_index --rebuild -f SystemCheckError: System check identified some issues: ERRORS: {'search.documents.applications': 'entities'}: (search.E001) No elasticsearch index 'entities' exists HINT: Run `manage.py search_index --rebuild -f` to recreate then repopulate the indices. One workaround is to disable this check using system settings but I don't want to have to change system settings to disable it, deploy, run the rebuild, change back, redeploy every time I attach a different search index or flush elasticsearch. Is there a way of disabling this error (eg by overriding that setting) by passing something to the actual manage.py command? -
Render dropdown in django view using values from postgres arrayfield
Here is an example from the model: class Shipment(models.Model): shipment_id = models.BigAutoField(null=False, primary_key=True) potential_shipping_dates = ArrayField(models.DateField(), verbose_name='Ship Dates', null=True) Here is what I'm sort of attempting in my form: class ShippingForm(forms.Form): potential_shipping_dates = forms.ModelChoiceField(queryset=Shipment.objects.all()) def __init__(self, *args, **kwargs): super(ShippingForm, self).__init__(*args, **kwargs) And here is where my form is added to context: context['shippingForm'] = ShippingForm(initial=??what_goes_here_maybe??) My form renders fine but I want to show a dropdown with a date for each option. -
Django Full height template
I am trying to have all the templates to use the whole height of the browser page (using chrome) In my CSS body { min-height: 100vh; } Then in by base.html {% load static%} {% load custom_tags %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %}My Platform{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/base.css'%}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <div> <body> <nav class="navbar navbar-expand-lg nav3" > ....stuff.... </nav> <main> <div class="container"> {% block content %} {% endblock content %} </div> </main> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> </body> <div class="d-flex justify-content-between flex-wrap footerstyle" > <div> <i class="far fa-copyright"></i> All rights reserved by WozNot </div> <ul class="list-inline "> <li class="list-inline-item"><a href="{% url 'web_terms' %}" class="hidelink"> Terms & Conditions </a> | </li> <li class="list-inline-item "><a href="{% url 'web_privacy' %}" class="hidelink"> Privacy Policy </a>| </li> <li class="list-inline-item "><a href="{% url 'web_contact' %}" class="hidelink"> Contact Us</a> </li> </ul> </div> </div> </html> Unfortunately it looks like the min-height does not go across when the base … -
Django: MultiPartParser is skipped when uploaded file size > DATA_UPLOAD_MAX_MEMORY_SIZE
I have a view in my DRF app which accepts Content-type: multipart/form-data which I use to POST multiple files together, sample represents a binary file data is a string-yfied JSON. Code: from rest_framework.parsers import MultiPartParser from rest_framework.decorators import api_view, parser_classes class CustomMultiPartParser(MultiPartParser): def parse(self, stream, *args, **kwargs): print("----- inside MultiPartJSONParser ------") ## for debug req = super().parse(stream, *args, **kwargs) data_str = req.data.get("data", None) if data_str: parsed = json.loads(data_str) mutable_data = {"data": parsed} mutable_files = {} for key, value in req.files.items(): if key != "data": mutable_files[key] = value return parsers.DataAndFiles(mutable_data, mutable_files) return req @api_view(["POST"]) @parser_classes((CustomMultiPartParser,)) def my_view(request): print(type(request.data)) ## for debug serializer = CustomFileSerializer(data=request.data) # ...snip... When the sample POSTed to this endpoint is < 2.5 mb in size, the type(request.data) is dict whereas if file size > 2.5 mb, the type(request.data) is django's QueryDict. Logs: # file size < 2.5mb ----- inside MultiPartJSONParser ------ {'data': {'private': False}, 'sample': <InMemoryUploadedFile: pafish.exe (application/x-ms-dos-executable)>} # file size > 2.5mb <QueryDict: {'data': '[{"private": false}]', 'sample': [<TemporaryUploadedFile: wannacry.bin (application/octet-stream)>]}>> On debugging more, I find out that: The 2.5mb threshold is the django's DATA_UPLOAD_MAX_MEMORY_SIZE. When I set this variable to a higher value, the threshold becomes exactly that. the CustomMultiPartParser is skipped all-together in the second … -
Is there a better way to import load_model from tensorflow in a django web app?
I have deployed a keras model on a django app on a shared hosting environment. The model is working well. The problem is, it takes much time to load. From my experiment I have seen that it is taking time to excute: from tensorflow.keras.models import load_model This only occurs at the first page load. Is there any way to solve it? Thanks in advance. -
I'm having trouble looping through my dataset objects in django
<script src='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js'>></script> <link href='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css' rel='stylesheet' /> <form method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Submit Address"/> </form> <div id='map' style='width: 100%; height: 700px;'></div> <script> mapboxgl.accessToken = 'pk.eyJ1IjoiZHVueWFzYWlkIiwiYSI6ImNrb2FmNHA1czA2ZTAzMXBnYTBrZ253a3QifQ.7vcmfsekylXlTOnloBHpiA'; // var geocoder = new Google.maps.geocoder(); var map = new mapboxgl.Map({ container: 'map', // container ID style: 'mapbox://styles/mapbox/streets-v11', // style URL center: [17.6, 59.8], // starting position [lng, lat] zoom: 9 // starting zoom }); // Set options {% for task in qs %} console.log(qs) {% if task.address != '' %} var marker = new mapboxgl.Marker({ color: 'green', draggable: true }).setLngLat([task.long, task.lat]) .addTo(map); {% endif %} {% endfor %} views.py in the same app as the task def map(request, *args, **kwargs): qs = Task.objects.all() Address = request.GET.get('Address') if Address != None: qs = qs.by_Address(Address) return render(request, 'pages/map.html', qs) Model class class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tasks") #many users can have many tasks accepts = models.ManyToManyField(User, related_name = "task_user", blank = True, through = TaskAccept) title = models.TextField(blank = True, null = True) content = models.TextField(blank = True, null = True) image = models.FileField(upload_to= 'images/', blank = True, null = True) timestamp = models.DateTimeField(auto_now_add = True) completed = models.BooleanField(default=False) accepted_by = models.ManyToManyField(User, through = TaskAcceptedUsers , blank = True, related_name "accepted_by") Address = … -
LINE 1: ..." timestamp with time zone NOT NULL, "attributes" hstore NOT
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres dbi5k: image: postgres volumes: - ./data/dbi5k:/var/lib/postgresql/data environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } and $ vim i5k/settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_i5k', 'USER': 'django', 'PASSWORD': 'postgres', 'HOST': 'dbi5k', 'PORT': '5432', } } Please below the logs after I ran docker-compose build docker-compose up # I had to wait for 2 minutes and do CTRL+C in order to give the database to start docker-compose up … -
bootstrap navbar not showing properly
I am beginning to learn django. This is my first bootstrap template to work on but navbar is not showing properly.I will continue learning django for the meantime but this propblem is irritating me. please help me solve it this is the template <!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"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>{% block title %}page one {% endblock %}</title> <!-- Bootstrap --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <nav class="navbar navbar-expand-md navbar-light bg-faded"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#">Navbar</a> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-item nav-link" href="#">Features</a> <a class="nav-item nav-link" href="#">Pricing</a> <a class="nav-item nav-link disabled" href="#">Disabled</a> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </div> </nav> {% … -
How to group an array of objects by one of the model's attribute in Django?
I would like to do the something similar to this example How to group an array of objects by key but I couldn't find a solution for API Get in Django. Here's an example of what I have: [ { "id": 1, "nutrition_measurement_id": "1", "nutrition_type_id": "2", "feeding_time": "dinner" }, { "id": 2, "nutrition_measurement_id": "2", "nutrition_type_id": "1", "feeding_time": "dinner" }, { "id": 3, "nutrition_measurement_id": "3", "nutrition_type_id": "2", "feeding_time": "breakfast" }, { "id": 4, "nutrition_measurement_id": "2", "nutrition_type_id": "1", "feeding_time": "breakfast" } ] Here's an example of what i want to achieve: { "dinner": [ { "id": 3, "nutrition_type_id": 2, "nutrition_measurement_id": 1 } ], "dinner": [ { "id": 3, "nutrition_type_id": 1, "nutrition_measurement_id": 2 } ], "breakfast": [ { "id": 3, "nutrition_type_id": 2, "nutrition_measurement_id": 3 } ], "breakfast": [ { "id": 5, "nutrition_type_id": 1, "nutrition_measurement_id": 4 }, ] } Here are the models I have: class HorseNutrition(models.Model): horse = models.ForeignKey(Horse, models.DO_NOTHING) nutrition_type = models.ForeignKey('NutritionType', models.DO_NOTHING) nutrition_measurement = models.ForeignKey('NutritionMeasurement', models.DO_NOTHING) feeding_time = models.CharField(max_length=10, blank=True, null=True) class Meta: managed = False db_table = 'horse_nutrition' class NutritionMeasurement(models.Model): name = models.CharField(unique=True, max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'nutrition_measurement' def __str__(self): return self.name def __unicode__(self): return self.name class NutritionType(models.Model): name = models.CharField(unique=True, max_length=30, blank=True, null=True) … -
temporarily save an image from HTTP get
I am trying to test a get response which fetches a filtered image (sepia, in this case). It would be nice to store the fetched data locally until the test is executed. I have tried the following: loc = join(dirname(__file__), 'image_file') def save_sepia(data): img_temp = NamedTemporaryFile(delete=True) img_temp.write(data.content) img_temp.flush() img = data.save(loc, File(img_temp), save=True) return img @pytest.fixture def image_sep(client): req = client.get('some url') save_sepia(req) return { 'id': 'test-image', 'image': open(loc[0], 'rb') } Is this the right approach? -
What happens with the existing data if Decimals decimal_places are changed in a Django model?
I need to change a DecimalField from having decimal_places=0 to decimal_places=7 while keeping max_digits=50. I think all numbers in this column are between 0 and 1,000,000,000. So the data migration could be unproblematic. However, I'm uncertain. I have seen the AlterField documentation and I think I found the source code. However, I would need an introduction to this. Is it possible to see the generated SQL queries? I could imagine several things going wrong: Data Dropping if Decimal(decimal_places=0) is different from Decimal(decimal_places=7) in a way that Django/Postgres does not take care of Data Change if the internal representation stays the same but the values are interpreted in a different way Overflow if values get out of bounds NaN / NULL if values get out of bounds The last two cases should not happen in my specific case, but I'm still interested how Django migrations would deal with out of bounds cases. -
Why can't I import an external package into my views.py file?
Normally I don't use StackOverflow and ask my questions on Reddit, however I think this might be a problem for other users as well, so here I am. I'm a beginning Django developer and I'm building my very first Feed reader so that I can display RSS data on my template. To get this to work I use the package called: 'feedparser'. And I installed it correctly following the steps: 'pip install feedparser'. However an error accurs when I want to import this package into my views.py file: 'import "feedparser" can not be resolved'. Because I'm still a beginner I work with tutorials to understand how I can create a feedreader. The very first step in every case is to install this package and to import it (ofcourse!) only using: import feedparser, unfortunately for me, it raises an error. I don't know how to fix it, I can see by using pip freeze that the package indeed is installed but why can't I import it? I hope someone can help me out because I have tried everything all day and nothing seems to work or to help. Views.py (import area): from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin … -
I'm getting this JSONDecodeError at /vaccine/handle vaccine slots/ on heroku server but on my local server its working fine
Heroku log 2021-05-20T09:48:41.906814+00:00 app[web.1]: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 2021-05-20T09:48:41.907973+00:00 app[web.1]: 10.5.245.135 - - [20/May/2021:09:48:41 +0000] "POST /vaccine/handle_vaccine_slots/ HTTP/1.1" 500 82617 "https://systemofreckoning.herokuapp.com/vaccine/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36" 2021-05-20T09:48:41.909232+00:00 heroku[router]: at=info method=POST path="/vaccine/handle_vaccine_slots/" host=systemofreckoning.herokuapp.com request_id=d4a0b644-a44b-435f-963a-6cf8eaa9a5da fwd="103.88.217.153" dyno=web.1 connect=1ms service=141ms status=500 bytes=82877 protocol=https 2021-05-20T09:49:27.945441+00:00 app[web.1]: 10.97.195.7 - - [20/May/2021:09:49:27 +0000] "GET /logout/ HTTP/1.1" 302 0 "-" "Mozilla/5.0 (compatible; proximic; +https://www.comscore.com/Web-Crawler)" 2021-05-20T09:49:27.946900+00:00 heroku[router]: at=info method=GET path="/logout/" host=systemofreckoning.herokuapp.com request_id=fdeb198f-21c1-4d20-913d-ee93134c5b07 fwd="18.232.161.22" dyno=web.1 connect=0ms service=3ms status=302 bytes=395 protocol=https 2021-05-20T09:49:27.962588+00:00 app[web.1]: 10.97.195.7 - - [20/May/2021:09:49:27 +0000] "GET /accounts/login/ HTTP/1.1" 200 7748 "-" "Mozilla/5.0 (compatible; proximic; +https://www.comscore.com/Web-Crawler)" 2021-05-20T09:49:27.964058+00:00 heroku[router]: at=info method=GET path="/accounts/login/" host=systemofreckoning.herokuapp.com request_id=3fe99047-99a3-4d96-ad1f-087146838825 fwd="18.232.161.22" dyno=web.1 connect=0ms service=14ms status=200 bytes=8282 protocol=https 2021-05-20T09:50:05.878286+00:00 heroku[run.9390]: Client connection closed. Sending SIGHUP to all processes 2021-05-20T09:50:06.436547+00:00 heroku[run.9390]: Process exited with status 129 2021-05-20T09:50:06.537160+00:00 heroku[run.9390]: State changed from up to complete 2021-05-20T09:50:36.900551+00:00 heroku[router]: at=info method=POST path="/vaccine/handle_vaccine_slots/" host=systemofreckoning.herokuapp.com request_id=84aeeb06-fb0c-4802-910b-fc05d58fda52 fwd="103.88.217.153" dyno=web.1 connect=0ms service=126ms status=500 bytes=82891 protocol=https 2021-05-20T09:50:36.895526+00:00 app[web.1]: Internal Server Error: /vaccine/handle_vaccine_slots/ 2021-05-20T09:50:36.895536+00:00 app[web.1]: Traceback (most recent call last): 2021-05-20T09:50:36.895537+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner 2021-05-20T09:50:36.895537+00:00 app[web.1]: response = get_response(request) 2021-05-20T09:50:36.895547+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response 2021-05-20T09:50:36.895547+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2021-05-20T09:50:36.895548+00:00 app[web.1]: File "/app/vaccine/views.py", line 51, … -
Django : How can I display only the checked items from a model in a template?
Here is my Django Model: class InterviewAssessment(models.Model): topics = models.ManyToManyField(AdvocacyTopic, verbose_name="Topics", blank=True) They consist into a list of topics out of them one or several items can be selected. Therefore, when I want to create an object InterviewAssessment, I use this class: class InterviewForm(models.Model): class Meta: model = Interview fields = ['topics'] widgets = { 'topics': forms.CheckboxSelectMultiple(), } My workflow requires that another User, who conducts the interview, updates my form to make an assessment. Therefore I have created a form dedicated to the assessment, as only some fields are to be updated. I would like to display only the topics which have been checked. They are not to be updated. However, if through a widget: I disable the field with : self.fields['topics'].widget.attrs.update({'disabled': 'true'}) All the items are displayed in grey, however the field in the database is reset to 0 (which is normal with Django) I make the field readonly with: self.fields['topics'].widget.attrs.update({'readonly': 'true'}) The items are selectable and are implemented in the DB, which is worse. I directly act at the level of the template with: {{ form.topics }} Of course, I get all the topics, which I don't want. Therefore what would be the syntax to exclusively display … -
Angular Django Foreign Key Relationship
FYI: This question is probably not easily answered by someone, who doesn't know angular - I don't want to bait someone with django-rest-framework tag haha! In my Django models.py file I have two models with a Foreign Key relationship: class Work(models.Model): job = models.CharField(max_length = 200, blank = False) def __str__(self): return self.job class Personal(models.Model): name = models.CharField(max_length = 250) work = models.ForeignKey('Work', on_delete = models.CASCADE, null = True) def __str__(self): return self.name For these models I have also set up Django Rest Framework which is working perfectly fine I want this to work: User can add Personal name and job. Name is a basic text field but job should be a list, similar to how it works in Django backend. So my question is: How do I tell Angular to show me, when creating Personal, to display me a list of jobs I have set up in Django. This is what my html file is looking like right now: Name <input type="text" [(ngModel)]="selectedPersonal.name"/><br> Job <input type="text" [(ngModel)]="selectedPersonal.job"/><br> <button *ngIf="selectedPersonal.id != -1" (click)="updatePersonal()"> PUT </button> <button *ngIf="selectedPersonal.id == -1" (click)="createPersonal()"> CREATE </button> <button *ngIf="selectedPersonal.id != -1" (click)="deletePersonal()"> DELETE </button> This gives me a simple page, where I can see the … -
Is it safe to override queryset in a custom django-rest-framework action
Let's say I have a queryset like this class DataViewSet(viewsets.ModelViewSet): serializer_class = DataSerializer queryset = Data.objects.all() @action(detail=False, methods=['get'], url_path='viewers/sum') def viewers_sum(self, request): self.queryset = Data.objects.filter(foo="bar").order_by('-foo') return super().list(request) As you can see I override queryset in the custom action viewers_sum. My question is if this has risk to cause issue with other actions, like list(). I've had similar problems before with permission where I've overwritten some property that's hasn't been restored for the next request. I've tried to debug this and It seems like there's no problem, but I don't understand the reason behind it. And it might not behave the same on production server as in my dev-server. In the docs they're not using this method. But I would prefer this since it feels very clean (if it's safe). -
Problem with Google Maps Place autocomplete and django forms
I have a django form with this atribute: origin_address=forms.CharField(max_length=100,widget=forms.TextInput(attrs={"id":"autocomplete"})) I need to use Google Maps Place autocomplete in origin_address. In html file I am doing the following things: <form method="post"> {% csrf_token %} {{ form }} <script> function initAutocomplete() { var locat_input=document.getElementById('origin_address') var autocomplete=new google.maps.place.Autocomplete(locat_input); // { // types: ['address'], // componentRestrictions: {'country': ['es']}, // } // autocomplete.addListener('place_changed',onPlaceChanged); } </script> <script src='https://maps.google.apis.com/maps/api/js?key=AIzaSyCaR0xc4Xiv3rHEV-HkFD-4Dt7hsIx3aT0&libraries=place&callback=initAutocomplete'></script> <button>Enviar</button> </form> I am following this post: Django. Google Place Autocomplete Address Form . However, I cant see what its failing. Thank you -
Django Rest url page shown when reload react app
I have deployed my app using nginx and gunicorn, i have used Reactjs on front-end and django rest on backend, when my django server starts it loads react on front as template,everything works fine, but when i reload my react app instead of staying on react it moves to django rest pages, how it can be solved, it only giving issue whenenver i reload my app. urlpatterns = [ path("", index, name="index"), ] def index(request): return render(request, "build/index.html") -
django throttle rate limit for specific unauthenticated user based ip address
i have setup as given instructions https://www.django-rest-framework.org/api-guide/throttling/ and my setup code is setting.py """ REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', ], 'DEFAULT_THROTTLE_RATES': { 'anon': '5/min', 'anon_day': '10/day', 'user': '10/min', 'user_day': '20/day', } """ and custom throttle.py """ from rest_framework.throttling import AnonRateThrottle, UserRateThrottle class AnonDayThrottle(AnonRateThrottle): scope = 'anon_day' class UserDayThrottle(UserRateThrottle): scope = 'user_day' """ and assign to api class comparable_summary.py """ from rest_framework.throttling import AnonRateThrottle from rest_framework.views import APIView from .throttle import AnonDayThrottle LOGGER = logging.getLogger(__name__) class ComparablesSummaryAPI(APIView): """ apis performs for given response """ throttle_classes = [AnonDayThrottle, AnonRateThrottle] """ my question is i have checked two different ip_addresses but it consider unique ip_address for all request, please help me thank for your help -
How to disable Django cache view for superuser?
I use cache_page decorator for caching views in Django. How can I disable cache for superuser or authorized users ? -
how to disappear one page with popup of another page?
I have one sign in (pop up) page which has register tab in it for sign up, I supposed to make these 2 pages such that when i click on register the sign in page disappear and Registration(sign up) page pops up.But from few days i have been facing some issues as when i click on register the sign up page pops up properly but sign in page does not disappear properly instead it appears in backside of signup page(I have attached a screenshot for this). Here is my code: signin.html: {% load static %} <div class="modal fade" id="signin-modal" tabindex="-1" role="dialog" aria-labelledby="signin-modalLabel" aria-hidden="true" data-dismiss="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h2>Sign in</h2> <button class="btn-black-border" type="button" data-toggle="modal" data-target="#register-modal" id="register">Register</button> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {# A more "HTML" way of creating the login form#} <form method="post" action="{% url 'user_login' %}"> {% csrf_token %} <div class="form-group"> <label for="username">Email</label> <input type="email" name="username" placeholder="Username" class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" required> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" name="password" placeholder="Password" class="form-control" required> </div> <div class="check-data"> <div class="form-group"> <input type="checkbox" id="signin" name="signin" value="Sign In"> <label for="signin" class="checkbox-label">Stay signed in</label> </div> <a href="#" title="Forgot your password?" type="button" data-toggle="modal" data-target="#forgot-modal" id="forgot-psw">Forgot your password?</a> </div> … -
Custom tag doesn't render template completely
so here's my custom tag: @register.inclusion_tag('app/comments_list.html', takes_context=True) def show_comments(context): request = context['request'] comments_list = Comments.objects.all().order_by('-comment_time') paginator = Paginator(comments_list, 3) page = request.GET.get('page') try: comments = paginator.page(page) request.GET except PageNotAnInteger: comments = paginator.page(1) except EmptyPage: comments = paginator.page( paginator.num_pages) return {'comments': comments} and here's my template to render: {% for comment in comments %} {% if comment.commented_by.username == user.username %} <h6><font color="green">You</font></h6> <h7>{{ comment.comment_time }}</h7> {% else %} {{comment.commented_by}} {% endif %} <div class="comment"> {{comment}} </div> {% endfor %} My model: class Comments(models.Model): commented_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) comment = models.TextField(max_length=300) comment_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.comment For some reason it successfully renders {{comment.commented_by}} and {{ comment }} and completely ignores if condition and {{ comment.comment_time }}. And I have no idea why. Any help will be appreciated! Thank you!