Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using a modal to select quatities
I'm trying to implement a system to sell books, first I implemented a way to look into my database for the data of my books, for example if I look for "Algebra" I get: 0: Object { id: 1, titulo: "Algebra", coleccion: "AM" } 1: Object { id: 3, titulo: "Algebra II", coleccion: "AM" } with that I would like to use a modal to have something like. Algebra [ ] Algebra II [ ] [Ok] [Cancel] And then I can use as: Algebra [ 3 ] Algebra II [ ] [Ok] [Cancel] But I don't know how can I do this. This is the code of my django template. {% extends 'base.html' %} {% block content %} <form method="GET" action="{% url 'libros:buscar' %}" id="buscador-libros"> <div> <input type="text" , name="titulo" /> <input type="submit" value="Buscar" /> </div> </form> <script type="text/javascript"> $(document).ready(function() { $("#buscador-libros").submit(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: $(this).attr("method"), data: $(this).serialize(), success: function(json) { console.log("perro"); console.log(json); } }); }); }); </script> <!-- The Modal --> <div id="selector-cantidades" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> <form> **titulo**:<br /> <input type="number" name="Cantidad" /><br /> </form> </div> {% endblock content %} Any ideas on how to do it? -
What is a good way to store visits and clicks in a django app
I have a website built in Django in which I need to save clicks to specific ads and also page visits to be shown in a dashboard. Right now they’re being saved in the database itself but it is growing too much every day and I’m afraid it will impact on performance. What alternative do I have to store this simple user tracking data and retrieve it? -
How can I integrate a list in place of static values in charts.js/javascript with a list that is dynamically loaded from django backend?
I want to dynamically load database datas to fill a chart. I am using django as backend and chart.js for visualization. "images": [{ "zoomLevel": 5, "scale": 0.5, "title": "Brussels", "latitude": 50.8371, "longitude": 4.3676 }, { "zoomLevel": 5, "scale": 0.5, "title": "Copenhagen", "latitude": 55.6763, "longitude": 12.5681 }, { "zoomLevel": 5, "scale": 0.5, "title": "Paris", "latitude": 48.8567, "longitude": 2.3510 }] This above code is my javascript default code. I want to pass the above values dynamically from django backend as mentioned below: for item in Listings.objects.all()[:5]: images.append( { "zoomLevel": 5, "scale": 0.5, "title": item.neighbourhood, "latitude": item.latitude, "longitude": item.longitude } ) Here, Listings is a model and neighbourhood, latitude and longitude are its fields. I am passing only 5 values here so it makes a list named images containing 5 dictionary elements. return render(request, template_name, {"context": images} Now, I pass it to javascript as context. {% autoescape off %} <script type="text/javascript"> var arr_images = {{ context }}; </script>{% endautoescape %} Then, in the html, I loaded the context in a variable named arr_images. "images": arr_images Now, in javascript, I want to load the whole list as a part of code, just like the code in the top but due to some reason, only … -
Field required when using two forms in Django
I have a template in my Django project where i'm using the same form two times. The form is the same, but each of them has a different use case for the user. The problem when using two forms is that if i try to use the first one, the data will NOT be sent to the database, as i will get this error This field is required.. That's because if i compile one form, the second one, being not compiled, will throw the error. Is there any way to solve this? <h3> First form </h3> <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form %} <button type="submit" class="btn btn-danger style="background-color: red;">SUBMIT</button> </form> <h3> Second form </h3> <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form %} <button type="submit" class="btn btn-danger style="background-color: red;">SUBMIT</button> </form> -
'CommentForm' object has no attribute 'cleaned_data'
I tried this if form.is_valid() and request.user.is_authenticated():, it shows me that, bool obj is not callable. then i tried without parentheses then it shows error that, 'CommentForm' object has no attribute cleaned_data. please help me out, it would be appreciated. def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > timezone.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form":form, } return render(request, "post_detail.html", context) -
Getting a circular import error in django urls
I'm getting the following circular import error in the project level urls.py file: ImproperlyConfigured: The included URLconf 'pres_value.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. To be clear, pres_value is the project level and present is the app level. So apparently the error is occurring in the project level urls file. The app has been registered in the settings.py file. Any help on what's wrong here is appreciated. Project level pres_value/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('present/', include('present.urls')), ] App level present/urls.py: from django.urls import path from .views import HomePageView, PresentValueView, AboutPageView, ResultView urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('pv/', PresentValueView.as_view(), name='present_value'), path('result/', ResultView.as_view(), name='result'), ] -
Django: collectstatic fails locally after configuring django-storages for AWS S3
I'm trying to configure my webapp, so when deployed to Heroku it will acept files (audio, video) and stores them in Amazon S3 Bucket. I've made the necessary changes in settings.py but now I cannot use python manage.py collectstatic. I'm also hopping my configurations lets my app recieve and store files in AWS S3. I get this error: File "D:\virtual_envs\universidad_elim\lib\site-packages\botocore\handlers.py", line 219, in validate_bucket_name if VALID_BUCKET.search(bucket) is None: TypeError: expected string or bytes-like object .env: In my env file, I've: AWS_STORAGE_BUCKET_NAME = 'universidad-elim-test-videos' AWS_S3_REGION_NAME = 'us-west-1' # Tell django-storages the domain to use to refer to static files. AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_ACCESS_KEY_ID = 'XXXX' AWS_SECRET_ACCESS_KEY = 'XYXYX' Apparently it's something related to botocore library. setttings.py: The app works correctly (renders index.html and contents). The problem is when trying to collecstatic files. """ Django settings for el_comercio_app project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from decouple import config from dj_database_url import parse as dburl # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS … -
Invalid literal for int() with base 10 : "some string", but the field in question is a foreign key to a charfield
I keep getting the invalid literal error for an int() with base 10. The field in question is a foreign key to a class that only has one attribute and that attribute is a CharField, so I don't understand why I keep getting this error. If I try to query the the Progress class it works fine, but when I search for a value for progress within the Tasks class I get the error. I have already tried clearing my my migrations and re-migrating, it had no effect. class Program(models.Model): name = models.CharField(max_length=30) class Tasks(models.Model): program = models.ForeignKey(Program, max_length=30, on_delete=models.CASCADE) Shell >>> from app.models import * >>> a = Program.objects.filter(name="GM") >>> print(a) <QuerySet [<Program: GM>]> >>> a = Tasks.objects.filter(program="GM") ValueError: invalid literal for int() with base 10: 'GM' I should be able to grab this object and manipulate it, I am certain that there is an object with program set to "GM". -
mutex on different instances of django model
I'm creating a django-docker project where each user has their own docker container running an agent that manages their blockchain wallet. The problem I'm running into is that sometimes the server needs to start a container to manage user connections, and the user starts their docker container on login as well. If the server and the user both logout at the same time, it may try to delete a container twice. likewise if the user and the server start a docker container at the same time, we would have two copies of the same docker container running. I've used a couple semaphores and a lock to solve the problem on paper, but I'm wondering if I create two agent objects using: agent_obj_1 = agent.objects.get(wallet_name=request.session["wallet"]) agent_obj_2 = agent.objects.get(wallet_name=request.session["wallet"]) agent_obj_1.start() agent_obj_2.start() where each agent has a lock and semaphore local variable, and I lock the mutex on agent_obj_1, can I still lock agent_obj_2 because they are different instances? or can I not lock agent_obj_2 because it is only a different referance pointing to the same object in memory as agent_obj_1? ie. do agent_obj_1 and agent_obj_2 share a lock instance variable defined in the __init__() method? here is the relevant part of my … -
How to Save Table Row On Change (Django/Ajax)
I have a table which is populated by iterating over various records in a local database. Nested within the table data are divs which hold different HTML objects such as textboxes and dropdown menus which are subject to user input. Upon a change to one or more of these elements in a particular row, I would like to update the database record with the data in the table row. Do I need individual AJAX payloads for each HTML element for which I want to save data? Or am I able to assign an ID to the table to reference in my AJAX? If so, then how would I specify which row needs to be updated since rows are dependent upon the iteration which creates them? template.html <table class="table is-fullwidth is-striped is-bordered"> <thead> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 4</th> <th>Header 5</th> </tr> </thead> <tfoot> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> <th>Header 4</th> <th>Header 5</th> </tr> </tfoot> {% for object, opportunity, account_manager, presales_engineer, inside_solution, time in object_zip %} <tbody> <tr> <th> {{ object.opportunityId }} </th> <td> <div class="select"> <select name="status" id="cw_status"> <option value="{{ opportunity.status.id }}">{{ opportunity.status.name }}</option> <option value="Lost">Lost</option> </select> </div> </td> <td> <div class="select"> <select name="account_manager" id="account_manager"> <option value="{{ … -
I do pagination on the site, but when I add it to the template, there’s nothing at all
I did pagination with when adding it to the template should have appeared a couple of pages but for some reason on the page where the pagination should be displayed nothing is displayed. And I do not know whether to create a model for this? my views.py class ArticleIndex(ListView): model = Articles template_name = 'news/posts.html' def get_queryset(self): articles = Articles.objects.all() # Отбираем первые 10 статей paginator = Paginator(articles, 10) page = self.request.GET.get('page') try: articles = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. articles = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. articles = paginator.page(paginator.num_pages) return articles posts.html <div class="pagination"> {% if articles.has_previous %} <a href="?page={{ articles.previous_page_number }}">←</a> {% endif %} {% for num in articles.paginator.page_range %} {% if num == articles.number %} <span class="current"><b>{{ num }}</b></span> {% else %} <a href="?page={{ num }}"> {{ num }}</a> {% endif %} {% endfor %} {% if article_list.has_next %} <a href="?page={{ article_list.next_page_number }}">→</a> {% endif %} </div> -
Can I interpret Django object values as JSON data within the JS script in my HTML?
I've hit a bit of a stumbling block with a Django project having added a chart to a page using Chart.js only to find that it relies on the data inputted being in JSON format. I've researched ways of converting Django object values into JSON, such as serializing and re-writing my views, but for a number of reasons these aren't ideal options for me. Is there a way to convert Django object data to JSON data within the JS script? I have an 'Accelerator' Django model with five separate decimal fields which ultimately need to be converted to JSON to feature in the chart. For each object created, the value of each field is prone to change (they are determined by a method calculating the mean value of separate values inputted into a separate model). I have an 'accelerator_detail' HTML template which renders and displays the various values of individual objects created using the Accelerator model. This template is heavily reliant on Django placeholders and Python logic calling on object values, which is one reason why I'm hesitant about attempting to serialize the Django objects as JSON within my views (presumably this would mean I would have to re-write this … -
Checked checkbox does not send bolean to database
I created a custom signup page. I want the user to have, by default, two boolean field is_nhs and agree_conditions. However, the checked attribute in my html i snot working. The database does receive it. In fact, if I login as superuser in the django dashboard, the attribute is_nhs and agree_conditions are always set to false (red cross). My custom user model: class CustomUser(AbstractUser): first_name = models.CharField(max_length=100, default='') last_name = models.CharField(max_length=100, default='') organization = models.CharField(max_length=100, default='') location = models.CharField(max_length=100, default='') postcode = models.CharField(max_length=100, default='') phone = models.CharField(max_length=100, default='') agree_conditions = models.BooleanField(default=True) is_nhs = models.BooleanField(default=False) def __str__(self): return self.email My signup.html <form> <div class="form-group form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1" checked="checked"> <label class="form-check-label" for="exampleCheck1" name="agree_conditions">Agree conditions</label> <a href="{% url 'conditions'%}">Click here to see the conditions you are accepting</a> <div class="form-check" hidden> <input class="form-check-input" type="radio" name="is_nhs" id="exampleRadios1" value="Yes" required checked> <label class="form-check-label" for="exampleRadios1"> Yes </label> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> I tried to change unsuccessfully to checked_attribute following this guide: What's the proper value for a checked attribute of an HTML checkbox? Moreover, I find strange that agree_conditions (in my model's field) show a red cross (in the admin/superuser dashboard) even if it is by defaul=True -
django allauth login test can't login correctly
I'm trying to write a login test for django allauth but although the app works correctly and I can login, when I write a login test it fails to login correctly and I get an assertion error Response didn't redirect as expected: Response code was 200 (expected 302) 302 != 200 because of a validation error `'The e-mail address and/or password you specified are not correct' Looking at the tests in django all-auth here: https://github.com/pennersr/django-allauth/blob/master/allauth/account/tests.py I can see that they also create an EmailAddress object when testing login - I'm not sure why or if this is needed? class TestLoginView(TestCase): def setUp(self): self.client = Client() self.username = "test@test.com" self.password = "password" user = get_user_model().objects.create_user(self.username, self.password) # EmailAddress.objects.create(user=user, email=self.username, primary=True, verified=True) def test_login(self): response = self.client.post(reverse( settings.LOGIN_URL), {"login": self.username, "password": self.password} ) self.assertRedirects(response, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False) def test_wrong_login(self): response = self.client.post(reverse( settings.LOGIN_URL), {"login": "bad@login.com", "password": "wrong"} ) validation_error = 'The e-mail address and/or password you specified are not correct' assert validation_error in response.content.decode('utf-8') -
Suggest Me About Learning
I have just finished Django For Beginners by William S. Vincent. Now I am learning basic CSS, HTML from freeCodeCamp.org. What should I do now to become proficient in Django? Should I finish another tutorial on Django(like Django For Girls) or should I revise the previous one another time? Thanks in advance. -
AttributeError: 'bytes' object has no attribute
I have a class in which I am checking user permissions, and depending on them, I return a list of results from models. Here is what I have: from AnnualLeave.models import Leaves, RejectedLeaves, Employee class GetLeaves: def get_results(request): try: if request.user.groups.filter(name__in=['SuperAdmin']).exists(): return Leaves.objects.all() elif request.user.groups.filter(name__in=['Admin']).exists(): return Leaves.objects.filter(employee_id=Employee.objects.get(manager_id=request.user.pk)) else: ... except (Leaves.DoesNotExist, Employee.DoesNotExist): return [] def process_results(request): leave_request = [] for leave in GetLeaves.get_results(request): .... .... leave_request.append(content) return leave_request And then I'm calling process_results function in TemplateView like this: class ProcessLeaveRequest(TemplateView): template_name = 'LMSAdmin/process_leave_request.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, {'leave_requests': GetLeaves.process_results(request)}) From what I can see, it is reading the entire webpage with the request parameter in functions. Like the get_results function is not returning a list, but the entire webpage. I do not understand why this is happening because it was working fine before without any changes. Any help would be really appreciated. -
manual facebook login process with flutter
I'm trying to implement facebook login with flutter using Django Rest Framework as the backend with rest-social-auth dependency for social login. This dependency doesn't take the access_token, which the facebook sdk provides by default but it takes the code, as stated in https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/#login. The problem I'm having is that now, I have to show the facebook login popup by myself to the user and wait for a response from backend. the url used is something like: https://www.facebook.com/v3.3/dialog/oauth ?client_id=1234567890 &redirect_uri=https://example.com:8000/redirect/uri/ Currently, I'm trying to do this: User taps on 'login with facebook' button (it's just a common button with onPress method) App shows pop with facebook auth popup (don't know how to implement this) If user accepts, the facebook will return a code to backend Backend exchanges that code (via rest-social-auth) for an access token, gets user data and authenticates her. Backend sends message back to mobile client with jwt token. Is that approach correct? If it's ok, how can I invoke the facebook authenticate popup from flutter and capture the response sent by backend? So.. Here are some questions: Should the redirect_uri be a backend endpoint or should it be sent back to mobile and the mobile sends a request … -
Django Autocomplete, how to get the ID but show the text value
thanks for looking at my problem: How do I display the text in the form textbox, but retrieve the ID on posting the form. Everything works as expected with Autocomplete, expect for correctly displaying the reps name. When I try this below I can post the form, using the PK, but the pk number is displayed rather than the reps name. I want to see the reps name in the text box view.py rep_json = {} rep_json['id'] = item.pk rep_json['label'] = f'{item.rep_first_name} {item.rep_last_name}' rep_json['value'] = item.pk I have tried various combinations to get this to work, but when I can display the text in the textbox, the validation fails on the pk. The field being autocompleted is foreign key, hence the validation failure. sandbox.html <script> $(function() { $("#autoc").autocomplete({ source: "/autocomplete/", minLength: 2, }); }); </script> <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> forms.py class sales_form2(forms.ModelForm): class Meta: model = sales fields = ( 'position', 'rep', 'comm' ) widgets = { 'rep': forms.TextInput(attrs={'style':'width:100px','data-url':'autocomplete/','id':'autoc'})} views.py - Autocomplete def sandbox_complete(request): if request.is_ajax(): q = request.GET.get('term', '') theReps = reps.objects.filter(Q(rep_first_name__icontains = q)|Q(rep_last_name__icontains=q)) results = [] for item in theReps: rep_json = {} rep_json['id'] = item.pk rep_json['label'] = f'{item.rep_first_name} {item.rep_last_name}' … -
Having a Django serializer return two flat lists
With a serializer like this... class MyPriceSerializer(serializers.Serializer): prices = serializers.SerializerMethodField() def get_prices(self, obj): return obj.prices.values_list('price', flat=True) class ChartData(RetrieveAPIView): queryset = Market.objects.all() authentication_classes = [] permission_classes = [] serializer_class = MyPriceSerializer ...I can pick up a flat list like this on the other end: { "prices": [ 0.52, 0.55, ... 0.94, 0.93 ] } And if I change the serlializer to return obj.prices.values_list('price_date', flat=True), I can get this: { "price_dates": [ "2019-07-22T15:19:02.924811Z", "2019-07-22T15:19:02.924811Z", ... "2019-07-22T15:58:41.337422Z", "2019-07-22T16:04:16.753870Z" ] } But is it possible to get both (as below) in one serializer, so that I can pick up the result in one Ajax call in a template? { "prices": [ 0.52, 0.55, ... 0.94, 0.93 ] } { "price_dates": [ "2019-07-22T15:19:02.924811Z", "2019-07-22T15:19:02.924811Z", ... "2019-07-22T15:58:41.337422Z", "2019-07-22T16:04:16.753870Z" ] } -
How to count items in a dict and filter based on item ID?
I am querying the following dict that uses Users and Groups from Django contrib auth: In views.py I pass the following as context to the template: group_user_dict = {group: group.user_set.all() for group in Group.objects.all().order_by('id')} It's then easy enough to loop through all the items: {% for group, users in group_user_dict.items %} {{ group.id }}: {{ group.name }} {% for i in users %} {{ i.get_full_name }} {% endfor %} {% endfor %} However, how can I: Count the number of users in each group and display this in the template? E.g. {{ group.users_set.count() }} display just the results from the first, second, third (etc...) group? E.g. Group 1 ID, Group 1 name: Users in group 1 only. -
How to set max for positiveintegerfield
I am writing a model in django. I want to set a maximum number for a positiveintegerfield. How can I do that? -
Django: use AWS to host files only when DEBUG is False
I've a Django App hosted in Heroku. It works fine: I've only my static files (CSS) and it generates an Editorial object dayly trhough a command. You can visit my app here: https://el-comercio-editoriales.herokuapp.com/ However, now I need to host some upload user file, for this I'm using Amazon S3. But somehow now my app does not work locally, and don't know if it will work if I make a push to Heroku. So I'd like your help to determine what I've set wrong in my settings file: """ Django settings for el_comercio_app project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from decouple import config from dj_database_url import parse as dburl # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['127.0.0.1', 'el-comercio-editoriales.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'editorial.apps.EditorialConfig', 'storages' ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'editorial.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'editorial', 'templates/'), os.path.join(BASE_DIR, … -
Django pagination returning <Page 1 of 1> instead of list
Inspired by the official Django documentation, I want to retrieve pages of 20 logs at a time using this function: logs_list = ( Log.objects.filter(modified_object_id=device_id) .order_by("-created_at") .values( "username", "action_type", "modified_model_name", "modified_object_name", "group_name", "role_name", "workspace_name", "created_at", "modification", "modified_object_id", "user_id", ) ) # Pagination paginator = Paginator(logs_list, 20) try: logs = paginator.get_page(page) except PageNotAnInteger: # If page is not an integer, raise exception ValidationError("page_number_invalid") except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. return Response(data=[], status=status.HTTP_200_OK) print(logs) return Response(data=logs, status=status.HTTP_200_OK) I know that the device_id (UUID) and page(int) variables are correct. The logs_list Queryset contains multiple, valid values, but the logs value shows up as <Page 1 of 1> when it is printed, and the output of this method is {}. Why is the pagination not working correctly? -
Send emails via mailjet with django
I am trying to implement a reset password functionality and I want to use the mailjet for sending an email. So far I have been using the django views fro reset password just overwriting the html files. I have set up the EMAIL_BACKEND in the settings, but I do not get emails - do I need to write separate views? -
Creating a models.UniqueConstraint in abstract model
I am creating an abstract model for my django app, SrdObject. One of the characteristics of my model is that it has a pair of fields that, taken together, must be unique: 'name' and the foreign key 'module'. Here is an example of what I had class SrdObject(models.Model): name = models.CharField(max_length=50) slug_name = models.SlugField(max_length=75, unique=True) active = models.BooleanField(default=True) module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='%(class)s', blank=False, null=False, default='default') class Meta: unique_together = ['name', 'module'] ordering = ['name'] abstract = True This seemed to be working ok, but the unique_together attribute has been marked as deprecated by django (See here), so I changed it to this class Meta: constraints = [ models.UniqueConstraint(fields=['name', 'module'], name='unique-in-module') ] ordering = ['name'] abstract = True This doesn't work because the name field must be unique, and since this is an abstract class, the constraint is repeated over several models. I also tried models.UniqueConstraint(fields=['name', 'module'], name='{}-unique-in-module'.format(model_name)) But obviously this falls into scoping problems, so I tried a decorator method def add_unique_in_module_constraint(cls): cls._meta.constraints = [ models.UniqueConstraint(fields=['name', 'module'], name='unique-in-module') ] return cls @add_unique_in_module_constraint class SrdObject(models.Model): class Meta: ordering = ['name'] abstract = True But this didn't seem to do anything. So how do I create a models.UniqueConstraint in abstract model …