Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
i am trying to show flights related to the id when u type in the id on the url but it brings up an error (function-object-has-no-attribute-objects)
from django.shortcuts import render from django.http import Http404, HttpResponse from .models import flight Create your views here. def index(request): flights = flight.objects.all() context = { "flights": flight } return render(request,"flights/index.html",context) def flight(request, flight_id): try: flight = flight.objects.get(pk=flight_id) except flight.DoesNotExist: raise Http404("flight does not exist") context = { "flight": flight } return render(request,"flights/flight.html", context) -
How can I import the structure of a docx in python-docx?
I want to build a docx file via python-docx in django. However, this document is based on a pre-existing template, which has several pages, styles and so on. And I have this template only as a docx file. Do I have to compare with the template and give python-docx instructions for every single paragraph and run? Or is it somehow possible to import the structure of a docx file with python-docx? I found examples how to read an existing file, getting all the text and so on. But I did not find instructions how to get the structure of a file and therefore how to rebuild a complex document easily. -
Display username in template with custom user model as welcome message
I want to display username in base.html but it's not working.I am learning django if you see any mistake please tell. # settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', ) User model class accountUser(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] base.html <li><a href="#">{{ accountUser.username }}</a></li> <li><a href="{% url 'account_logout' %}">Logout</a></li> -
how to add a choice field to django user model
I am completely satisfied with the way user model handles the auth, but I want to add a choice field to it that the users could choose between being a patient, doctor or a regular user. then creating the profile model according to their chosen field. for instance the patients have info about their sickness but doctors don't. is there any other way except abstractuser ? because I really don't want to start make another project again from scratch. thank you for the responses this is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) and this is my forms.py: class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] -
Django - Password2 from User Registration Form coming a none in request dict
below is the cleaned data from User registration form and appears password2 is not in the request. Not sure what is the reason. I have included the form and view code below. please assist why password2 is missing. {'username': 'xyzabc', 'first_name': 'xyz', 'last_name': 'abc', 'email': 'xyzabc@gmail.com', 'password1': 'kjfhekwjfhekjf'} forms.py class RegistrationForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'username'}), label="Username") first_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'first_name'}), label="First Name") last_name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'last_name'}), label="Last Name") email = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'email'}), label="Email") password1 = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control','type':'password', 'name':'password1'}), label="Password") password2 = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control','type':'password', 'name': 'password2'}), label="Password (again)") class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] def clean(self, *args, **kwargs): cleaned_data = super(RegistrationForm, self).clean() print(cleaned_data) if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError("Passwords don't match. Please try again!") return self.cleaned_data views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from .forms import RegistrationForm def registerPage(request, *args, **kwargs): form = RegistrationForm() register_context = { 'form': form } print(register_context) if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return render(request, "register.html", register_context) -
["'02-05-2020' value has an invalid format. It must be in YYYY-MM-DD format."]
I get the above error as I try to enter 02-05-2020 date in the database. I want the format of date entered to be DD-MM-YYYY and not YYYY-MM-DD. I am using DateField. date = models.DateField() -
Django/MySQL LOCK TABLE with transaction.atomic gives savepoint does not exist
I have activities, which can have multiple 'action' holders, where eacht 'action_holder' can have a dynamic role. For example 'gym-leader', 'student', etc. These roles can be create by the client and are not fixed. Also the 'primary' action_holder_role is denormalized on the model, because otherwise the QuerySet filtering would take to long (more then 2000 activities are loaded on one page, if I would use normal cache instead of the database denormalisatie it would take 20+ seconds instead of 2/3 seconds). For simplicity a lot of fields are taken out in the example. Please note it creates a race condition, which is why the LOCK TABLE is necessary. class Activity(models.Model): data = models.DateField() action_holders = models.ManyToManyField(settings.AUTH_USER_MODEL, through='ActivityUserRole', related_name='realactivities') cached_primary_action_holder = models.ForeignKey('ActivityUserRole', null=True, blank=True, on_delete=models.SET_NULL, related_name='activity_primary_action_holder_role') order = models.IntegerField() class ActivityUserRole(models.Model): role = models.ForeignKey('Role', on_delete=models.PROTECT) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) primary = models.BooleanField(default=False) # primary for realactivity class Role(models.Model): name = models.CharField(max_length=255) My problem is that when I create a new activity, I give the new_action_holders as an argument to the activity and call set_new_action_holders to create the corresponding ActivityUserRoles after saving the new activity (because the ActivityUserRole needs the activity, so it should be saved first). The … -
django-graphene mutation of many to many field
CreateArticle(input:{ title: "title", subTitle: "subtitle", imageCaption: "new caoption", publish: false, categoryName: "test", tagName: "test" }) { article{ title subTitle category{ name } } } } this code get error message "Direct assignment to the forward side of a many-to-many set is prohibited. Use tags.set() instead." -
Python Arelle library throwing Permission Error "/home/nagat/"
Created an XBRL parsing python script using Arelle library which works fine locally but when I deployed it on the server, In celery log I'm getting this error saying Permission Error "/home/nagat/" did some research and found an issue on GitHub which refers to this problem (https://github.com/josw123/dart-fss/issues/2) still no luck. -
Best approach to writing a python based app with web frontend and backend tasks
I've been researching and unsuccessfully trying to use Django and Django Background tasks for a webapp I'm writing. This app will be launch as a service on linux and will automatically start background tasks. The web interface will show various pieces of information. Task status etc.., pausing the background tasks etc.. I have the backend running and logging, but now I'm wanting to put the web interface over the top, and I'm not sure on how to do this. I've looked at Django/Background tasks, but can't quite see how they can be used. The background tasks should start automatically without anyone hitting a webpage. Maybe I'm over complicating it using Django, and I should just use threading and run a simple HTTP web server, or create them as two seperate apps. Background Processor <-> Database <-> Web Application (gets data from database) Background Tasks Processing (Start automatically run application is launched using S6 overlay) Web Interface (started when background daemon is launched, display information on background processing) Thanks any help and direction offered. -
using custom signup form in django allauth and rest-auth and modify the serializer
i am trying to use custom user model and a custom sugnup form in django rest-auth and allauth but i cannot modify the django restauth signup/ register form can anyone help with it models.py from django.db import models from django.core.validators import RegexValidator from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from .managers import UserManager phone_number_regex = RegexValidator( regex= "^((\+91|91|0)[\- ]{0,1})?[456789]\d{9}$", message="Please Enter 10/11 digit mobile number or landline as 0<std code><phone number>", code="invalid_mobile", ) USER_CHOICES = [ ("customer","customer"), ("shopkeeper","shopkeeper"), ("rider","rider") ] class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) phone = models.CharField(max_length=14, validators=[phone_number_regex]) user_type = models.CharField(choices=USER_CHOICES,max_length=50) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name','user_type','phone'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name manager.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, password, **extra_fields): """ Creates …