Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TemplateDoesNotExist at / app/school_list.html CBS in Django
Hi Every one i want to see my home page but i get this error again and again TemplateDoesNotExist at / app/school_list.html I'm Using CBS ~ Class Based Views Here is my Settings.py TEMPLATE_DIR = os.path.join(BASE_DIR,"app/templates") INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "app", ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Here is my Tree View Here is my Views.py from django.shortcuts import render from django.views.generic import (ListView) from . import models # Create your views here. class SchoolListView(ListView): model = models.School Here is my urls.py from django.contrib import admin from django.urls import path from app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.SchoolListView.as_view(),name="index"), ] -
How to create django model objects where one of the field is datetime
I have a model class Fixture(models.Model): fixture_id=models.IntegerField(primary_key=True) league_id =models.ForeignKey('League',null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(null=True) event_timestamp = models.DateTimeField(null=True) I am trying to create object from this model. I am using Postgresql and in settings.py activated USE_TZ = True fixt = Fixture.objects.create(fixture_id = fixture_id,league_id_id = league_id,event_date=event_date, event_timestamp = event_timestamp) while i am trying to create object get the folowing traceback django.core.exceptions.ValidationError: ["'event_date' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] -
Django-Admin custom ImageField
I wanna add additional ImageField which obtains image from static folder to the model. I've tried to use some answers from the same questions, but there're nothing about ImageField. -
Django DRY model attributes, classes, and triggers
I'm hacking on an graph-based app with about 50 different types of relationships. They all look like this. class SomeModel(CustomClazz): created_at = DateTimeProperty(default_now=True) updated_at = DateTimeProperty(default_now=True) class Meta: app_label = 'custom_relation' def save(self, *args, **kwargs): self.updated_at = datetime.now() super(SomeModel, self).save(*args, **kwargs) When I started writing this post, I was just looking for a one-liner for class Meta: but I realized most of these lines are duplicates for each model. Although I view the integrity and human-readability of the model as sacred, part of that is keeping my model file short enough that I don't need to split it up into many files. If the model definition becomes extremely dry, I'd still like to be able to set custom attributes for SomeModel. -
How to get the plain password from the password field in the signup form in Django
I have the sign up form in django through which I am taking the entry for the new user. The data can be saved using the u_form.save method but I also need the plain password that the user has entered as that password will be needed to create account in other website through the REST API and hence both password needs to be same. I am able to access the password from the form but when I receive it Django has already encrypted it. How can I get the original plain password? This is what I have tried : views.py from users.forms import SignUpForm, ProfileForm def create(request): context = {} if(request.method == 'POST'): u_form = SignUpForm(request.POST) # fill it with user details p_form = ProfileForm(request.POST, request.FILES) if u_form.is_valid() and p_form.is_valid(): user = u_form.save() email = user.email username = user.username first_name = user.first_name # Accessing plain password password = user.password Profile.objects.filter(user=user).delete() profile = p_form.save(commit=False) profile.user = user profile.save() messages.success(request, f'Account Created') return render(request, 'mainapp/homepage.html', context) forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import Profile class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, label='Email', error_messages={'exists': 'Oops'}, widget=forms.TextInput(attrs={'readonly':'readonly'})) username = forms.Field(widget=forms.TextInput(attrs={'readonly':'readonly'})) first_name = forms.Field(widget=forms.TextInput(attrs={'readonly':'readonly'})) readonly_fields = ('username', 'first_name', … -
Testing a form. What'happening? is this really working?
I have a django form with a field directed to a foreignkey. Initially is empty, I mean without any option. Javascript will add options based on another form field. It's working but I want to test it, without using Selenium (and so, without using javascript). After numerous attempts I write this code and apparently it's working but I don't know why and I'm not sure it's really working. def test_form_validation(self): maschio = Gender.objects.create(name_en='Male', name_it='Maschio') nome = NameType.objects.create(name_en='Name', name_it='Nome') romani = NameLanguage.objects.create( name_en='Romans', name_it='Romani') romani.syntax.add(nome) form = NameForm({'nametype': nome.id, 'gender': maschio.id, 'name': 'Remo', 'namelanguage': romani.id}) # print('1', form) form.fields['nametype'].initial = nome.id form.fields['gender'].initial = maschio.id form.fields['name'].initial = 'Remo' form.fields['namelanguage'].initial = romani.id print('2', form) form.save() self.assertEqual(Name.objects.all().count(), 1) my_name = Name.objects.first() self.assertEqual(my_name.name, 'remo') self.assertEqual(my_name.nametype, nome) self.assertEqual(my_name.gender, maschio) self.assertEqual(my_name.namelanguage, romani) print('end of test') # print('1', form) is commented out because with that the test will be give error on line form.save() (ValueError ... the data didn't validate). Without that line the test pass (!?!). I will expected an error when I call my form bounded because nametype has no option to choose from. nome.id is not one of the ammissible choices. And in effect, as I said, it will give an error if I ask … -
Django Custom Setting Size Attribute on Model Form Not Working
I am trying to specify the length in characters on a model field. I cannot get it to render on the page and drop in the size attribute to the input field. The basic form looks like: class QuestionForm(ModelForm): question = forms.CharField(label="Question") class Meta: model = Question fields = ["question"] I have tried the following: class QuestionForm(ModelForm): question = forms.CharField(label="Question",widgets=forms.TextInput(attrs={'size':'50'})) class Meta: model = Question fields = ["question"] And class QuestionForm(ModelForm): question = forms.CharField(label="Question") class Meta: model = Question fields = ["question"] widgets = { 'question': forms.TextInput(attrs={'size':'50'}) } And class QuestionForm(ModelForm): question = forms.CharField(label="Question") def __init__(self, *args, **kwargs): super(QuestionForm,self).__init__(*args, **kwargs) self.fields['question'].widget.attrs['size'] = '50' The form is part of a formset factory, do you need to do anything different when using that? ApplicationForm = forms.formset_factory(QuestionForm) ModelApplicationForm = forms.modelformset_factory(Question, fields=('question',)) -
django , angular :- How to render the page according to the session status?
We are checking the session details from Django-sessions. If the session is active the "Layout.html" page should open else "login.html" page should open. Both "Layout.html" and "login.html" are in Angular 7. I have tried to send the JSONdata(status of login) using render() from django to angular and according to that status I used "*ngIf" to open the files, but I was not able to access the JSONdata outside the index.html -
Get all related data from model and save it to the another model using django signal
I just want that if the admin insert the Course(ABM) and Education Level (Grade 11) and Section(Chronicles) in table student enrollment record it will get all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. student enrollment record subjectsectionteacher This is what the result I want Result I want This is the result I get what I got result -
How to create a dynamic form with values in a model in Django?
I am creating a kind of quiz app where i provide a quiz (say 10 question) to a user with choices for each question. I want to save the user's selected choices in a database. I dont want to check selected choices against an answer, just store user's selected choice(s). I have 3 models, one each for Questions, Choices and UserSubmission. UserSubmission model has 3 field, User, question and choice. Each entry in this database maps a user with a question and his selected choices for that question. I am having trouble creating a form with all (say 10) questions and their respective choices and storing them in the database. -
Django update data on click button
i have a classic form and a submit button that save data in model1 and i would like to update data of another model2 calling a function on the click button I try tu use an Ajax request like another mentionned in another post: Django: How to Like an Object with Ajax I try to implement an Ajax request and start with a very simple code (just want to print 'Randomize' when my method is called I have a simple form that will store data in its related model (Randomisation) But I want to update 2 others models when user click on the submit button of the form (id=randomize) I have a method in my view that should be call by Ajax but it does not work I enter in the JQuery function (alter('test') == OK) but the randomize method is not called as I have no print in my console (print('test') != OK) and the confirm is not called (confirm("You have randomize the patient") != OK) What is wrong? urls.py from django.urls import path from . import views app_name='randomization' urlpatterns = [ path('detail/<int:pk>', views.randomisation_detail, name='randomisation_detail'), path('edit/', views.randomisation_edit, name='randomisation_edit'), path('', views.index, name='index'), path('randomize/', views.randomize, name="randomize"), ] views.py @csrf_exempt def randomize(request): … -
Why is there a difference between GitHub webhook local development hashed secret vs production hashed secret?
I am validating the hashes of the signature passed with the GitHub webhook POST request to the hash of my secret. Working locally, the hashes are computed as equal (as they should be) because the secret sent from GitHub is the same as my local secret. However, when I change the URL of the webhook payload from my local development URL to my production URL, the hash of the secret sent in the webhook POST is different. The payload of the POST request is the exact same between the two environments. The only difference is the URL GitHub is POST-ing to. The secret does not change between the two environments either. My project is a Django project and is hosted on Heroku. Here is the code that compares the hashes: header_signature = request.META.get('HTTP_X_HUB_SIGNATURE') if header_signature is None: return HttpResponseForbidden('Permission denied.') sha_name, signature = header_signature.split('=') if sha_name != 'sha1': return HttpResponseServerError('Operation not supported.', status=501) mac = hmac.new(force_bytes(settings.GITHUB_WEBHOOK_KEY), msg=force_bytes(request.body), digestmod=sha1) if not hmac.compare_digest(force_bytes(mac.hexdigest()), force_bytes(signature)): return HttpResponseForbidden('Permission denied.') Any ideas why the hashes are different between local and development, even though the only thing that changes is the URL GitHub is sending the POST request to? Something to do with Heroku maybe? -
Return results from more than one database table in Django
Suppose I have 3 hypothetical models; class State(models.Model): name = models.CharField(max_length=20) class Company(models.Model): name = models.CharField(max_length=60) state = models.ForeignField(State) class Person(models.Model): name = models.CharField(max_length=60) state = models.ForeignField(State) I want to be able to return results in a Django app, where the results, if using SQL directly, would be based on a query such as this: SELECT a.name as 'personName',b.name as 'companyName', b.state as 'State' FROM Person a, Company b WHERE a.state=b.state I have tried using the select_related() method as suggested here, but I don't think this is quite what I am after, since I am trying to join two tables that have a common foreign-key, but have no key-relationships amongst themselves. Any suggestions? -
Django Doubling the path leading to a 404
I am trying to redirect the user to another page if login is successful and leading the user to the log in page if the login is unsuccessful. However, Django is leading me to the path http://127.0.0.1:8000/loginuser/loginuser in either case. Can someone point out the mistake and offer a correction? views.py def loginuser(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user) return render(request,'getstarted.html') else: messages.info(request,"Invalid Credentials!") return render(request,'login.html') else: return render(request,"login.html") urls.py urlpatterns = [ path('admin/', admin.site.urls), path("",views.HomePage,name="home"), path("registeruser.html/",views.RegisterUser,name='registeruser'), path("registerdoctor.html/",views.RegisterDoctor,name='registerdoctor'), path("loginuser/",views.loginuser,name='login'), path("logoutuser/",views.logoutuser,name='logout'), path('aboutus/',views.about,name='about'), path('feedback/',views.feedback,name='feedback'), path('start/',views.getstarted,name='getstarted'), ] -
Read excel file in Django views using pandas module
I'm trying to read an excel file using pandas in a views method. But the server stopped with: File "/Users/ronsair/anaconda3/lib/python3.6/site-packages/py/_error.py", line 44, in __getattr__ raise AttributeError(name) AttributeError: __name__ Code: import pandas as pd def extract(request): df = pd.read_excel('update.xlsx') return render(request, "work/index.html") Can you help please? -
what is the best way to manage models in django application by separating the entities involved in project?
I started a simple contact list project and This is the current structure: project/ app/ app/ __init__.py settings.py urls.py wsgi.py core migrations/ entities/ city.py group.py town.py user.py __init__.py admin.py apps.py Dockerfile manage.py requirements.txt docker-compose.yml .env.dev I used this structure as a practice to manage the models in my django project. the entities folders are the database models and I want to come up with a good approach to keep them as separate and clean as possible. but when I run migrations with this command docker-compose run web sh -c "python manage.py makemigrations core", I get this: No changes detected in app 'core' It's probably because models.py does not exists I really need to practice the best possible approach for server programming to be able to work in a team in the future. I was wondering if anyone could help me in here and if possible please include sample codes and references. -
django forms modelchoicefield dependent to other modelchoicefield (parent child)
In django forms a have a modelchoicefield like country and a second modelchoicefield like cities. I want when I select the countries only the corrensponding cities to be available to the second modelchoicefield. A simple parent - child relationship in django forms fields. -
Wagtail: FieldError when creating instance of snippet
I'm using Wagtail v2.6.3 and Django 2.2.6. I'm trying add snippets which just consist of a plain text description and a StreamField. However, it only seems to work if I include a 'title' field. If I don't have a 'title' field I get a FieldError exception when try to create an instance of the snippet from the admin page. I've used snippets before without title fields, so I know it's something I am doing wrong, but I'm new to Django and Wagtail so it's difficult to know where to look and what to make of the debug info. Here's the snippet (uncommenting the two lines with 'title' in makes the code work), but I don't want a title field. #Content box for the sidebar @register_snippet class SidebarBox(models.Model): #title = models.CharField(max_length=100, blank=True, verbose_name="Item title"); description = models.CharField(max_length=100, blank=True, verbose_name="Optional description for this item (for ID purposes - this does not create any visuals)"); body = StreamField([ ("heading", blocks.CharBlock()), ("paragraph", blocks.RichTextBlock()), ("image", ImageChooserBlock()), ], null=True, blank=True); panels = Page.content_panels + [ FieldPanel("description"), #FieldPanel("title"), StreamFieldPanel("body"), ]; def __str__(self): return self.description; From the debug info it sounds like something is still trying to access the 'title' field of SidebarBox, but I don't know where. … -
I want to Serialize dept_name as well as it's "id" in one single model serializer. How should I do it?
I want to serialize "Department name"(dept_name) as well as Department ID(id) in the Employee Model Serializer from department Model In the Employee Serializer I want to Serialize "Department name" as well as "Dept ID" models. I mentioned Department Model in class Meta of Employee Serializer as well MODELS class Department(models.Model): dept_name = models.CharField(max_length=10) class Employee(models.Model): emp_name = models.CharField(max_length=15) email = models.EmailField(unique=True) password = models.CharField(max_length=14) designation = models.CharField(max_length=20) dept_id = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) class Meta: ordering = ('id',) def __str__(self): return self.emp_name SERIALIZER class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = [ 'id', 'dept_name', ] class EmployeeSerializer(serializers.ModelSerializer): dept_id = serializers.SlugRelatedField(queryset=Department.objects.all(), slug_field='dept_name') deptname = DepartmentSerializer() class Meta: model = Employee,Department fields = [ 'id', 'emp_name', 'email', 'password', 'designation', 'dept_id', 'deptname', ] -
create django rest-framework request without url
I want to have a fake request object just for testing its params, a request without URL. The object that I can set its params like this: request.GET = {"offset":0, "limit":10} but when I import Request from rest-framework as below: from rest_framework.request import Request request = Request(request=None) I deal with this error: AttributeError: 'NoneType' object has no attribute 'encoding' can someone help me, to have the request object which I want? -
Django authentication error : 'str' object has no attribute 'pk'
I am having problem in Django authentication, whenever I try to login it gives 'str' object has no attribute 'pk' error. I am using MySql as my database. # views.py def user_login(request): if request.method == 'POST': form = AuthenticationForm(request,data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate( username= username,password= password) if user is not None: login(request,username) return redirect('app:home') else: return render(request,'404error.html',context={}) else: return render(request,'404error.html',context={}) form = AuthenticationForm() return render(request,'login.html',context={'form':form}) def user_logout(request): logout(request) return redirect('app:home') #urls.py # from django.contrib import admin from django.urls import path,include # from app import urls from . import views app_name = 'app' urlpatterns = [ path('',views.home,name='home'), path('register/',views.register,name='register'), path('login/',views.user_login,name='user_login'), ] -
I can't call the function merge in the file merge.py from views.py
I want to call the merge function in the file merge.py when a user has entered his input in the create_proposal.html. my merge.py file looks like: from __future__ import print_function from mailmerge import MailMerge def merge(name, refer): template = 'template.docx' document = MailMerge(template) document.merge( reference = refer ) print('merge') document.write(name) And my views.py file looks like: from django.shortcuts import render from django.http import HttpResponse from .forms import createNewFinancial from .merge import merge def inputPage(request): if request.method == 'POST': form =createNewFinancial(request.POST) if form.is_valid(): name = form.cleaned_data['name'] reference = form.cleaned_data['reference'] merge(name, reference) form = createNewFinancial() return render(request, 'create_proposal.html', {'form': form}) def resultPage(request): return render(request, 'result.html') the template create_proposal.html looks like: {% extends 'base.html' %} {% block content %} <div class="row"> <div class="col-sm-4" style="margin-left: 10vw;"> <h2>New Financial Proposal</h2> <form class="form-group" action="result/" method="post"> {% csrf_token %} {{form}}<br><br> <input type="Submit" class="btn btn-primary" value="Create"/> </form> </div> </div> {% endblock content %} I am trying to create a word document with file name from user input in create_proposal.htmland also merge the reference number from user input in the template using mailmerge -
How to control the amount of notifications sent by django signal
I have a django admin based CRM and API which updates my google spreadsheet. It is triggered by django signals. Sometimes I need to send request once with a single row change in spreadsheet. Sometimes i need to update multiple rows. The problem is that django signals trigger every time a change is registered in DB, but i can update my spreadsheet with a single request. For example, I need to remove 2 rows: Achange in DB registered for 1 row, A Request is sent to spreadsheet, A change in DB registered for 2 row, A Request is sent to spreadsheet. But I need: A change in DB registered for 1 row, A change in DB registered for 2 row, A Request is sent to spreadsheet. All the unneccessary requests pile up and take a lot of time to process. How do i register all the changes only once to send a single request? An additional question. I have 2 models: Project and ProjectImages. PI is related to P, so if i delete P, then before its removed for every related PI instance i see signals beeing triggered. Whole spreadsheet is removed and there is no neccessity to remove rows … -
Django Comment form leads to a blank page and doesn't post the comment
Right after I type the comment in the form and click the button, it gives me a white screen and it also didn't post the comment either I have a django code as shown below, I have already added the success_url but it still shows a blank screen after I click the button, and It didn't save the comment either #views.py class MessageDetailView(DetailView): model = Message template_name = "messaging/detail.html" success_url = "post/<int:pk>" #queryset = Message.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(message=self.object) context['form'] = CommentForm() return context #detail.html <div class="text-area"> <div class="comment-area"> <p>{{ comment.date_posted|date:"H:i, j-n-o" }}</p> <hr> <p> {{ comment.comment }} </p> </div> </div> #forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment',) #models.py class Comment(models.Model): message = models.ForeignKey(Message,on_delete=models.CASCADE) comment = models.TextField(max_length=50) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return "Comment on {}".format(str(self.date_posted)) I am trying to show the comment and direct it to the detail page itself, help appreciated. -
get_object_or_404 don't show the value it gets from DB
I am building af blog in django. When I click to see/read details on an article and its related comments, I only see the comments, the details of the article doesn't show, but the page do not fail. I have tried just to call the model 'LifePost' and then it shows data in the template but not the related comments (only the fields for it). I have tried to call the method that use get_object_or_404 to call the model 'LifePost' and then it shows all the comments to the related article but not the article data (only the fields for it) models.py class Comment(models.Model): post = models.ForeignKey(LifePost, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=100) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) views.py def life_detail(request, slug): template_name = 'life_detail.html' post = get_object_or_404(LifePost, slug=slug) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, template_name, {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form}) urls.py path('life/<slug:slug>/', views.life_detail, name='life_detail'), (NOT IN USE, but works and show the article correctly) #path('life/<slug:slug>/', …