Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files are not loading after deployment on digitelocean
I have deploye my django application on digitel ocean by following this blog:alocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 this is the url as an error i am getting in console for static files (index):5913 GET http://67.205.160.21/static/js/dashkit.min.js net::ERR_ABORTED 403 (Forbidden) (index):5913 GET http://67.205.160.21/static/js/style.js net::ERR_ABORTED 403 (Forbidden) every thing is fine except static file, settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') after running the python3 manage.py collect static it gives this /home/podstatsclub/webapp/Podcast_stats/static which i have put into default.config file which look something like this Alias /static /home/podstatsclub/webapp/Podcast_stats/static <Directory /home/podstatsclub/webapp/Podcast_stats/static> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/podstatsclub/webapp/Podcast_stats/podcast> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess Podcast_stats python-home=/home/podstatsclub/webapp/Podcast_stats/env pytho> WSGIProcessGroup Podcast_stats WSGIScriptAlias / /home/podstatsclub/webapp/Podcast_stats/podcast/wsgi.py -
Django framework list all products and sum all sales for each
Models.py class Entity(models.Model): entity = models.CharField(max_length=40) class Period(models.Model): period = models.CharField(max_length=10) class Product(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, default=None, blank=True, null=True) period = models.ForeignKey(Period, on_delete=models.CASCADE, default=None, blank=True, null=True) sku = models.CharField(max_length=12) class Sale(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, default=None, blank=True, null=True) price = models.DecimalField(max_digits=11, decimal_places=2) Views.py if request.method == 'POST': if form.is_valid(): entityquery = form.cleaned_data['entity'] periodquery = form.cleaned_data['period'] entities = Entity.objects.get(entity=entityquery) periods = Period.objects.get(period=periodquery) products = Product.objects.filter(entity=entityquery, period=periodquery).values('id', 'period', 'entity', 'sku') for sales in products.iterator(): sales = Sale.objects.filter(product__sku=product.sku, product__entity=entityquery, product__period=periodquery).aggregate(Sum('price')) return sales args = {'form': form, 'products': products, 'periods': periods, 'entities': entities, 'sales': sales} return render(request, "products_list.html", args) Expected Result So far I am able to list all the SKU items that were sold based on the criteria (Period and Entity). Lets assume SKU 12 has two sales $10 and $30 and SKU 23 has three sales $5, $5 and $6 and I need to show the total sales for each of those products. Input Entity: Company XZY Period: November Output SKU Total Sales 12 40.00 23 16.00 -
How to insert product data in all related table in django using serializers
I'm using Django REST framework, I'm stuck in Inserting related product data in multiple table. Please refer the scenario below: In AddProductSerializer, I want to pop again inside variations for loop in else part in nested django serializer so that i can save all the data related to product table. Json Data { "category": 15, "images": [ {"image_url": "https://images/1607679352290_0f32f124a14b3e20db88e50da69ad686.jpg", "main_image": true}, {"image_url": "https://images/1607679352290_0f32f124a14b3e20db88e50da69ad686.jpg", "main_image": false} ], "keywords": "related keywords", "long_description": "<p>l</p>", "mrp_price": "120", "selling_price": "908", "short_description": "<p>k</p>", "sku": "Sam-009", "stock": "7", "title": "Samsung", "have_variations": true, "variant": "Size-Color", "slug": "samsung-phone", "variations": [ { "image_url": "https://images/607679417554_0f32f124a14b3e20db88e50da69ad686.jpg", "mrp_price": 68, "selling_price": 86786, "sku": "iuy", "stock": 68768, "title": "hkj", "color": { "name": "red" }, "size": { "name": 9 } }, { "image_url": "https://images/607679434082_0392bab5c6a3ec64552ea57aa69852a5.jpg", "mrp_price": 67, "selling_price": 6876, "sku": "hkjh", "stock": 868, "title": "yiui", "color": { "name": "blue" }, "size": { "name": 9 } } ] } Serializer.py # List images class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ('image_url', 'main_image',) # List variations class VariationSerializer(serializers.ModelSerializer): class Meta: model = Variation fields = ('title', 'stock', 'mrp_price', 'selling_price',) # List sizes class SizeSerializer(serializers.ModelSerializer): class Meta: model = Size fields = ('name',) # List sizes class ColorSerializer(serializers.ModelSerializer): class Meta: model = Color fields = ('name',) # Add … -
Django group manager getting each member roles
I have installed django_group_manager and I defined some members then allocated some roles from django admin panel. Now I want to print all member roles but can't: >>> from groups_manager.models import Group, GroupType, Member >>> member = Member.objects.get(username='myuser') >>> member <Member: test user> How can I print each member roles? -
Django model, saving objects
I'm developing a small exchange system and I want to give everyone who joins this app a random amount (1-10) of btc. When someone compiles the register form succesfully, recives a random amount of Btc in the wallet. That is my code but doesn't work models.py class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) wallet = models.FloatField() class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(User, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) price = models.FloatField() quantity = models.FloatField() views.py def registerPage(request): bonus = randint(1,10) form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.wallet = bonus form.save() return redirect('login') contex = {'form':form} return render(request, 'app/register.html', contex) forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] I don't know if is't important but I'm working with Mongodb. Thanks -
Django, admin page
I have a problem with achieving this functionality: An administrator must be able to view data for a specific user group in the administration page, how could I do this in my django project? Thank you in advance for your answers -
New client on Django Channels chat reloads data for other user as well
I am trying to implement a chat application using Django Channels via WebSockets. However, every time a client (One user from a private chat refreshes or joins the chat, the data for the other user gets updated again. Below is my connect method for my websockets: def connect(self): self.user = self.scope['user'] self.room_id = self.scope['url_route']['kwargs']['room_id'] user1 = Profile.objects.get(username = self.user.username) if PrivateChat.objects.filter( Q(user1 = user1, guid=self.room_id) | Q(user2=user1, guid=self.room_id) ).exists(): self.room = PrivateChat.objects.filter( Q(user1 = user1, guid=self.room_id) | Q(user2=user1, guid=self.room_id) )[0] self.room_group_name = 'chat_%s' % str(self.room.guid) self.messages_pre_connect_count = self.room.get_messages_count() async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() Now I have a fetch messages method: def fetch_messages(self, data): if data['username'] == self.user.username: room = PrivateChat.objects.get(guid=data['room_id']) messages, has_messages = room.get_messages() self.messages_all_loaded = not has_messages result = [] if len(messages) > 0: for message in messages: json_message = { 'id':message.id, 'author':message.author.username, 'content':message.content, 'timestamp':message.get_time_sent(), 'is_fetching':True, } result.append(json_message) content = { 'command':'messages', 'messages': result } if self.messages_all_loaded and len(messages) > 0: content['first_message_time'] = room.get_first_message_time() self.send_chat_message(content) Which is called via javascript using: chatSocket.onopen = function(e) { fetchMessages(); } function fetchMessages() { chatSocket.send(JSON.stringify({ 'command':'fetch_messages', 'room_id':roomName, 'username': username }) ); } How can I avoid this issue. I currently have one user on Safari and one user on Chrome and when either … -
Django keeps making old db schema
I have deleted one column from my model. Then I deleted database, migration files, venv direcotry, and pycache. But after executing makemigrations the old db schema is generating ( it still contains this column). What is the problem. How django knows about this column. It's no longer present in data model. -
Python Django - Issue w/ View Request
I am building a test application using Django framework written in Python. I am trying to ask a question, have the user answer the question, then get the results of the User's selected answer. I am having an issue with the retrieving what the User has selected. models.py class Question(models.Model): passage = models.ForeignKey(Passage, on_delete=models.CASCADE) questions_text = models.CharField(max_length=400) def __str__(self): return self.questions_text class Choice(models.Model): correct_choices = ( ("Correct", "Correct"), ("Incorrect", "Incorrect"), ) question = models.ForeignKey(Question, on_delete=models.CASCADE) explain = models.ForeignKey(Explanation, on_delete=models.CASCADE, default="") choice_text = models.CharField(max_length=200) correct = models.CharField(max_length=10, choices=correct_choices, default='Incorrect') answer = models.CharField(max_length=500, default='') def __str__(self): return self.choice_text def check_answer(self, choice): return self.choices_set.filter(id=choice.id, is_answer=True).exists() def get_answer(self): return self.choices_set.filter(is_answer=True)''' views.py def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Sorry, Question does not exist") return render(request, 'index/details.html', {'question': question}) def result(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'index/results.html', {'question': question}) def answer(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_answer = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'index/details.html', { 'question': question, 'error_message': "Please make a Valid Selection.", }) else: selected_answer.save() return HttpResponseRedirect(reverse('results', args=(question.id,)))''' results.html <h1>Passage / Equation:</h1> <p>{{ question.passage }}</p> </div> <div class="column" style="background-color:#bbb;"> <h1>Answer for Question: </h1> <h1>{{ question.questions_text }}</h1> <p>Your Choice was: **{{ choice.selected_answer … -
How to know if you are connecting two sockets to same group of channel-layer in django channels
I am actually trying to build a system wherein two entities(being doctor and patient) can share the same data over websockets using django. The way I have setup my channels is sending the auth-token through query_string in the websocket protocol The models are configured in the following fashion the patient model also has an attribute called "grp_id" grp_id = models.UUIDField(default=uuid.uuid4, editable=False) The consumers.py file is • Working for patient make a connection request by sending auth token through query-string which will authenticate the user since the user is patient, the grp_id of the patient is fetched A channel is created using the grp_id value The patient triggers the start_sepsis function which would receive a set of sepsis-attribute, then serialize it and store it it in DB The same serialize data is broadcasted over the channel • Working for doctor authentication like above the doctor fetches patients associated to them using _get_patient_of_doctor helper function doctor will try to connect all the patient's grp_id associated to it Once connected broadcast a message called "doc is connected" class SepsisDynamicConsumer(AsyncJsonWebsocketConsumer): groups = ['test'] @database_sync_to_async def _get_user_group(self, user): return user.user_type @database_sync_to_async def _get_user_grp_id(self, user): #************** THE grp function initiated ************** print("THE USER obj", user)#output below … -
An overview of using Tailwind CSS with Django?
I was looking for some overview information on using Tailwind CSS with Django. I found this excellent thread, and I followed the first answer to install Tailwind ready for use with Django: How to use TailwindCSS with Django? I understand that Tailwind is a CSS framework, that will help you manage your CSS/rendering and related resources. But I am confused as to how Tailwind and Django can fit together. For example: What is the purpose of the PyPi project django-tailwind, and is it necessary? How does Tailwind fit in with Django forms and the render as "p" or render as "table", i.e. is there an alternative way to style Django forms, or will Tailwind work well with these? Any other "overview" information on this topic? -
Django / Ajax : How to filter a form field's queryset asynchronously?
In a given Django form view, I'd like to filter a field's queryset by an option a user has selected while viewing the form. And I'd like that to happen asynchronously. I've read that AJAX might be what I should use, but I know very little of JS, and I can't make much sense of the information I've read. The way I see it, I'd like a user to be able to click on one or more checkboxes that would filter 'loot.item_name' by 'item.in_itemlist' or 'item.item_type' (automatically, using onChange or onUpdate or smth?). Would someone kindly give me some pointers? Cheers, Here are my models: ***models.py*** class Itemlist(models.Model): name = models.CharField([...]) class Item(models.Model): name = models.CharField([...]) item_type = models.CharField([...]) in_itemlist = models.ForeignKey(Itemlist, [...]) class Loot(models.Model): item_name = models.ForeignKey(Item, [...]) quantity = [...] my view, ***views.py*** def create_loot(request): # LootForm is a simple ModelForm, with some crispy layout stuff. form = LootForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() [...] return render(request, 'loot_form.html', context={'form': form} and the template, ***loot_form.html*** {% extends "base_generic.html" %} {% block leftsidebar %} /* for each unique itemlist referenced in the items, */ /* make a checkbox that once clicked, filters 'loot.item_name' by the selected … -
Django views.py : unable to use vriable outside function
I want a new page to open when a django form is filled- by hitting enter/by clicking on the 'Search' input and display results in that page using the data entered in the form. forms.py: class SearchBar(forms.Form): Search = forms.CharField(label='', max_length=100, widget=forms.TextInput) The HTML page with the form looks like: index.html <form class="" action="result" method="post"> {% csrf_token %} {{ form1.as_table }} <input class="Search" type="submit" name="" value="Search"> </form> I want the submission of this form to open a new page: result.html I have set the url of 'result' to the said HTML page: urls.py urlpatterns=[ path('result', views.result, name='result'), ] I have extracted the data entered in the from by form1.cleaned_data['Search']. form_input=form1.cleaned_data['Search'] However, once the result page is opened, it shows that the data (form_input) is not defined. The following error is shown: name 'form_input' is not defined I am unable to use this data (form_input) in any other function of the views.py file. views.py def index(request): form1 = forms.SearchBar() if request.method == "POST": form1 = forms.SearchBar(request.POST) if form1.is_valid(): global form_input form_input= (form1.cleaned_data['Search']) def result(request): print(form_input) I don't understand why this is happening. I have even declared the variable form_input as a global variable. -
Local variable x referenced before assignment - Django
I must get data value from POST request and write it to Word document. But I'm getting error. How can I fix the problem ? def military_document(request): if request.method == 'POST': form = CreateMilitaryDocumentForm(request.POST, request.FILES, use_required_attribute=False) if form.is_valid(): group_degree = request.POST.get('group_degree') print(group_degree) form.save() messages.success(request, 'Added successfully !') return HttpResponseRedirect('military_document') else: form = CreateMilitaryDocumentForm(use_required_attribute=False) doc = DocxTemplate("../document.docx") context = { 'form': form, 'group_degree': group_degree, } doc.render(context) doc.save("generated_doc.docx") return render(request, 'military_document.html', context) -
error when trying to authenticate on react using django rest as backend
pages/Login.js Error const mapStateToProps = (state) => ({ isAuthenticated: state.auth.isAuthenticated, # Error on this line }); TypeError: "Cannot read property 'isAuthenticated' of undefined" first time creating full stack app using django rest + react. everything works on the backend, but on the front when i go to http://localhost:3000/login and try to login i get an error, i tried everything but i cant figure this out. i've added the authentication related files, if anyone identify a problem please let me know. thanks :) action/auth.js import { setAlertMsgAndType } from './alert'; import { LOGIN_SUCCESS, LOGIN_FAIL, } from './types'; export const login = (email, password) => async (dispatch) => { const config = { headers: { 'Content-Type': 'application/json', }, }; const body = JSON.stringify({ email, password }); try { const res = await axios.post( 'http://localhost:8000/api/token/', body, config ); dispatch({ type: LOGIN_SUCCESS, payload: res.data, }); dispatch(setAlertMsgAndType('Authenticated successfully', 'success')); } catch (err) { dispatch({ type: LOGIN_FAIL, }); dispatch(setAlertMsgAndType('Error Authenticating', 'error')); } }; reducers/auth.js import { SIGNUP_SUCCESS, SIGNUP_FAIL, LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT, } from '../actions/types'; const initialState = { token: localStorage.getItem('token'), isAuthenticated: null, loading: false, }; export default function authReducer(state = initialState, action) { const { type, payload } = action; switch (type) { case LOGIN_SUCCESS: localStorage.setItem('token', … -
Creating multiple charts based on dictionary length
I am building a dashboard website for some water quality sensors I have that send the information as an API in JSON format. The plan is to create real-time charts using that data using chart.js and django. Right now I am turning the JSON file to dictionaries like so: JSON file: { "11:00:00 AM": { "Temperatura": 30, "pH": 7.1, "Conductividad": 759, "Cloro Residual": 1.1, "Turbidez": 0, "Color": "<5", "pH de la Det de color": 7.12, "Solidos totales": 512, "S�lidos disueltos": 494, "S�lidos suspendidos totales": 0, "Dureza total como CaCO3": 227.24, "Alcalinidad como CaCO3": 227.7, "Cloruros": 64.02, "Fluoruros": 0.91, "Nitrogeno Amoniacal": 0, "Nitrogeno de nitritos": 0, "Nitrogeno de nitratos": 4.47, "Sulfatos": 37.27, "Sustancias activas al azul de metileno": 0, "Fenoles": 0, "Coliformes totales": 0, "Aluminio": 0, "Arsenico": 0.015, "Bario": 0.1784, "Calcio": 79.7, "Cadmio": 0, "Cromo": 0.0085, "Cobre": 0, "Fierro": 0.0327, "Potasio": 12.18, "Magnesio": 13.37, "Manganeso": 0, "Sodio": 55.75, "Plomo": 0, "Zinc": 0, "Mercurio": 0 }, I am then turning them to dictionaries with all of the values like so: ['11:00:00 AM', '11:10:05 AM', '11:20:10 AM', '11:30:14 AM', '11:40:19 AM', '11:50:24 AM', '12:00:29 PM', '12:10:34 PM', '12:20:38 PM', '12:30:43 PM', '12:40:48 PM', '12:50:53 PM', '01:00:58 PM', '01:11:03 PM', '01:21:07 PM', '01:31:07 PM'] … -
Django Combined registration form
I want to put the registration and login form on the same page. Before that I had it in 2 functions def loginPage() and def registerPage(). Now I combined them together in to one def loginPage() and there is error and I dont know what is the problem here. Please help <div class="container" id="container"> <div class="form-container sign-up-container"> <form method="POST" action="#"> {% csrf_token %} <h1>Create Account</h1> <!-- <div class="social-container"> <a href="#" class="social"><i class="fab fa-facebook-f"></i></a> <a href="#" class="social"><i class="fab fa-google-plus-g"></i></a> <a href="#" class="social"><i class="fab fa-linkedin-in"></i></a> </div>--> <span>or use your email for registration</span> {{form.username}} {{form.email}} {{form.password1}} {{form.password2}} <input class="btn login_btn" type="submit" value="Register Account"> <button type='submit' name='submit' value='sign_up'></button> </form> </div> {{form.errors}} <div class="form-container sign-in-container"> <form method="POST" action="#"> {% csrf_token %} <h1>Sign in</h1> <div class="social-container"> <a href="#" class="social"><i class="fab fa-facebook-f"></i></a> <a href="#" class="social"><i class="fab fa-google-plus-g"></i></a> <a href="#" class="social"><i class="fab fa-linkedin-in"></i></a> </div> <span>or use your account</span> <input type="text" name="username" placeholder="Email" /> <input type="password" name="password" placeholder="Password" /> <a href="#">Forgot your password?</a> <input class="btn login_btn" type="submit" value="Login"> <button type='submit' name='submit' value='sign_in'></button> </form> </div> {% for message in messages %} <p id="messages">{{message}}</p> {% endfor %} <div class="overlay-container"> <div class="overlay"> <div class="overlay-panel overlay-left"> <h1>Welcome Back!</h1> <p>To keep connected with us please login with your personal info</p> <button class="ghost" id="signIn">Sign In</button> … -
default data type of primary keys in models (django), The current path, url '/app' didn't match any of these
As far as I know, the default data type of id is integer for models in Django. For example, if I have such a model inside my models.py file, Django sets a id(primary key) for every instance of it and Django increments it automatically like 1,2,3 etc. : class AuctionListing(models.Model): name = models.CharField(max_length=200) url = models.URLField() def __str__(self): return f"{self.name}" Since it sets id(primary key) automatically as a data type of integer, I can create such a url in the url.py file : path("<int:listing_id>", views.listing, name="listing") And my views.py file: def index(request): return render(request, "auctions/index.html", {"auctionList":AuctionListing.objects.all()} ) also, index.html file : {% for listing in auctionList %} <a href="url 'listing' listing.id"><img src = "{{listing.url}}" alt = "{{listing.name}}"></a> {% endfor %} The issue with this, when it passes listing.id to the path("int:listing_id", views.listing, name = "listing"), it doesn't pass id as integer but as str. That's why, path doesn't accept it since it is int:listing_id and when I go to the page, it gives me this error : " The current path, url 'listing' listing.id, didn't match any of these". When I change int:listing_id to str:listing_id it works. I wonder if the default data type of id is a string data … -
How to filter by dropdown and search in Django, JQuery and Ajax?
I have a Postgresql database containing 5 columns. id region_name subregion_code zone_code building_code #Database Details Total row = 300k Distinct region name total = 221 Each region have 1+ subregion code (code value start from 1, 2, 3, ..) Each subregion have 1+ zone code (code value start from 1, 2, 3, ..) Each zone code have 200+ building code (code value start from 1, 2, 3, ..) All are inter-related. #What I want?? I have a search page where user can search thier buidling details using building_code. First select region_name (choose from dropdown distinct list) Then, select subregion_code of this selected region_name (choose from dropdown distinct list) Then, select zone_code of this selected subregion_code Finally, type building_code and search building details of this selected zone_code #Django Model Class RBC(models.Model): id = models.AutoField(primary_key=True) region_name = models.CharField(max_length=255) subregion_code = models.IntegerField() zone_code = models.IntegerField() building_code = models.IntegerField() def __str__(self): return self.region_name How can I do it? Thanks! -
Django Tutorial: Reverse for 'results' with arguments '(1,)' not found error
I'm currently following the Django tutorial and got stuck at module 4 since I keep getting the following error message: NoReverseMatch at /polls/1/vote/ Reverse for 'results' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/int:question_id>/results/$'] Below my codes so far: views.py: from django.shortcuts import get_object_or_404, render from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.urls import reverse from .models import Choice, Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question' : question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) urls.py: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] reults.html: <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> … -
Django lt+gt condition Vs. not equal condition
I have the following model class P(models.Model): name = models.CharField(max_length=30, blank=False) class pr(models.Model): p = models.ForeignKey(P, on_delete=models.CASCADE, related_name='cs') r = models.CharField(max_length=1) c = models.ForeignKey(P, on_delete=models.CASCADE, related_name='ps') rc = models.PositiveSmallIntegerField() class Meta: unique_together = (('p', 'c'),) and the data "id","name" 69,"Hunter" 104,"Savannah" 198,"Adrian" 205,"Andrew" 213,"Matthew" 214,"Aiden" 218,"Madison" 219,"Harper" --- "id","r","rc","c_id","p_id" 7556,"F",1,219,213 7557,"M",1,219,218 7559,"H",3,218,213 7572,"F",1,214,213 7573,"M",1,214,218 7604,"F",1,198,213 7605,"M",1,198,218 7788,"H",3,104,205 7789,"F",1,104,213 7790,"M",1,104,218 7866,"M",1,69,104 7867,"F",1,69,205 the following two queries should produce similar results A = P.objects.filter(Q(Q(ps__rc__lt = 3) | Q(ps__rc__gt = 3)), ps__p__cs__c = 198).exclude(pk = 198).annotate(bt=Count('ps__rc', filter=Q(ps__rc = 1, ps__p__cs__rc = 1))) B = P.objects.filter(~Q(ps__rc = 3), ps__p__cs__c = 198).exclude(pk = 198).annotate(bt=Count('ps__rc', filter=Q(ps__rc = 1, ps__p__cs__rc = 1))) strangely; query A produce the expected results but B is missing model instance 104! After further troubleshooting I found that query B generates the following SQL: SELECT "eftapp_p"."id", "eftapp_p"."name", COUNT("eftapp_pr"."rc") FILTER (WHERE (T4."rc" = 1 AND "eftapp_pr"."rc" = 1)) AS "bt" FROM "eftapp_p" LEFT OUTER JOIN "eftapp_pr" ON ("eftapp_p"."id" = "eftapp_pr"."c_id") LEFT OUTER JOIN "eftapp_p" T3 ON ("eftapp_pr"."p_id" = T3."id") LEFT OUTER JOIN "eftapp_pr" T4 ON (T3."id" = T4."p_id") WHERE (NOT ("eftapp_p"."id" IN (SELECT U1."c_id" FROM "eftapp_pr" U1 WHERE U1."rc" = 3)) AND T4."c_id" = 198 AND NOT ("eftapp_p"."id" = 198)) GROUP BY "eftapp_p"."id" Is … -
Standard way to implement data input table's frontend for Django
I need to build a website with the following types of data input table. I want to use html, css, js and bootstrap for the frontend and Django for the backend and SQLite also as Django's default database system. Now I am confused about what is the standard way to implement this type of input table's frontend. I can generally implement a table and inside the cell(means inside <td> tag) I can put another <input> tag to take input data and send it in the database from the user). Or I can use an editable table (Actually I do not know if it is possible to use this type of editable table to send data in the database or not). Here I need an add row button and delete row icon also like the picture to add/remove the input row if needed, and I don't know how to implement it also thus it will easily reachable from the backend. So please suggest to me what is the best way and how I should implement this frontend thus I won't be trouble to implement this website's backend also. -
How to upload pdf file in django model and handle as json object?
Field:cv_file Explanation:A json object with only Unique UUID field. Upon POST, server will respond with a FILE ID TOKEN in response's cv_file json object. Restriction to handle:JSON Object, REQUIRED Field:cv_file.tsync_id Explanation:UUID type unique string ID for cv_file entity - Needs to be internally generated from API Client side Restriction to handle:Plain Text, max length = 55, REQUIRED -
django: loop through images to show one per page
i want to make the images appear one per page as in "template/1" shows image 1 and so on. i got pagination from bootstrap but i couldn't figure out how to link the images in my template. i already have static set up and most of my website ready but i don't have any relevant code to show except this list i tried. def imageview(request): context_dict = {} files = os.listdir(os.path.join(os.path.join(BASE_DIR, 'static'), "app_name/images/")) context_dict['files'] = files return render(request, 'images.html', context=context_dict) -
django long-running process
My Django app has a function that enables end-user to retrieve data from a third-party server and store the data on S3 bucket. This function can be running for a long time of 1-2 hours depending on the requested data. Apart from setting the timeout for my Gunicorn to a very large number, maybe 99999 seconds, is there another alternative? The app is on AWS micro instance, if this is relevant.