Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How can i render a specific Django admin page from a view?
I know that can reverse to admin pages from a template by doing this: {% url 'admin:index' %} or {% url 'admin:app_model_add' %} But how can i render an admin page using the render function in my view? When i do render(request, template_name='admin/index.html') I get a blank looking admin page with the message "You do not have permission to view or edit anything" Furthermore, I am not sure what the syntax would be to render a specific admin template, i.e. the equivalent of using this reverse in a template: admin:app_model_add is not something like this in a view: render(request, template_name='admin/app_model_add.html') -
The function is.valid() returns false although it shouldn't
I have a form in one of my models and regardless of what I select it returns false. I don't know exactly where it comes from as my other form that is similar to this one except for the target_group queryset works just fine, there seems to be a problem with the html in the POST request. class ActivitiesForm(forms.Form): activity = forms.ModelChoiceField(label='Select your activities', queryset=Activity.objects.all()) target_group = forms.ModelChoiceField(label='Who is the report destined to?', queryset=OutputOutcomeImpact.objects.order_by().values_list('target_group', flat=True).distinct()) class Activities(TemplateView): template_name = 'blog/activities.html' context = {'title': 'Activities selection page'} def get(self, request): form_act = ActivitiesForm() form_act.fields['activity'].queryset = Activity.objects.filter(categories__sectors__name=request.session['sector']['name']) self.context['form_act']=form_act return render(request,self.template_name, self.context) def post(self,request): form_act = ActivitiesForm(request.POST) print(form_act.is_valid(),form_act) if form_act.is_valid(): request.session['activity'] = model_to_dict(form_act.cleaned_data['activity']) request.session['target_group'] = model_to_dict(form_act.cleaned_data['target_group']) return redirect('/about', self.context) Console print: False <tr><th><label for="id_activity">Select your activities:</label></th><td><select name="activity" required id="id_activity"> <option value="">---------</option> <option value="Municipal waste incineration" selected>Municipal waste incineration</option> <option value="Plastic upcycling">Plastic upcycling</option> </select></td></tr> <tr><th><label for="id_target_group">Who is the report destined to?</label></th><td><ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul><select name="target_group" required id="id_target_group"> <option value="">---------</option> <option value="Standard" selected>Standard</option> <option value="Investors">Investors</option> </select></td></tr> -
How to loop all groups AND users within those groups in a Django template?
How do I list all groups AND all users within those groups? So far I am able to list all the known groups, but not the users within those groups. For example in views.py I have: def group_management(request): group_list = Group.objects.all() return render(request, "app/group_management.html", {"group_list": group_list}) In group_management.html I have: {% if group_list %} <ul> {% for group in group_list %} <li>{{ group.name }}</li> {% endfor %} </ul> {% else %} <p>No group are available.</p> {% endif %} How do I extend this loop to include users associated with in that group. E.g. {% if group_list %} <ul> {% for group in group_list %} <li>{{ group.name }}. USERS: {% for user in group_user_list %} {{user.username}} , {% endfor %} </li> {% endfor %} </ul> {% else %} <p>No group are available.</p> {% endif %} I assume there is some extra code required in views.py but am unsure of where to start. -
Function name is not defined at HTMLButtonElement.onclick
Searched a lot of question with the same error but nothing helped. Am using Python/Django and here the HTML code am trying to make it work. here is my code: <tr class="gradeA odd" role="row"> <td class="sorting_1"> {{ item.book_name }} </td> <td>{{ item.book_subject }} </td> <td>{{ item.book_level }} </td> <td>{{ item.book_teacher }} </td> <td><input type="number" id="price_{{ item.id }}" style="width: 50px;"/> </td> <td><input type="number" id="commission_{{ item.id }}"style="width: 50px;"/> </td> <td> <button class="btn btn-primary" id="submit_button" onclick="addingTheBook_{{ item.id }}()"> إضافة </button> </td> </tr> <script> function addingTheBook_{{ item.id }}() { var the_price = document.getElementById('price_{{ item.id }}'); var the_commission = document.getElementById('commission_{{item.id}}'); window.location.href = '/vip/add/pricelist/' + {{ item.id }} +'/' + the_price.value + '/' + {{ current_vip }} +'/' + the_commission.value + '/'; } </script> Whenever I click the button with onclick attribute, it gives me the error addingTheBook_3 is not defined at HTMLButtonElement.onclick -
'function' object has no attribute 'get_extra_actions' on new endpoint
I am attempting to set up a new endpoint in my Django project: router.register( r"v1/alert-summary/(?P<alert_id>[^/]+)/page/(?P<page>[^/]+)", alerts_views_v1.alert_summary, basename="Alerts" ) Alerts is my model, and the method alert_summary is in the alerts.views.py file BUT IS NOT IN THE AlertViewSet class. @api_view(["GET"]) def alert_summary(request): data = "hello world" return Response(data=data, status=status.HTTP_200_OK) However, when I test this endpoint I keep getting this error: 'function' object has no attribute 'get_extra_actions' Google searches and StackOverflow scrolling have proven fruitless, I have tried this answer with no success, and this one doesn't apply as the method isn't inside the ViewSet class. What should I do? -
How to fix Time Out error 504 when calling www.googleapis.com:443 from lambda function (django)
I am setting up a backend (django) and frontend (react) application. Here I am trying to implement google sign in through google-auth pypi package. So the front end calls the google sign in -> gets the token and passes it to a backend endpoint that receives the token and passes it to id_token.verify_oauth2_token() to get the details (name, username email etc). Issue is that it works on my localhost well. Once I deploy the django package to lambda using Zappa, the HTTPS connection (1): www.googleapis.com:443 is timing out. Upgraded the google-auth package added domain to google api credentials Passing the google client ID to make the call Suspecting that there might be something on the AWS side that isn't allowing it to make an external get request. Not sure where to find this. class GoogleSignIn(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): # upon signing in using google sign in, the front end calls /users/google-sign-in, which calls this method. It passes a OneTime googleUserId # this methods verifies the one time googleUserId with google to make sure that the signed in user is for our platform. # On successful verification, the google side will reply with a 200 response as … -
How to annotate a postgis distance in a queryset in an specific unit?
i have a queryset in which i annotate the distance between a point and the location of the object like this: distance_subquery = Headquarter.objects.filter( organization_id=OuterRef('pk'), location__distance_lte=(search_location_center, D(m=distance)) ).annotate( distance=Distance('location', search_location_center) ).order_by( 'distance' ).values( 'distance' )[:1] how can i get the distance in an specific metric unit?, this parameter could be a variable in some way? as the documentation said, the distance function returns a distance object, and you could use distance."metric_unit" for get the distance in an specific unit, but i get and error there is a way i can have control over the annotated distance? -
Use login page to authenticate REMOTE_USER in Django?
I've got a Django application that uses REMOTE_USER to authenticate 'automatically' since we're in a Windows AD environment (this app is deployed on IIS). If a user is on another browser that isn't IE a pop-up box appears asking them to enter their credentials. We're trying to do away with the 'automatically log users in' and force users to login when they visit the page regardless of browser - but don't want them logging into a browser pop-up box when they hit the page. Currently our Django is setup and works to treat that 'authenticated user' as if they had used the Model Authentication (so it auths against AD, but uses the Django user table). I'm just trying to eliminate the pop-up login and make it a login page. How best is this accomplished? -
problem in displaying foreignkey objects in django
I am having two models Patient and Ipd, Patient can have multiple Ipd. I am trying to get Patient Info in IpdForm but don't know where I am getting wrong I have already tried "qs = Ipd.objects.get(patient__id=patient_id)" , "qs = Ipd.objects.filter(patient__id=patient_id)" but nothing worked models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); patient_id = models.AutoField(primary_key=True); gender= models.CharField(choices=GENDER, max_length=10) consultant = models.CharField(choices=CONSULTANT, max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=False, default = "") def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','patient_id','consultant','Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient', 'reason_admission', 'presenting_complaints', 'rooms', 'date_of_admission'] views.py: @login_required def ipd (request,patient_id): formtwo = IpdForm() qs = Ipd.objects.filter(patient_patient_id=patient_id) if request.method=="POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'a':qs,'form2':formtwo}) urls.py : url(r'^order/ipd/(?P<patient_id>\d+)/$', my_order.ipd, name='ipd'), html : <div class="card-panel"> <span class="blue-text text-darken-2">Name : {{ab.name}}</span> <br> <span class="blue-text text-darken-2">Phone : {{ a.phone }}</span><br> <span class="blue-text text-darken-2">Address : {{ a.address }}</span><br> <span class="blue-text text-darken-2">Gender : {{ a.Gender }}</span><br> </div> -
How can I return JSON response in case of 500 error?
Let's say I want to send an email through ajax, and I have this code in my method: send_mail( subject='subject', messagex='message', from_email='some_mail@domain.com', recipient_list=['some_mail@domain.com'] ) As you can see I made an error and instead of message, I passed messagex field. And I get AttributeError at /contact 'TypeError' object has no attribute 'message' How can I nicely pass this message as {error: "'TypeError' object has no attribute 'message'"} so it could be used in frontend? I tried using except Exception as e, but it doesn't catch it, as it is an error, not an exception. Any solutions? -
define quantity for each selected item in the same time
i have tried a lot to get an answer for my problem i'm working on a restaurant order management system , and apart of the system is a point of sale at the same time(for cashier) , when a customer visit to the restaurant , the cashier be able to fill a receipt,for example (3 pizza with 2 sandwich) models.py class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE , null=True,blank=True) ordering = models.ForeignKey(Order, on_delete=models.CASCADE , blank=True) quantity = models.IntegerField(default=1) #to make a new instance from order,but doesnt make! def create_order(sender, instance, **kwargs): instance.ordering.save() pre_save.connect(create_order,sender=ProductOrder) views.py class ProductOrderCreate(CreateView): form_class = ProductOrdering model = ProductOrder template_name = 'create_product_order.html' success_url = '/orders/' def form_valid(self,form): form.instance.ordering = Order.objects.order_by('-pk')[0] return super(ProductOrderCreate,self).form_valid(form) if the signal(pre_save) worked fine and after select a product,creating another field automatically(not formset) it will solve the problem i asked alot everywhere but still but still not solved , please someone help me out i much appreciate -
Why my javascript/ajax script is not executing?
I have: {% 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(json); } }); }); }); } </script> {% endblock content %} I get the json response from the server side fine but don't know why I can not show it in console or why is this still redirecting me. I mean why my script is not executing. This is in my header of base.html that is inerithed from. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> What is happening? -
How to get Sum with group by in Django query
I am trying to get Sum of my quantity with the group by product_id but it returns multiple records. I am working on Django and trying to get sum with group by so. I try with annotate and values. productinventory_ds = ( ProductInventory.objects.filter(product_id=product_id) .values("product_id") .annotate( instock_quantity_s=Sum("instock_quantity"), delivered_quantity_s=Sum("delivered_quantity"), ) ) But instead of giving one product id and sum of all the quantity. this query returns multiple results with the same product id. -
How to Handle Case When Item Does Not Exist
I have a simple for loop which iterates through all objects in a local database. For each object, I reference a presalesEngineer and pass that ID to an API call to retrieve a JSON response. However, there are records in the database for which there is no value for presalesEngineer. When this is the case, the empty string throws a HttpError when a bad URL is passed to the API call. How can I handle when presalesEngineer does not exist, so the API is not passed an empty value? views.py objects = Opportunity.objects.all() for object in objects: if object.presalesEngineer: presales_engineers = [cwObj.get_member_by_id(object.presalesEngineer) for object in objects] else: presales_engineers = 'None' -
Django: CI/CD, BitBucket Pipelines and VPS
Is it possible to have CD set up for BitBucket repo, so that once the code is commited/merged into dev branch, tests are run in BitBucket(or other) cloud, and if tests pass, git pull is triggered on VPS as well as python manage.py commands? -
Django Forms - Is 'readonly' safe to use?
I created a form in Django. In this form, there is a field that must not be edited by the user, because the default value of the form must be sent to my database as it is. I come up with the following solution, but after making some research, i've come to find that using readOnly is generally not a good idea. Can someone clarify me on this? Should i go with another solution? tst = forms.CharField( initial='//value to be sent to the db without being touched', widget=forms.TextInput(attrs={'readonly':'readonly'})) -
PostgreSQL database design for Django real estate website
I'm working on a real estate website, and am struggling to define a design for my DB. Database needs to store Properties, attributes, property category/subcategory, and have them be linked all together. I could easily solve said problem by hard-coding property categories/subcategories in code, but would like to have it be more dynamic. Now, I want to have categories table having ID and category title, then subcategories table having ID, title and ID of a category it belongs to, so a rather basic manytoone relationship. I also need a more dynamic approach to attributes, so that I have one table, with ID, title and subcategory_id, where I'll limit attributes so that they can only be used for properties in certain subcategories. With this said, I'm having an issue figuring out how would I form a table for properties, so that it stores all the properties and its attribute/value pairs. NOTE: I'm doing this in Django.