Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Couldn't Make Django Talk with Postgres in k8s
I have a deployment of simple django app in minikube. It has two containers one for django app and one for postgres db. It is working with docker-compose, but couldn't make it work in minikube k8s cluster. When I opened a terminal to the container and ping the service it wasn't succesful. I didn't find what causes this communication error. DATABASES part in settings.py in django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Deployment file: apiVersion: apps/v1 kind: Deployment metadata: name: notejam-deployment labels: app: notejam-app spec: selector: matchLabels: app: notejam-app template: metadata: labels: app: notejam-app spec: volumes: - name: postgres-pvc persistentVolumeClaim: claimName: postgres-pvc containers: - name: notejam image: notejam_k8s imagePullPolicy: Never resources: limits: memory: "128Mi" cpu: "500m" ports: - containerPort: 8000 - name: postgres-db image: postgres imagePullPolicy: Never ports: - containerPort: 5432 resources: limits: memory: "128Mi" cpu: "500m" env: - name: POSTGRES_USERNAME valueFrom: configMapKeyRef: name: postgres-configmap key: postgres-username - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgres-secret key: postgres-password - name: POSTGRES_DB valueFrom: configMapKeyRef: name: postgres-configmap key: postgres-db volumeMounts: - mountPath: /notejam-db name: postgres-pvc --- apiVersion: v1 kind: Service metadata: name: db spec: selector: app: notejam-app ports: - port: … -
¿Is it good practice to add migrations files to the repository?
I am using Django Framework to create my applications and I am uploading them to GitHub. I have like a "history" of migrations files and they are all there, Is it good practice to upload all migrations files to GitHub or do they need to be deleted? Thank you! -
I have two for loops in Jinja. (Django Project) I want to save the forloop.counter for the first loop to a variable and use in the secodn loop
I can't get the correct loop counter variable to save - I want a similar functionality to the enumerate in python, or just a way to store my variables for the next for loop. {% for boards, value_dict in my_dict.items %} **{{ forloop.counter }}** <---- gets the correct loop index I need {% for mode, platform_dict in value_dict.items %} // I have no way of saving the above value, if I call forloop.counter in this line it gets the counter for the wrong forloop **// I need to use the index above in this line.** {% for mode, platform_dict in value_dict.items %} **// I also need the same variable here** {% endfor %} {% endfor %} {% endfor %} What I tried using : {% with counter=forloop.counter %} (in first loop set this) {% with forloop.counter as counter %} {set counter = {{forloopcounter}} (in first loop set this) Using loop.index Using forloop.parent.count This seems to be a very simple thing I want to do yet I can seem to find the right syntax to do it. Also using the -
Create Django Serializer with default fields in Meta and query params
I'm trying to write a Serializer that would take dynamic fields and add them to the restricted number of fields specified in Meta, but it seems that there's no method to "add back" a field to the serializer once it's been created. Dynamic Fields per Django documentation class DynamicFieldsModelSerializer(ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) class BldgLocationAndFilters(DynamicFieldsModelSerializer): latitude = fields.FloatField(source='lat_016_decimal') longitude = fields.FloatField(source='long_017_decimal') class Meta: model = Bldg fields = ('latitude', 'longitude') I'd like to do something that would modify the DynamicFieldsModelSerializer such that fields can be appended to the set that has already been filtered down, but it looks like the Meta fields override everything such that nothing can be added back (fields can only be removed Pseudocode of desired behavior: class DynamicFieldsUnionModelSerializer(ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument … -
Django request.method in class View
I have a simple question as in title, how to use request.method inside class view. I have form there and I would like to play with her. class ShopDetailView(DetailView): model = Item template_name = 'shop/detail.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CommentCreationForm() context['comments'] = Comments.objects.all() context['profile'] = Profile.objects.all() return context if request.method == 'POST' -
show informations from a table, django
(Sorry for asking but I'm a beginner on django) I'm looking for to show informations from my database 'profile' but I don't find how to make that... There is two functionality to show on my 'infos.html' : the one part is for user's informations like the mail and birthday, the second part is for the favourite items who have been add by the user. #views.py -- post from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.db import models from .models import Post from django.utils import timezone from django.contrib import messages from django.contrib.auth import logout from django.urls import reverse, reverse_lazy from .forms import PostForm from django.contrib.auth.decorators import login_required import datetime def index(request): posts = Post.objects.order_by('-id') posts_number = posts.count() context = { 'posts' : posts, 'posts_number': posts_number, } return render(request, 'blog/pages/index.html', context) def details(request, pk): post = Post.objects.get(pk=pk) context = { 'post': post, } return render(request, 'blog/pages/details.html', context) @login_required def new_post(request): if request.method == 'POST': form =PostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.author= request.user form.save() return redirect('new_post') else: form = PostForm() context ={ 'form' : form, } return render(request, 'blog/pages/new_post.html', context) @login_required def update_post(request,pk): post = Post.objects.get(pk=pk) if post.author == request.user : if request.method == 'POST': … -
How do i run some python code in the background
So I'm making a website using Django, and there is some code that I have set up to run every hour, however when I call this as a function in views.py it doesn't load the web page until the function has finished which isn't ideal for my website, I want it to be a background process which occurs outside my views file. -
How to change a value of HttpRequest.body in django?
I am getting a HttpRequest object in my view function. I want to change a particular key-value of that request. Currently I am doing this - def myview(request): request._body['key1'] = 'value1' # where 'key1' already exists in request body ... But this is giving an error: TypeError: 'bytes' object does not support item assignment -
What python http server to use?
I'm looking to build a python script that will listen to requests on mysite.com/@username then will get the username and internally fetch this user's pictures from instagram, then do some processing on the images, save them locally so they don't have to be fetched again and return the urls of these new processed images. I have a basic idea of how to do it but I'm not sure if I should use something like Django, Flask or just simply http-server. This is something only I'll use so that's why I wonder if I might be overthinking it. -
Go to next page when True
JavaScript was created as follows: If the diction value is true, I want to go to another page, and if it is false, I want to let you go to Home. What should I do? async function predict() { // predict can take in an image, video or canvas html element var image = document.getElementById("face-image") const prediction = await model.predict(image, false); prediction.sort((a,b) => parseFloat(b.probability) - parseFloat(a.probability)); switch (prediction[0].className){ case "True": resultMessege = "성공" break; case "False": resultMessege = "실패." break; default: resultMessege = "알 수 없는 오류가 발생하였습니다. 다시 시도해보시길 바랍니다." } $('.result-message').html(resultMessege); -
How to add links to other apps working with markdown?
I have a project with 2 apps: main and articles. main contains some products (the Product model) and it's linked to project's main url (i.e. 'main.urls') so if you type example.com/products/best-product you'll go (via slug) to this product view. No need to add .../main/... articles app is like blog app that under example.com/articles/art-1 you'll see obviously some Article object. It is rendered with markdown by markdown() function defined in markdown_extras.py Now, what I want to do is inside any Article have links to any Product objects. It's trivial without markdown: {% url 'main:product' prod_obj.slug %} but how to do this with markdown? Ideally the syntax (considering different target models) would be: I recommend [this product](main:product best-product) for you. I tried with basic syntax but any link leads to example.com/articles/art-1/name So containing: app name, target model, slug/id. I've found some solutions but mostly for external links or internal (this page, not this django project). -
Getting Count Result With Multiple Conditions
I have models named Class, StudentList, Child, TakingQuiz and TakingQuizAnswer. Students can take exams. In this case, when they start the exam, data is added to the 'TakingQuiz' table. With each new answer, the answers are also recorded in the TakingQuizAnswer table. The result I want to reach -> The question with the most mistakes in the exams solved by the students in a class. I tried to use Count for this. I'm filtering answer_is_correct to False but that is insufficient. I also need to filter this data for the question column. So I need to get rows where both question and answer_is_correct = False columns are the same and return the first few most repetitive data as results. I always get a general result in my experiments. I can't include rows where the question column is the same. How can I access the questions with the most mistakes in exams solved by students studying in a class? Serializer class ClassSerializerReport(ModelSerializer): instructor = InstructorSerializerReport(source="instructor.user") students = StudenListSerializerReport(many=True, source="student_list_class") max_incorrect_question = serializers.SerializerMethodField() class Meta: model = Class exclude = [ "created_at", "updated_at", "school", ] def get_max_incorrect_question(self, obj): data = Class.objects.filter(id = obj.id).values('student_list_class__child__child_taking_quiz__taking_quizes').annotate(res = Count('student_list_class__child__child_taking_quiz__taking_quizes__question', filter = Q(student_list_class__child__child_taking_quiz__taking_quizes__answer_is_correct = False))) print(data) return … -
How to show a loader when one of the paypal payment options gets clicked
I've been working on a Django project, and I added paypal to my site. I know basic python and javascript, but i'm still new to them. After payment by paypal it takes some time to do some code internally, so I want to show a loader when user clicked one of the paypal payment options. I have no idea to do this. Thank you in advance. -
How to display django array data
I am using Django postgresql. I have insert some data into models array field. My models are like class PurchaseInvoice(models.Model): invoice = models.CharField(max_length=20) date = models.DateField(default=date.today) product_name = ArrayField(models.CharField(max_length=500)) price = ArrayField(models.CharField(max_length=300)) quantity = ArrayField(models.CharField(max_length=200)) amount = ArrayField(models.CharField(max_length=300)) I have insert data successfully but when I try to query my data I got like ["['LNB Inverto', 'Dish']"]. I want to view my data on html table. My views.py are following def purchaseDetails(request,pk): invo_data = PurchaseInvoice.objects.filter(invoice=pk) return render(request,'purchase/invoice_details.html',{'invoice':invo_data}) and my html tables like {% for data in invoice %} <tr> <td >{{data.product_name}}</td> <td >{{data.price}}</td> <td >{{data.quantity}}</td></tr> {% endfor %} -
Security concerns for posting live site code on GitHub public repo
First, I am trying to get my first software engineering job and have limited "completed" projects including my resume site (built in Django). I currently self host on my a dokku home server and I want to put the code for the few sites I do have live to GitHub for sharing with potential employers. I've mostly kept my sites in private repos but with now wanting to make them public, I'm having security concerns. A few security precautions I have taken already: Change my admin login route (if posting code that route is made public) Removed all domain specific items (With resume site, that will be public) All keys for apis are in ENV files that are not shared Things I'm considering doing: At minimum migrating my sites to public hosting because I don't think I monitor my security well enough. Have 2 different repos for each site, private and public. I'd hate to do it, because of complicating things in my already complicated career change, but I could see the benefits. What are some security concerns I didn't think of or how do people keep public repos for live sites? -
OperationalError - no such table - Django Dynamic URL
I have a list like this (as return, this list returns directly.); list1 = [ {'ID': 0, 'IP': '192.168.1.1', 'Hostname': 'Hostname1', 'Ports': '23,53,80,139,443,445'}, {'ID': 1, 'IP': '192.168.1.1', 'Hostname': 'Hostname2', 'Ports': '23'}, {'ID': 2, 'IP': '192.168.1.1', 'Hostname': 'Hostname3', 'Ports': '5555,8009'}, {'ID': 3, 'IP': '192.168.1.1', 'Hostname': 'Hostname4', 'Ports': '135,139,443'} ] And I have a table like below. <tr> <th scope="col">#</th> <th scope="col">IP</th> <th scope="col">Hostname</th> <th scope="col">Ports</th> </tr> {% for i in searchin %} <tr> <td>{{i.ID}}</td> <td scope="row">{{i.IP}}</td> <td scope="row">{{i.Hostname}}</td> <td><a href = "/ports/{{i.ID}}" class="btn btn-danger">Ports</a></td> </tr> {% endfor %} In each row, when the 'Ports' link is clicked ../ports/{{i.ID}} and I want it to go and bring the ports according to the in the first list. For example; ports/0 >>output in html>> '23,53,80,139,443,445' ports/1 >>output in html>> '23' In django, I could not set this algorithm in model and views files or forms. Thanks. -
FactoryBoy is accessing normal DB instead of TEST DB
I'm trying to create some objects in setUp method of Django test case. I use FactoryBoy that helps me with creating the objects. But it seems that FactoryBoy can't find any objects in the database. class ProductFactory(DjangoModelFactory): ... market_category = factory.fuzzy.FuzzyChoice(list(MarketplaceCategory.objects.all())) class Meta: model = Product class MyTestCase(TestCase): def setUp(self) -> None: ... self.marketplace_category = MarketplaceCategoryFactory.create() print(MarketplaceCategory.objects.first().pk) # prints 1 self.product = ProductFactory(created_by=self.user) As you can see, ProductFactory tries to populate Product.market_category by random MarketCategory object. The problem is that it seems like it does not exist even when I've created it before and made sure it is in the db (it has pk). EDIT: It chose a MarketCategory object with pk=25 but there is only one such objects in the test db with pk=1. I think it accesses Django development DB instead of testing one. The error: psycopg2.errors.ForeignKeyViolation: insert or update on table "products_product" violates foreign key constraint "products_product_market_category_id_2d634517_fk" DETAIL: Key (market_category_id)=(25) is not present in table "marketplaces_marketplacecategory". Do you have any idea why it behaves this way? It looks like the Factory is accessing the real DB instead of testdb for some reason. -
Django, user can update email and username but not Image
As in title I have a problem with updating form because everything works as I want but not an image updating feature.It sends success message but it does not change the image for the profile. views.py def profileView(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user,) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Your account has been updated!') return redirect('profile-page') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form} return render(request, 'shop/profile.html', context) HTML: <div> {{ user.username }} <img src="{{ user.profile.user_image.url }}"> <a href="{% url 'delete-page' pk=user.id %}">Delete</a> <form method="POST"> {% csrf_token %} {{ p_form.as_p}} {{ u_form.username }} {{ u_form.email }} <button type="submit">Update</button> </form> </div> signals.py @receiver(post_save, sender=User) def profile_creation(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() {{ u_form.email }} <button type="submit">Update</button> </form> </div> -
In local machine, django project run on which server?
i have only query to in which server python run and django run please help , on which server Django run locally? gunicorn and uwsgi is same? -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8c in position 119485: invalid start byte (while migrating sqlite3 to postgreSQL - djangocms)
I have been trying to migrate the database of my djangocms project from the default sqlite3 to postgreSQL. But at the end of the process I got this error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8c in position 119485: invalid start byte. I am not sure how to handle this issue as I have no experience in databases and most posts about this type of issues on the internet are not database-related from what I have seen. What I did to reach this point: I have created a local djangocms website with sqlite. To make the database migration, I have followed the procedure described here: I dumped the database into a db.json file then created the new postgres database on pgAdmin. I modified the field DATABASES in my django settings.py, installed psycopg2 and ran python manage.py makemigrations and python manage.py migrate and then (in the Python shell) I ran: from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() before python manage.py loaddata db.json. I also had to re-create a superuser which helped me to log into djangocms admin. But as expected my website was absent (and even the layout of djangocms was wrong). Any help would be much appreciated! Many thanks. Here are the … -
how do i display another website data in django template
**urls.py** urlpatterns = [ path('',views.index,name='index'), ] **views.py** def index(request): return render(request,"index.html") template.html my template has 1)input box 2)search button 3)bootstrap card when i enter any url and hit search button, the website data should appear in the card <input type="text" value=""> <button type="button">Search</button> <div class="row"> <div class="col-sm-6"> <div class="card"> <div class="card-body"> <h5 class="card-title">Search results will appear here</h5> </div> </div> </div> </div> -
Django - Custom Join's F('') includes single quotes in column reference, causing Postgres to think it's string and not a column reference
I've created a custom join that allows a queryset to join onto a custom Postgres function. The parameters for this function require an outer ref to the overall query to be passed as part of the parameter list. When Django does this for an F(''), it includes single quotes around the double quotes such that postgres believe's the parameter is a string, not a reference to the outer alias. Custom Join: def join_to_function(table, function_model, table_field, function_field, queryset, alias, table_function_params): foreign_object = ForeignObject(to=function_model, on_delete=DO_NOTHING, from_fields=[None], to_fields=[None], rel=None) foreign_object.opts = Options(table._meta) foreign_object.opts.model = table foreign_object.get_joining_columns = lambda: ((table_field, function_field),) # table._meta.db_table is passed twice, once as the base table name, and once as the parent alias join = TableToFunctionJoin( table._meta.db_table, table._meta.db_table, alias, "LEFT JOIN", foreign_object, True, table_function_params=table_function_params, queryset=queryset) queryset.query.join(join) # hook for set alias join.table_alias = alias queryset.query.external_aliases[alias] = alias return queryset class TableToFunctionJoin(Join): def __init__(self, table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation=None, table_function_params=None, queryset=None): super().__init__(table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation) self.table_function_params = table_function_params self.queryset = queryset def as_sql(self, compiler, connection): # Sets up the on clause '{join_info} on lhs = rhs' # lhs / rhs come from a tuple of joinable columns for (lhs_col, rhs_col) in self.join_cols: on_clause_sql = '{}.{} … -
How to filter distinct objects in a many-to-many relationship in Django?
I have a page where I show all workout plans from each user. But I want to show only one entry per user, so then I can click and get all workouts plans of that user. So, instead of showing: User 1 - Day 1 USer 1 - Day 2 User 2 - Day 1 USer 2 - Day 2 I want to show: User 1 User 2 I was using the following view: planos = Workout.objects.all() But this would show everything, so I tried: plan = Workout.objects.values('member').distinct() But this returns {'member': 1} and {'member': 2}. How can I access the name of the user? class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) socio = models.CharField(max_length=6) address = models.CharField(max_length=200) city = models.CharField(max_length=200) class Exercise(models.Model): exercise = models.CharField(max_length=166) series = models.CharField(max_length=2) reps = models.CharField(max_length=2) maquina = models.ForeignKey(Maquina) class Workout(models.Model): member = models.ForeignKey(Membro) day = models.CharField(max_length=1) exercises = models.ManyToManyField(Exercise) -
Python Social Auth with Instagram Basic Display API
I'm developing an app that lets users see their own social media data. I'm using python-social-auth with Django and it works great with twitter and facebook. However, I'm having some trouble getting it working with instagram. The 'authorize with Instagram link' takes the user to the following URL: https://www.instagram.com/oauth/authorize?client_id=******&redirect_uri=https://example.com:8000/social-auth/complete/instagram/?redirect_state=******&state=******&response_type=code&scope=user_profile+user_media The user clicks 'allow', at which point python-social-auth produces the following URL and raises an exception: https://example.com:8000/social-auth/complete/instagram/?code=******#_ social_core.exceptions.AuthCanceled: Authentication process canceled I found the reponse object and call response.text to get this output: {"error_type": "OAuthException", "code": 400, "error_message": "Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request"}' I've checked the redirect uri is the same in the Instagram basic display settings. https://example.com:8000/social-auth/complete/instagram/ Any suggestions very welcome! Thanks Lloyd -
x and y must have same first dimension, but have shapes (3000,) and (1,)
I have the code to plot functions with django and when entering a function by keyboard I get the error mentioned above. How the code should work is that when a user enters a mathematical function by keyboard it graphs it for me. Function import numpy as np import matplotlib.pyplot as plt, mpld3 def Graficador(request): x = symbols('x') t = np.arange(-10.0, 20.0, 0.010) s = (request.POST['funcion']) s = parse_expr(s) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='tiempo (s)', ylabel='voltaje (mV)') ax.grid() g = mpld3.fig_to_html(fig) fig.savefig("test.png") context = {'g': g} return render(request, 'Graficar.html', context) The error appears when I wrap it in the plot, i.e. in the line "ax.plot(t,s)" the x and y error appears. HTML <div class="news_posts"> <center> <form class="form" action="/GraficarSolucion/" method="POST"> {% csrf_token %} <div class="camposLogin"> <input type="text" placeholder= "Ingrese una función" id="id_username" class="form-control" name="funcion" required> </div> <input class="btn" type="submit" value="Calcular"> </form> {% autoescape off %} <div>{{ g }}</div> {% endautoescape %} </center> </div> </div> URLS path('graficas/', views.vistaGraficador, name='graficas'), path('GraficarSolucion/',views.Graficador, name='GraficarSolucion'),