Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - export one-to-many in csv using one row per foreign key
I have a postgres database in Django and one of the tables has a foreign key and a number of entries. I want to generate a csv file with one row per foreign key. i.e. this is the table AuthorID Bookname Price 1001 “I love django” 3.40 1001 “Python is cool” 4.20 1002 “Pandas is cool” 5.10 The resulting csv should look like this AuthorID,Bookname1,Price1,Bookname2,Price2 1001,I love django,3.40,Python is cool,4.20 1002,Pandas is cool,5.10,, Can you help me with that? Is there a native way to do it in Django or in Postgres using raw sql? Thanks -
Question about EnviromentFile config setting for Gunicorn and Django production, do I need to use it?
I have a Django app in production, using gunicorn for help. I have a question about the setting EnviromentFile, should I refence the venv path for my project? Is it mandatory? The reason why I'm not adding it in my service file, is because I'm not serving any variables through the env. /etc/systemd/system/gunicorn.service : [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/alpha/project ExecStart=/home/user/alpha/project/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project.wsgi:application [Install] WantedBy=multi-user.target Do I still need to add, EnviromentFile,to my file above? And if I do, is referencing the activation needed? Like so: EnviromentFile=PATH/TO/venv/bin/activate? -
How do I get datatables to work with bootstrap4 tabs in Django templates?
I have a Django template with multiple tables. I am using Bootstrap 4 with datatables. I wanted to put my tables in tabs, and that is giving me problems. If the tables are not in tabs, this code works fine: $(document).ready(function() { $('.datatable').DataTable( { dom: 'Blfrtip', buttons: [ 'copy', 'csv', 'excel', 'print' ] } ); } ); I looked at these two links: Scrolling and Bootstrap tabs and Hidden initialisation. And got the snippet at the bottom of this post to work as datables (though the table widths have issues in Django). However, that snippet only works with hard-coded tables. In my Django template, I am using template tags to loop through query strings like this: {% if items %} <table class="table table-striped table-valign-middle datatable" id="data"> <th>Item Table</th> <thead> <tr> <th>Title</th> <th>Price</th> <th>Date</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{ item.item.title|truncatechars:25 }}</td> <td>{{ item.price }}</td> <td>{{ item.date }}</td> </tr> {% endfor %} </tbody> </table> {% else %} <div class="text-center font-weight-bold"> No items </div> {% endif %} In Django using the snippet example, if I replace the first tab's hard coded table with that template for loop, the datatable only works for the first tab (i.e., no … -
PUT POSTGRESQL DATABASE ONLINE
I'm working on a Django Project in which I'm using a postgresql database. Now I have to put my project online on python anywhere, but I looked at some videos and they put the database on AWS. I don't understand why can't I put also the database on python anywhere but I have to put it on AWS for example. I'm sorry if it is a dumb question but this is my first experience with backend. -
How to send a JavaScript variable to Django to use in views.py
I have a model that contains information about the different buildings being displayed on my website. When a user selects one of the buildings I would like that information to be displayed. When the user selects a building, a JavaScript variable contains the building name that the user selected. How can I send this variable to my views.py so I can get the building object specified by the "name" JavaScript variable? Here is what I currently have for my views.py, the building name "Harris" is hard coded in. This is where I would like to put the JavaScript variable, so I can display the buildings information depending on which one the user selects. from django.shortcuts import render from django.http import HttpResponse from .models import Building def index(request): buildings = Building.objects.get(buildingName = "Harris") return render(request, 'index.html', {'buildings': buildings}) I am new to Django so any information is helpful. Thanks -
How to use django ORM to query database
I have a model called 'dboinv_product' and this model has a field called 'product_name' I need to use Django ORM in my views.py file to pull ALL the product names. The goal is to put it into a list this way I can serialize it using JSON. Does anyone know which Django command(s) can be used to produce this list? Essentially, I need the equivalent of "SELECT ALL product_name FROM dbo.inv_product" -
Algorithm: track relationship changes of 3 elements
I want to log changes in 2 elements related to a 3rd one, but I can't come up with a nice algorithm to it. Let there be 3 objects (or components) that can be installed one inside the other (like russian dolls), and their state change when you put them in or take them out: A is installed in B and B is installed in C. A is taken out of B, but B still is in C. (A becomes avaiable) A and B are taken out of C. (A and B become available) I have 3 different classes defining the 3 components, but I'm not sure how to log the changes... on the same object? on a different class just for logging? Is there a pattern I should use as a base case? COMPSTATUS = ((1,'Available'),(2,'In use')) class A(models.Model): id = models.AutoField(primary_key=True) class B(models.Model): id = models.AutoField(primary_key=True) compA = models.ForeignKey(A, on_delete=models.PROTECT) status = models.CharField(max_length=2,choices=COMPSTATUS,default='1') class C(models.Model): id = models.AutoField(primary_key=True) compB = models.ForeignKey(B, on_delete=models.PROTECT) status = models.CharField(max_length=2,choices=COMPSTATUS,default='1') -
django tcp connection to models, FATAL: sorry, too many clients already database
First, let me say that I am new to Python i connected to djnago with tcp socket and i run the server with custom script and setup.djangu(), i get , create, and updated models with tcp and works fine , but problem is if 100 user coonected to a socket and be online i get this exception conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: sorry, too many clients already And I'm going to have a lot more online users than that,this is interesting to me i get online query from from django.db import connection and i see just two connection is online, if i connected with django plugin why other connections wont show, My question is how can I control postgress connections and use one or multi conecction to database, not per user in django with tcp connection, and i can work with django syntax ? thanks -
How to use dynamic urls to go to a database item
How do I make my website that going to the url 'mywebsite.com/1/' would show an item in the database that's id is 1 (and the same for /2/, /3/, etc.)? All the tutorials I have found are for setting up 'urls.py' in the older versions of Django. -
filter queryset of unique objects in django
Hi, I have a model in django lets say UserProfile and it has some data as like this. I want to filter over this model in such a way that if there are multiple records for same user_auth_id (for example user_auth_id=279) then I will take the last one. By this way I want to get the queryset from this model. What will be the filter expression here? From this example my queryset will be [247, 248, 249, 250, 251, 252, 312, 254, 255, 260, 262] -
Respect django tables order
is there any way to make django respect the data base order once I make migrations?, I constantly make some changes and when I see the data base tables the order changes and it is a bit disgusting. -
Django redirect URLs in modal forms
I am new with Django so I created a delete_orders modal form and now I want to redirect to the true path after deleting the order. My views.py is something like: def deleteOrder(request, order_id): order_item = Order.objects.get(id=order_id) customer = order_item.customer.username url = request.META['HTTP_REFERER'] parsed_url = urlparse(url) url_path = parsed_url.path if '/panel/profile/' in url_path: url_path = '/panel/profile/' + customer if request.method == 'POST': order_item.delete() return redirect(url_path) context = {'order_item': order_item} return render(request, '', context) And my urlpatterns is: path('<int:order_id>', views.deleteOrder, name='delete_order'), I want to know if it is a good practice to do the job or we have some other standard solutions? -
How to link some users with an OAuth application to allow or deny authentication based on that application in django-oauth-toolkit?
I'm using django-oauth-toolkit to do user authentication with DRF, my goal is to allow or deny authentication based on the OAuth application linked to the user. Let's say that I have application-one with user-a linked to it and application-two with user-b linked to it, now if user-a or user-b tries to provide different client_id:client_secret than the one for that OAuth application each one is linked to it, authentication should be denied. That's useful because if I created two OAuth applications, one for android users and the other for web users I can deny authentication for users who are not linked to with requested OAuth application or allow access for users who are linked to the correct OAuth application. I didn't find anything useful in the docs or over the internet about linking some users or for that purpose although it sounds very helpful, so any tips or suggestion will be appreciated. Thanks -
Django 2.2 ORM Exclude Not Working as expected
Im trying to get all customer list form Cust models that not having a record in Stat (ForeignKey), Django 2.2 class Cust(models.Model): name = models.CharField(max_length=50) active = models.BooleanField(default=True) class Stat(models.Model): cust = models.ForeignKey(Cust, on_delete=models.PROTECT, null=True) date = models.DateField(null=True, blank=True) im trying this but doestn work, month = datetime.now() month = month.strftime("%Y-%m") inner_qs = Stat.objects.filter(date__icontains=month) data = Cust.objects.exclude(id__in=inner_qs) print(inner_qs) print(data) The query above returning: <QuerySet [<Stat: Ruth>]> <QuerySet [<Cust: Jhonny>, <Cust: Rony>, <Cust: Sinta>, <Cust: Ruth>]> As you can see, i need the result [<Stat: Ruth>] excluded from the data queryset/list. but what i expected is: <QuerySet [<Stat: Ruth>]> <QuerySet [<Cust: Jhonny>, <Cust: Rony>, <Cust: Sinta>> -
Django model linked to multiple model objects
I'm new to Django and am looking to create a surveys which contains a: subject area a sub-domain subject response option to that sub-domain The best I can do right now is create a survey object linked to a single sub-domain and a single response. Is there a way to return JSON for a survey linked to ALL defined subjects and related sub-domains? Or at least, have a way to create a survey with all subjects and sub-domains? -
how to connect to main db use django pytest
I am using django and pytest in my project. I need to write tests based on data in the main database. But pytest cleans up and creates a clean database every test run session. I need to use the main db, which is specified in settings.py. I need a way without copying all the data of the main database to the test one! import pytest @pytest.mark.django_db def test_my_user(): me = User.objects.get(username='me') assert me.is_superuser I want the information to be taken from the main database in this case -
django-rest-auth: avoid password and email being same
I am using django rest auth for registration. I am using email as login and the below are my settings ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = 'http://localhost:3000/login' I am trying the api end point rest-auth/registration/ Now if i pass email and password same, it does not raise password validaiton error. these are my password validators: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] How to ensure the password is not similar to email using dango rest auth -
Finding the Time Range to restrict the events occuring on same time in calendar. (django)
The Problem is, I want to restrict overlapping of events occuring on same date and same time. I want to show the overlapping Error to the user when he registered an Event on same date having same time i am unable to query the time range between start_time and end_time. Kindly suggest me the best way to restrict overlapping. models.py class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() created_date = models.DateTimeField(auto_now_add=True) group = models.ForeignKey(Group , on_delete= models.CASCADE , null= True , blank=True) priority = models.ForeignKey('Priority' , on_delete= models.CASCADE , null= True , blank=True) @property def get_html_url(self): url = reverse('event-detail', args=(self.id,)) return f' <a href="{url}"> {self.title} </a>' def create_event(slef): return f"http://localhost:800/event/create/" # def get_event_in_current_date(self): # # print(Event.objects.filter(date= self.date)) # return Event.objects.filter(date= self.date) @property def get_all_events(self): if Event.objects.filter(date= self.date).count() >1: url = reverse('event-all', args=(self.date, )) return f' <a href="{url}"> ... </a>' return "" @property def get_all_events_by_group(self): print(self.group) if Event.objects.filter(date= self.date , group= self.group ).count() >1: url = reverse('event-all-group', args=(self.date, self.group.name )) return f' <a href="{url}"> ... </a>' return "" def __str__(self): # print(self.date) return str(self.date) views.py class CreateEvent(LoginRequiredMixin , View): def post(self , request , *args , **kwargs): start_time … -
I want to keep data in my database after deletion and track it. How can I achive this goal?
i have a simple model Category. I want to soft delete instances and keep track of them in my db from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django_currentuser.middleware import get_current_user, get_current_authenticated_user from django_currentuser.db.models import CurrentUserField class Category(models.Model): name = models.CharField(max_length=80) created_on = models.DateTimeField("Created At", auto_now_add = True, null = True) created_by = CurrentUserField(related_name='created_by') updated_on = models.DateTimeField("Updated At", auto_now = True, null = True) updated_by = CurrentUserField(related_name='updated_by') deleted_on = deleted_by = def __str__(self): return self.name -
How to get composite of two tables in Django Queryset?
Is there a way to do the equivalent of a full outer join in Django (I think I've read that full outer joins are not supported). My scenario is that I have three tables: Staff / WeekList / WeeksCompleted The relevant fields I'm trying to work with are: Staff table - Staff Number. WeekList table - Week Start date. WeeksCompleted table - Week Start date and Staff Number. Basically, everyone should have an entry in the WeeksCompleted table (if they're still active, that is, but that's not pertinent for this question). The queryset I would like to produce is a list of Staff who have missing weeks in the WeeksCompleted table. I can get the result I want using SQL queries but it involves a full outer join on the Staff and WeekList tables. I was wondering if anyone knows of a way to do this using the queryset functions? -
Django, Ajax and JS . How to prevent page reloads and jump ups to the top of the page when i submit a comment
I followed a solution on how to get Django comment form to submit without page reloading and jumping to the top of the page. I tried many solutions online and offline but still no solution. I am new to Django Backend and Ajax, I will be happy if someone can help on how to deal with this. Thanks in Advance. JS AJAX $( document ).ready(function() { $(`.comment-form${post_id}`).submit(function() { $.ajax({ data: $(this).serialize(), type: $(this).attr('method'), url: $(this).attr('action'), success: function(response) { $(); }, error: function(response) { console.log('error', response) } }); return false; }); }); VIEWS from django.shortcuts import render, redirect from .models import Post, Like from django.contrib.auth.models import User from .forms import CommentModelForm from django.http import JsonResponse # Create your views here. def post_comment_create_and_list_view(request): qs = Post.objects.all() user = User.objects.get(pk=request.user.pk) #Comment form c_form = CommentModelForm() if 'submit_c_form' in request.POST: c_form = CommentModelForm(request.POST) if c_form.is_valid(): instance = c_form.save(commit=False) instance.user = user instance.post = Post.objects.get(id=request.POST.get('post_id')) instance.save() c_form = CommentModelForm() context = { 'qs': qs, 'user':user, 'c_form':c_form, } return render(request, 'posts/main.html', context) HTML <form action="" method="POST" class="comment-form" id='{{obj.id}}'> {% csrf_token %} <div class="input-group"> <input type="hidden" name="post_id" value={{obj.id}}> {{ c_form }} <div class="input-group-append"> <button type="submit" name="submit_c_form" class="btn btn-md u-btn-white g-color-red g-text-underline-hover g-brd-gray-light-v3 g-brd-none g-brd-top">Post</button> </div> </div> </form> -
Django multiple AJAX queries for images
I made a button the user can click and it makes a AJAX GET request to the backend class Image. The response is the image url. I paste the url into a image tag and display it on the template models.py class Image(models.Model): img = models.ImageField() views.py def ajax(request): from django.http import JsonResponse if request.is_ajax(): image = request.FILES.get('data') aaa = Image.objects.get(id=1) aaa = str(aaa.img.url) return JsonResponse({'image_query': aaa}, status=200) return render(request, 'components/ajax.html') AJAX (template) <button id="getData" class="btn btn-success">Get</button> <div id="seconds"></div> ... <script> $(document).ready(function () { $('#getData').click(function () { $.ajax({ url: 'ajax', type: 'get', data: { data: $(this).text() }, success: function (response) { $('#seconds').append('<img src="' + response.image_query + '" width="300">') } }) }) }) </script> Everything works fine and the image is rendered to the template! Now I dont want to query the image with ID=1, I want all images to be fetched to the template. I tried to do by adding a for loop into the views.py but it only returns the first element. if request.is_ajax(): image = request.FILES.get('data') for i in range(1, 5): aaa = Image.objects.get(id=i) aaa = str(aaa.img.url) return JsonResponse({'image_query': aaa}, status=200) I don't know what to modify that it will query every image in the DB. Does someone … -
Callback function of django leflet in forms
I am using django with django-leaflet. Normaly i can use the map.init callback function to add json layers. But when i am creating a form with a map in it django-leflet is using the callback function for the leaflet-draw. Anybody know how i can add functions for a json layer in the created callback function? <script> var geodjango_id_geom = {}; geodjango_id_geom.fieldid = 'id_geom'; geodjango_id_geom.modifiable = true; geodjango_id_geom.geom_type = 'LineString'; geodjango_id_geom.srid = 4326; function id_geom_map_callback(map, options) { geodjango_id_geom.store_class = L.FieldStore; geodjango_id_geom.precision = options.djoptions.precision; (new L.GeometryField(geodjango_id_geom)).addTo(map); }; -
django-rest-auth: LOGOUT_ON_PASSWORD_CHANGE: Is this session based or token based
I am using django-rest-auth I am implementing password change. I found this option: at https://django-rest-auth.readthedocs.io/en/latest/api_endpoints.html LOGOUT_ON_PASSWORD_CHANGE = False to keep the user logged in after password change I wanted to understand the flow. I sent my password details old_password new_password1 new_password2 to the endpoint /rest-auth/password/change/ (POST) curl --location --request POST "http://127.0.0.1:8000/rest-auth/password/change/" \ --header "Authorization:Token a42fdd3938ad24d8abd064d3fedhsh599115e38b6a" \ --header 'Content-Type: application/json' \ --data-raw '{ "old_password": "oldP" "new_password1": "newP" "new_password2": "newP" }' Now what happens to my token on LOGOUT_ON_PASSWORD_CHANGE = True -
how to handle failed recurring payments in razorpay?
I was trying to use the recurring module of Razorpay on the Django website. Although I successfully integrate Razorpay, I have no idea about how to handle the failure of recurring payments. Does anyone know how to deal with it? I mean how can I get a response that payment is failed for a particular user