Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I connect a python application to my Django PostgreSQL database to write data
I have seen many quite similar questions here but nothing quite like it. I would like to write a python(kivy) app with the functionality to add data to the postgreSQL database of my heroku-deployed Django web app. How would I go about approaching this? -
TEARING MY HAIR OUT trying to move databases from SQLite to Postgres
Not sure how/why, but I started out using SQLite in production; now I need to move to Postgres pronto. So I do this: python3 manage.py dumpdata --indent 4 --natural-primary --natural-foreign -e contenttypes -e auth.Permission -e sessions > dumpdata.json No problem so far. Changed my setting.py to point to new postgres db, then run: python3 manage.py migrate --run-syncdb Still no problem. Problem comes here, when I run this command: python3 manage.py loaddata dumpdata.json I get this nasty error: django.core.serializers.base.DeserializationError: Problem installing fixture 'dumpdata.json' Googled this error on Stack Overflow. Seems like it happens when the file isn't valid JSON. I run head -1000 dumpdata.json and tail -1000 dumpdata.json and everything looks good. No trailing commas, no weird strings, nothing. What gives!? -
Which data binding supported by Django? one way, two way or three way binding?
Which data binding supported by Django ? I am planning to develop a web application with django. So in term of developing UI with django which data binding django supports : one way, two way or three way binding ? -
How can i add something to the database with a submit button in Django?
I'm making a grocery list web app in django and i have a page with your groceries list and i have a page with all the products you can add to your list. every product has a button "add to list". The intention is that when you click on that button that that product automatically becomes added to the groceries list. Does someone know how to do that? thank you in advance. The Groceries List page The all products page models.py from django.db import models # Create your models here. class Brand(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class AllProducts(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class ShoppingList(models.Model): product = models.ForeignKey(AllProducts, null=True, on_delete= models.SET_NULL, blank=True) brand = models.ForeignKey(Brand, null=True, on_delete= models.SET_NULL, blank=True) quantity = models.CharField(max_length=200, null=True, blank=True) info = models.TextField(max_length=500, null=True, blank=True) def __str__(self): return self.product The class brand is a class with all the brands of the products. The class All_Products is a class with all the products that you can add to your groceries list. And the class ShoppingList is a class with all the products in the groceries list. Views.py def home(request): products = ShoppingList.objects.all() context = { 'products':products, } return render(request, 'groceries_list/home.html', … -
How to query the following use case in Django?
I have made a game similar to the drinking game piccolo where you have a list of challenges. Each challenges has variables that need to be filled in (e.g: Player X gives four sips to Player Y). Besides that, a challenge consists of rounds, with each round having an index and a description (e.g Round 0: X and Y drink 4 sips. Round 1: X and Y drink 5 sips now), with X and Y being the same names in both rounds. First we made a small console app that had the challenges hardcoded in them. The list of challenges would look like this: challenge_list = [ Challenge(["p(0)", "rand_phone_number()"],[[0, "{d[0]} moet een nummer bellen. Het volgende scherm bepaalt welk nummer"], [1, "Het nummer is {d[1]}"]]), Challenge(["p(0)", "rand(2,5)", "rand_char('a','z')", "rand(2,5)"], [[0, "{d[0]} noemt {d[1]} dieren die beginnen met de letter {d[2]} of drinkt {d[3]} slokken"]]), Challenge([], [[0, "Alle drankjes schuiven een plek naar links"]]), After requests from other friends we decided that it would be educational to migrate the project to Django, since we did not have much experience in web development and we want to learn something new. We came up with the following model to replicate the hardcoded challenges … -
Django save_model doesn't get called
I want to override the save_model(...) method of the django admin. For this I created following class and method in the admin.py file: class ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): print('IN ADMIN') super().save_model(request, obj, form, change) Now I know this doesn't do anything different but I just wanted to test if this method gets called and it doesn't (print since I got no debugger). According to the official documentation this is the accurate method. Does anybody know what I did wrong? -
how to send emails to all users?
How can I send email to all users whenever I want? I have built a blog app and I want to send some emails about news and updates to all the users and I have no idea how to do it. please help me with the code. I'm using the built in django user model for auth. thanks for the responses -
How to use self page database update in Django?
I have a question on my homepage that the user should answer through radio buttons. The user should press the submit button to send the answer, so basically it is a SELF PAGE submission. The user should not go to another page after submitting the answer but should remain on the same home page. Though I looked up some earlier questions, the code did not work out. I have created the TEMPLATE DIRECTORY under the root folder and under this directory, there is a 'pages' folder that has the index.html (homepage) inside which I am invoking the form The form code in the index.html page. <form action = "?" method = "POST"> I want to know what function should I write in the views. Since the form action does not call a named view I am not able to figure out how I should define the view that updates the data. def WHAT NAME SHOULD I GIVE HERE(request): .....other code Thanks -
django Download Link(filefield)
i am trying to create a Software download website, and each software has some file and download link (mac,windows,linux,..). Can anyone tell me how to use 'filefield' for download links(not one). (Sorry, my English is so weak). -
Django on Google App Engine in 2020, Cloud SQL slow and extremely costly, why is it the so popular or what am I doing wrong?
I have been testing django apps on google App engine following the tutorials from google, but I am experiencing extremely slow SQL, and looking at the billing it would be costing a ridiculous amount if I were not on the free credits that came with signup. At this stage I cannot see how this could work in production. It seems that running Django on app engine is more popular than ever, but I do not understand why? In my experience a simple django app would seem to incur charges of more than 100$ pr month from cloud sql and this is without any real traffic to the app? What could I be doing wrong (I am using the db settings from the tutorials)? Why is Django seemingly so popular if Cloud SQL charges are so high? Is there another way to run Django on app engine without using the costly Cloud SQL/PostgreSQL? I choose App engine for the scalability and to avoid having to maintain a VM but at this stage I am wondering if to avoid the GAE completely as I am very worried what the costs would be with a high traffic scenario.. -
I want to join 2 html pages but getting distorted output
I have two html pages one for navbar and other for contact form, when i try to join them both i get distorted single page. Image will be included below. I tried making section but its not helping out:/ This is for a django project so codes might b slightly different. Thanks in advance :) html of navbar <nav> <div class="logo"> <a class="h4" href="{% url 'home' %}">Nihaal Nz</a> </div> <ul class="nav-links"> <li><a href="{% url 'about' %}">About</a></li> <li><a href="#">Cool Cloud</a></li> <li><a href="{% url 'contact' %}">Contact</a></li> </ul> </nav> html of contact page <div class="container"> <form class="shake" action="{% url 'contact' %}" role="form" method="post" id="contactForm" name="contact-form" data-toggle="validator"> {% csrf_token %} <h2>Let me know what you felt.</h2> <div class="row100"> <div class="col"> <div class="inputBox"> <input type="text" name="name" required="required"> <span class="text">First Name</span> <span class="line"></span> </div> </div> </div> <div class="row100"> <div class="col"> <div class="inputBox"> <input type="text" name="email" required="required"> <span class="text">Email</span> <span class="line"></span> </div> </div> <div class="col"> <div class="inputBox"> <input type="text" name="subject" required="required"> <span class="text">Subject</span> <span class="line"></span> </div> </div> </div> <div class="row100"> <div class="col"> <div class="inputBox textarea"> <textarea name="message" required data-error="Write your message"></textarea> <span class="text">Type your message here...</span> <span class="line"></span> </div> </div> </div> <div class="row100"> <div class="col"> <input type="submit" value="Send"> </div> </div> </div> combined html code {% load static … -
Why do we pass in a function as an argument without execution in django?
When creating a post model that includes title, content, and author, I wrote author = models.ForeignKey(User, on_delete=models.CASCADE) for the author because one author can have many posts. My question is why is the function passed to the on_delete parameter not executed. In other words, why isn't it on_delete=models.CASCADE() instead(note the parentheses)? -
InlineFormset is_valid always return False
This is my models: class Company(BaseModel): name = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Company Name')) class CompanyPicture(BaseModel): title = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Company Picture Title')) picture = models.ImageField(upload_to=UploadTo(title), default='static/base_picture_avatar/No Image.jpg', blank=True, null=True, verbose_name=_('Company Picture')) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True, verbose_name=_('Company')) This is my Company Form and Company Picture Form. class CompanyForm(forms.ModelForm): class Meta: model = Company fields = ( 'name', ) class CompanyPictureForm(forms.ModelForm): picture = forms.ImageField(widget=ImagePreviewWidget) class Meta: model = CompanyPicture exclude = () fields = ( 'title', 'picture', 'description', 'avatar_flag' ) Inline FormSet Company Picture: CompanyPictureFormSet = inlineformset_factory( Company, CompanyPicture, form=CompanyPictureForm, fields=( 'title', 'picture', 'company', 'description', 'avatar_flag' ), extra=0, ) Update View. Form Submit have problem at form_valid. pictures.is_valid always return False. I really don't think my models and my forms have problem. But i don't know why can't valid inline formset. class CompanyEdit(UpdateView): model = Company form_class = CompanyForm template_name = 'frontend/company/createdit.html' context_object_name = 'company' success_message = 'Company Information Updated!' def get_context_data(self, **kwargs): context = super(CompanyEdit, self).get_context_data(**kwargs) if self.request.POST and self.request.FILES: context['pictures'] = CompanyPictureFormSet(self.request.POST.get(), self.request.FILES, instance=self.object) else: context['pictures'] = CompanyPictureFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() pictures = context['pictures'] with transaction.atomic(): form.instance.created_by = self.request.user.username self.object = form.save() if pictures.is_valid(): ##### This is always return is False print(pictures.instance) … -
my ajax request not worked in FF,IE but worked in chrome
i have two ajax function in my HTML file: 1 $(document).ready(function(){ $('#send').click(function(){ var value1 = document.getElementById("id1").value; $.ajax({ url: "http://somewhere/somedef", type: "post", // or "get" data: {'data1': value1}, headers: {'X-CSRFToken': '{{ csrf_token }}'}, // for csrf token success: function(data) { }}); }); }); 2 $(document).ready(function(){ $('#check').click(function(){ var value1= document.getElementById("id1").value; var value2= document.getElementById("id2").value; $.ajax({ url: "http://somewhere/somedef", type: "post", // or "get" data: {'data1': value1,'data2':value2}, headers: {'X-CSRFToken': '{{ csrf_token }}'}, // for csrf token success: function(data) { }}); }); }); both work in Chrome right. but in FF and IE, just the first one workes! also the second one works in localhost but not in onlineserver!! -
can we know how many routers did my request touched before getting to the server
As in internet the request is passed through various routers . I am working on a web application in which i want to know how many routers is my request is being passed before reaching the server . Help will be appreciated -
Django - 'WSGIRequest' object has no attribute 'get'
I'm trying to make a really basic site in Django. Right now you just have to enter your name and it gets saved. But even though I followed the instructions here it throws the error 'WSGIRequest' object has no attribute 'get' My views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from django.http import HttpResponse from .forms import NameForm from django.views.decorators.csrf import csrf_protect """ @csrf_protect def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): with open("name.txt" , "w") as f: f.write(form.cleaned_data) return HttpResponseRedirect('/nmindex/') @csrf_protect def vote_page(request): return render(request, 'name.html', {'form': NameForm(request)}) forms.py: from django import forms from django.views.decorators.csrf import csrf_protect class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) urls.py: from django.contrib import admin from django.urls import path, include from nmindex import views urlpatterns = [ path('data/', views.get_name), path('vote/', views.vote_page), path('admin/', admin.site.urls), ] And the template name.html: <form action="/data/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> But when I open http://localhost:8000/vote/: AttributeError at /vote/ 'WSGIRequest' object has no attribute 'get' … -
How to access the local files of the user in django
I am trying to build an FTP client on Django, and i am able to connect to the remote directory and access the files also i am able to upload and download files without an issue. it runs all fine when i am on local host here but when i host my django app on heroku, it will access the heroku files instead of the users local files here how do i access the user's files on the device with which they are using here is my code def get_dir_content(self): dir_content = list() output = list() if os.path.exists(self._dir) and os.path.isdir(self._dir): dir_content = os.listdir(self._dir) for item in dir_content: item_path = os.path.join(self._dir, item) item_info = { 'name': item, 'info': '', 'size': os.path.getsize(item_path), 'perms': oct(stat.S_IMODE(os.stat(item_path).st_mode)), 'type': '', 'full_path': item_path, } if os.path.isdir(item_path): item_info['info'] = 'Catalog' item_info['type'] = 'catalog' else: item_ext = os.path.splitext(item_path) item_info['info'] = '%s-file' % item_ext[1] if len(item_ext) > 1 and item_ext[1] else 'File' item_info['type'] = 'file' output.append(item_info) output.sort(key=lambda i: i['name'] and i['type']) output.insert(0, { 'name': '..', 'info': '', 'size': '', 'perms': '', 'type': 'catalog', 'full_path': os.path.dirname(self._dir), }) return output -
Send signal from contained block in Django
I'm attempting to edit a preexisting Django website to implement new functionality. I have a decent bit of experience with the Vue frontend framework but I'm very new to Django. Currently, I have a page with the following code segment <div class="row"> {% for question in questions %} <div class="col-12 col-md-6 col-lg-4"> {% include "question-card.html" %} </div> {% endfor %} <div> This code is all preexisting and works well. However, I'm trying to implement a feature where hovering over a button/image within the question card displays a popup image as shown below, where hovering over the 'tag' image will show the tags for the question. The issue that I'm encountering is that the tag display is outside the included block, meaning that the tag display will need to be shown in the outside html, instead of being included in the question card block. How would I go about sending a signal to the outer html from within the included block? Any help would be greatly appreciated. -
Django: in a separate app (= not main app), admin doesnt appear
I have my "main" app called app. I have installed two (my own) apps: core and wizard. Thus I have 3 folders. I've declared them in my settings.py. In wizard, I've added admin.py where I've declared the models of my wizard app: from django.contrib import admin from wizard.models.my_model import MyModel admin.site.register(MyModel) When I log in and open the /admin URL, it works, I see my Wizard section with the model. Nothing to do more. For the core app, I did the same but with a folder = module for the admin: I've created and admin section where I've put all my admin declarations (lot of admin stuff). Here's the organization: my_project | +-- app +-- my_project +-- core +-- admin +-- __init__.py +-- admin.py +-- file.py +-- generic.py +-- wizard +-- admin.py Nothing shows up for the core section. But if, in the __init__.py, I add from .admin import * then all my admin code shows up in the /admin URL. How does the "import" of the Django admin work, and when you want admin as a module (= folder, not a single file), what is the right way to do it (I didn't find something for it in the … -
I need a HTML front end to test and use a Django API
newbie here. I followed a guide online and successfully deploy a Keras model with Django API. I wanted to create a HTML file which connected to the Django API, where I can load image into the model for processing, and then send back the prediction. Below are the codes for the API. I need someone to guide me. import datetime import pickle import json from django.shortcuts import render from django.http import HttpResponse from rest_framework.decorators import api_view from api.settings import BASE_DIR from custom_code import image_converter @api_view(['GET']) def __index__function(request): start_time = datetime.datetime.now() elapsed_time = datetime.datetime.now() - start_time elapsed_time_ms = (elapsed_time.days * 86400000) + (elapsed_time.seconds * 1000) + (elapsed_time.microseconds / 1000) return_data = { "error" : "0", "message" : "Successful", "restime" : elapsed_time_ms } return HttpResponse(json.dumps(return_data), content_type='application/json; charset=utf-8') @api_view(['POST','GET']) def predict_plant_disease(request): try: if request.method == "GET" : return_data = { "error" : "0", "message" : "Plant Assessment System" } else: if request.body: request_data = request.data["plant_image"] header, image_data = request_data.split(';base64,') image_array, err_msg = image_converter.convert_image(image_data) if err_msg == None : model_file = f"{BASE_DIR}/ml_files/cnn_model.pkl" saved_classifier_model = pickle.load(open(model_file,'rb')) prediction = saved_classifier_model.predict(image_array) label_binarizer = pickle.load(open(f"{BASE_DIR}/ml_files/label_transform.pkl",'rb')) return_data = { "error" : "0", "data" : f"{label_binarizer.inverse_transform(prediction)[0]}" } else : return_data = { "error" : "4", "message" : f"Error : {err_msg}" … -
OperationalError at /class101/ (1054, "Unknown column 'group20.student_id' in 'field list'") - how to fix it?
Guys i have problem linking FpreigKey to my models. models.py class Student(models.Model): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) class Meta: managed=False db_table='student' class Group20(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) name=models.CharField(max_length=200) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: managed=False db_table='group20' class Nondemandgroup(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) name=models.CharField(max_length=200) acting=models.DecimalField(decimal_places=2,max_digits=1000) cooking=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: managed=False db_table='nondemandgroup' i receive the following message : OperationalError at /class101/ (1054, "Unknown column 'group20.student_id' in 'field list'") what is the cause? how to fix it ? I fisrt removed class meta : managed:"False" it indeed implemented migrations however still recive that OperationalError at /class101/ . -
Django: in a separate app (= not main app), admin doesnt appear
I have my "main" app called app. I have installed two (my own) apps: core and wizard. Thus I have 3 folders. I've declared them in my settings.py. In wizard, I've added admin.py where I've declared the models of my wizard app: from django.contrib import admin from wizard.models.my_model import MyModel admin.site.register(MyModel) -
How to link Django project to APNS .p8 key on Google Cloud Platform
I'm currently trying to add push notifications to my iOS app. My backend server is a Django server deployed on Google Cloud Platform. I've been using django-push-notifications on my backend and I was having trouble actually sending messages. When I try to send a message to a device, I get this error: FileNotFoundError: [Errno 2] No such file or directory: '/AuthKey_0123456789.p8' (Note I replaced the name of the file with dummy data). I placed my .p8 file in the root of my directory. Does anyone know where I should actually be storing the file and also what the path for the APNS_AUTH_KEY_PATH settings key should be? -
how to make django queryset with variable
I have a django model with a boolean field named status a normal query goes like: MyModel.objects.filter(status=True) but in some cases , I need to use this way: fieldname = 'status' MyModel.objects.filter(${fieldname}=True) # wrong syntax how to write this. thanks -
Adding a table with first row as the dates of the months in a web page
I am developing a habit tracker app in Django in which I want to write everyday progress for each habit. I want to create a table in which the first column is a list of all the current habits and first row for dates of the months. In each cell, I have to add fields like Textarea. I have searched for the solution but I am not getting how to do. How to add to the database.