Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to print user.surname in django html
In my model i use mixin account: models.py class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py lass UserCreateForm(UserCreationForm): email = forms.EmailField(max_length=20) surname = forms.CharField(max_length=20) class Meta: fields = ('username','surname','email') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Name' self.fields['surname'].label = 'Surname' self.fields['email'].label = 'Email Address' I can print the username in HTML {{user.get_username}} How to print surname? I tried to {{user.get_surname}} but it does not work. Please help -
Django tries to serve cached image that does not exist
I'm running django 1.7.1 I'm trying to render a .html page that makes used of some cached images. This is the Image model that these images belong too: image_pbox = models.ImageField( upload_to='pbox', blank=True, max_length=255, storage=STORAGE, null=True) image_pbox_300 = ImageSpecField( [ResizeToFit(300, 300)], source='image_pbox', format='JPEG', options={'quality': 90}, cachefile_storage=STORAGE) On the webpage, I can use pagintaion to select different sets of Image instances to return, and eventually they are rendered using: {{image.image_pbox_300.url}} Now, initially this all worked fine. Then, my server had a power issue and the drive on which these cached images were located was temporarily disconnected. Now, I can use my web page to render some cached images - I'm assuming those that have not been cached before, but this is a guess. Other images - ones that I am sure off were cached before - return a permission error. Remember that this are just different instances of the same model. E.g. the first few images return an error, the later ones don't. The permission error: OSError at /make_data_request/ [Errno 13] Permission denied: '/data/gallery/config/media/CACHE/images/pbox/MVSrCYHsteI6D0ocQfiLwwy' The permission error seems straightforward. Must be something with ..permissions, right? Everything related to permissions seems to be configured properly - and remember, a selection of images … -
Django: template renders wrong
I'm developing a web application that consists of registering employees, customers and suppliers in a database, via Python and Django. The code works perfectly, but when I register a new customer it presents me with the following error: Error The customer is registered in the database but the template that lists the customers does not load. Can you help me? -
How to incorporate FB graph api data in django template?
I'm using the FB graph API to retrieve data on instagram users such as the bio, nb of followers, profile pic ... I am 2 python files: fbsettings.py which contains the access token, my FB account credentials and where I set the insta username instadata.py that uses the settings from fbsettings and a function to get the info from the graph API Now I am trying to incorporate the information retrieved from the graph api into a Django client profile template where the insta username has been captured manually (so its a field in a model). I have added the 2 files (fbsettings.py and instadata.py) in the project folder (same level as views.py) and I'm trying to create a class in the views.py files but when importing functions from instadata.py which itself imports functions from fbsettings.py I get the error below: File "C:\Users\User\Documents\project\my_app\instadata.py", line 1, in <module from fbsettings import getDetails, makeApiCall ModuleNotFoundError: No module named 'fbsettings' When I just run the instadata.py it works great. What I am missing? Is there another way to do this? -
Display Parent page variable on Child page with template - wagtail/django
Tried to look for solution but probably missed it, probably because of unsure what exactly to ask. I am new to Wagtail/Django. How can I make variables from parent page visible on child page? I am trying to make a page that has Header, Content and Footer. I enclosed those inside {% block name_of_section %}. Now I have a child page (actually grandchild, but whatever) which template consists only of: {% extends main_page.html %} {% load wagtailcore_tags wagtailimages_tags static wagtailuserbar %} {% block content%} {{ page.photo }} {{ page.article }} {% endblock %} and the main page template (truncated of course): {% load wagtailcore_tags wagtailimages_tags static wagtailuserbar %} htmlcode {% block header %}some stuff here{% endblock %} {% block content %}stuff to be replaced in child pages here{% endblock%} {% block footer %}{{ page.address }} {{ page.links }} {{% endblock %}} finishing html code here Now the problem I am having is that when I load the child page, the header, content and footer display almost fine. The exceptions are those variables address and links from the footer. I assume it is because it gets passed to the child page still as {{ page.address }} and of course the child … -
Where can I find a reference for Django template syntax, specifically for accessing form field attributes
Just like the title says. I have a big form and I render it through a template like this: <table> {% for field in form.visible_fields|slice:":59" %} <tr> <td> {{ field.label_tag }} </td> <td>{{ field }}</td> </tr> {% endfor %} </table> I would like to know if I can do something like {% if field.is_boolean_field %} or {% if field.widget == select %}. However, even better would be if someone could point me in the direction of such documentation. For some reason I couldn't find it in the Django docs. -
Django "snippet_detail() got an unexpected keyword argument 'snippet_slug'" error
I am trying to submit the snippet and redirect to a page where I get the snippet detail page. Below is corresponding part of my views.py: def index(request): if request.method == 'POST': f = SnippetForm(request.POST) if f.is_valid(): snippet = f.save(request) return redirect(reverse('snippet_detail', args=[snippet.slug])) else: f = SnippetForm() return render(request, 'djangobin/index.html', {'form': f}) def snippet_detail(request, snippet_slug): snippet = get_object_or_404(Snippet, slug=snippet_slug) snippet.hits += 1 snippet.save() return render(request, 'djangobin/snippet_detail.html', {'snippet': snippet}) and corresponding part of my urls.py: urlpatterns = [ path('',views.index,name='index'), path('<int:snippet_slug>/',views.snippet_detail, name='snippet_detail'), ] But I get the error: TypeError at /1598354748868126/ snippet_detail() got an unexpected keyword argument 'snippet_slug' Python version: 3.8.2 Django version: 2.0 OS: Windows 8.1(32 bit) App name: djangobin -
Can we add something like *.sqlite3 in settings.txt in Django to refer multiple db files?
I am new to Django, in order to keep the db file light weighted I wanted to store monthly data in a separate sqlite3 file so that I can easily backup or restore monthly data in Django server. right now I have added as DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } this refers to a single db file. can I use *.sqlite3 so that it maps to all the sqlite3 files present in the folder? Thanks in advance -
Django aggregate ForeignKey hierarchy
Let's say I have the models Foo, Bar and FooBar. Bar has a ForeignKey reference to Foo. FooBar has a ForeignKey reference to Bar. Given a Foo-object, how do I most efficiently gather all related FooBar objects? I don't want this: foobars = [] for bar in foo.bar_set.all(): for foobar in bar.foobar_set.all(): foobars.append(foobar) -
Im not able to insert a data in django form-checkbox
Im not able to insert a data in django form,im using a custom form which contain check box.when i try to save the data it gives error message(MultiValueDictKeyError at /Hostel_Accomodation 'hostel_Boys') -
The view blogapp.views.blogpost didn't return an HttpResponse object. It returned None instead
from django import forms from .models import Blog I just rewrite code this point, from ↓: # class BlogPost(forms.ModelForm): # class Meta: # model = Blog # fields = ['title', 'body'] to ↓: class BlogPost(forms.Form): email = forms.EmailField() files = forms.FileField() url = forms.URLField() words = forms.CharField(max_length=200) max_number = forms.ChoiceField(choices=[('1','one'), ('2','two'),('3','three')]) and views.py file is here ↓: from django.shortcuts import render, get_object_or_404, redirect from .models import Blog from django.utils import timezone from .form import BlogPost from django.views.decorators.http import require_http_methods # Create your views here. def home(request): blogs = Blog.objects #쿼리셋 return render(request, 'home.html', {'blogs'`enter code here`:blogs}) def detail(request, blog_id): details = get_object_or_404(Blog, pk=blog_id) return render(request, 'detail.html', {'details':details}) def new(request): return render(request, 'new.html') def create(request): blog = Blog() blog.title = request.GET['title'] blog.body = request.GET['body'] blog.pub_date = timezone.datetime.now() blog.save() return redirect('/blog/'+str(blog.id)) #이 URL로 넘기세요 처리된 정보를 def blogpost(request): if request.method =='POST': form = BlogPost(request.POST) if form.is_valid(): post = form.save(commit=False) # post.pub_date = timezone.now() post.save() return redirect('home') else: form = BlogPost() return render(request, 'newblog.html',{'form':form}) I don't know why I only rewrite 'form.py' file, but vscode program says "The view blogapp.views.blogpost didn't return an HttpResponse object. It returned None instead." what should I do?? help.. -
How can I not put data in ImageField in Django?
I am to store images in imagefield. But I don't want to print out an error even if I don't put an image in ImageField. In other words, I want to leave ImageField null.I also tried null=True and blank=True to do this, but it didn't work properly. What should I do to make it possible? Here is my code. class post (models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=40) text = models.TextField(max_length=300) image1 = models.ImageField(blank=True, null=True) image2 = models.ImageField(blank=True, null=True) image3 = models.ImageField(blank=True, null=True) image4 = models.ImageField(blank=True, null=True) image5 = models.ImageField(blank=True, null=True) -
Run django program in debug mode with virtual env in pycharm?
I am new to django and pycharm, when i am trying to run my code with terminal everything works fine first i will activate my virtual environment and then use this command: python manage.py runserver 0.0.0.0:8000 But like this i am unable to go through breakpoints in the code and debug my application. Is there any command in python like above on which my code will execute on debug mode and stops on respective break points. I also try to edit my configure but that didnot workout, can you also guide me where i have to place my virtual coomand in this to activate virtual environment during debug mode. -
how to fetch the value of src, width, height of iframe in Django using GET method
views.py def add(request): report_list = {} if request.method == "POST": src =request.POST['src'] width=request.POST['width'] height=request.POST['height'] name=request.POST['name'] #context = {'report_list': report_list} report_list={'src':src, 'width':width, 'height':height, 'name':name} return render(request, 'report_one.html', report_list) else: src=request.GET.get('src', '') width=request.GET.get('width','') height=request.GET.get('height','') name=request.GET.get('name', '') #report_list={'src':src, 'width':width, 'height':height, 'name':name} #report_list={'src':request.POST['src'], 'width':request.POST['width'],'height':request.POST['height'], 'name':request.POST['name']} return render(request, 'report_two.html', report_list ) index.html <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Reports<span class="caret"></span></a> <ul class="dropdown-menu"> <li class="dropdown-header">Reports</li> <li> <div class="buttons pull-right"> <a href="{% url 'report:reporttest' %}" class="btn btn-xs btn-success" title="Add"><i class="fa fa-plus"></i></a> </div> <a href="{% url 'report:reporttwo' %}">Report one</a> </li> {% for item in report_list %} <li> <a href="{% url 'report:add' %}">{{item.name}}</a> </li> {% endfor %} </ul> **if** part getting the value of src, width ,name of report, and height from the user and then created report name should shown in the dropdown. When user click on the report name the created report will display on the screen and i think this part is handle by else ...but the problem is that i got the blank page **else** part giving blank value of iframe src, width,height -
django-crontab is not executing function
I am trying to set up a cron every minute to the following test function using django_crontab which hits a specific url but its not executing at all. drc / data_refresh.py def test(request): requests.post("https://example.com/sendmail") return JsonResponse({'message' : 'test_success'}) settings.py INSTALLED_APPS = [ ...... 'django_crontab', ] CRONJOBS = [ ('* * * * *', 'drc.data_refresh.test', ['request']) ] After the above steps, I have done ./manage.py crontab add and I waited for sometime but now nothing happens. When i ran the cron manually using ./manage.py crontab run cron_task_id , it executed perfectly. Please suggest where I am doing wrong. -
Why PDFkit Generate PDF which is not same as my HTML page?
I wrote a view for making an HTML page to a PDF. def public_profile_pdf_view(request, slug): template = get_template('public_profile_pdf.html') queryset = Professional.objects.filter( slug=slug ) html = template.render({'data': queryset}) options = { 'page-size': 'Letter', 'encoding': "UTF-8", "enable-local-file-access": None, } pdf = pdfkit.from_string(html, False, options=options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="person.pdf"' return response And The Page Screen Shot I want to Convert into PDF: See the Original Image: Click Here After Downloading the PDF it shows different than the Orginal. See This: After Converted to PDF Any Experts Here!!! -
Django project doesn't work when setting project root url to not "/"
I had a Django project (using Django, uwsgi and Nginx to deploy it) on a linux server that works well when I'm setting the project root url in Nginx as location / { uwsgi_pass django; include /path/to/project/uwsgi_params; } So the project can be accessed using url like: www.mysite.com However, I'm planing build more web projects on this server, and want to visit them using different urls like: www.mysite.com/oldproject www.mysite.com/project2``` So I changed my now existing project's Nginx conf file as: location /oldproject { uwsgi_pass django; include /path/to/project/uwsgi_params; } however, when I visit the old project using www.mysite.com/oldproject I get feed back like: Not Found. cant get resource on the server I'm pretty sure that the Nginx is working well with uwsgi because I did some simple test, so, what is going wrong? The full configuration is shown below: Nginx conf: # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///web/welib/welib.sock; # for a file socket } # configuration of the server server { listen 443 ssl; ssl_certificate /etc/nginx/certif/1_www.xxxxxxx.crt; ssl_certificate_key /etc/nginx/certif/2_www.xxxxx.key; ssl_session_timeout 5m; ssl_ciphers ECDHE8-GCM-SHA256:ES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste #log config … -
Django xlsx format using xlsxwriter
I am using xlsxwriter in Django to export xlsx format when ever the user click on button, it do export the xlsx format but untidy in excel sheet. I am using Django==1.9.5 and XlsxWriter==1.1.8 Django CODE in views.py: def export_student(request): students=Student.objects.all() filename = "student_list.xlsx" workbook = xlsxwriter.Workbook(filename) row = 3 worksheet = workbook.add_worksheet() worksheet.set_column('A:A', 6) worksheet.set_column('B:B', 12) worksheet.set_column('C:E', 15) worksheet.set_column('F:F', 25) worksheet.set_column('G:G', 70) worksheet.set_column('H:H', 25) worksheet.set_column('I:I', 12) worksheet.set_column('J:J', 25) worksheet.set_column('K:K', 12) worksheet.set_column('L:L', 25) worksheet.set_column('M:M', 77) maintitlecell = workbook.add_format({ 'bold': 1, 'border': 1, 'align': 'center', 'valign': 'vcenter', 'font_color':'red', 'font_size':18}) titlecell = workbook.add_format({ 'bold': 1, 'border': 1, 'align': 'center', 'font_size':12, 'valign': 'vcenter'}) datacell = workbook.add_format({ 'border': 1, 'align': 'left', 'font_size':10, 'valign': 'vcenter'}) worksheet.merge_range('A1:M1', "Student List", maintitlecell) worksheet.write("A2", "Count", titlecell) worksheet.write("B2", "Student NO", titlecell) worksheet.write("C2", 'Name', titlecell) worksheet.write("D2", 'Surname', titlecell) worksheet.write("E2", 'Gender', titlecell) worksheet.write("F2", 'Birthdate', titlecell) worksheet.write("G2", 'Previous School', titlecell) worksheet.write("H2", 'Birthplace', titlecell) worksheet.write("I2", 'Annul Fee', titlecell) worksheet.write("J2", 'Nationality', titlecell) worksheet.write("K2", 'Id No', titlecell) worksheet.write("L2", 'Blood Type', titlecell) worksheet.write("M2", 'Address', titlecell) for student in students: worksheet.write('A'+str(row) , row-2,centerdatacell) worksheet.write('B'+str(row) , student.id_no,datacell) worksheet.write('C'+str(row) , student.name,datacell) worksheet.write('D'+str(row) , student.surname,datacell) worksheet.write('E'+str(row) , student.guardian_type,datacell) worksheet.write('F'+str(row) , student.birthdate,datacell) worksheet.write('G'+str(row) , student.previous_school,datacell) worksheet.write('H'+str(row) , student.birthplace,datacell) worksheet.write('I'+str(row) , student.annual_fee,datacell) worksheet.write('J'+str(row) , student.nationality,datacell) worksheet.write('K'+str(row) , student.id_no,datacell) worksheet.write('L'+str(row) , student.blood_type,datacell) worksheet.write('M'+str(row) , … -
Django admin action to copy queryset to another model
I have two models in a Django app. For ease, let's call them MainModel and DraftModel. These are similar (not same) models and former is more like a subset of the latter model, intentionally kept that way in order to keep the MainModel clean and verified for live. Once the admin manually verifies entries in DraftModel, is there a way we can have the admin select entries to be transitioned to MainModel, and click on an admin action like: def transition_selected(self, request, queryset): #do some updates queryset.update(status='TRANSITIONED') #get these entries duplicated to MainModel #WHAT SHOULD BE THE LOGIC HERE? transition_selected.short_description = "Transition selected into MainModel" -
Django - check cookies's "SameSite" attribute
In my Django application, I want to check if a specific cookies has "SameSite=None" or not. I'm using this code to read the value of the cookies, cookiesid = request.COOKIES["cookiesid"] However, I don't know how to check "SameSite" attribute, seems there is no method to check it by request.COOKIES[""] How can I check it? I'm using Python 3.6.9 and Django 3.1 -
My django_email_verification app is not working on my linux server
So I tested the code out on a localhost and it worked perfectly fine and I even received emails to verify accounts. Now when I git pulled and pushed to the server it keeps giving me a error every time I try to delete a user account or I do not get an email verification when I signup. I've checked my pip and the same libs are install but for some reason the linux server is giving me this error. How do I fix this? If there is any other code or errors you need please let me know and I will show you. -
DRF custom check_permission not being called
I'm trying to add a custom permission to a view which extends a generic DetailView: from django.views.generic import DetailView from rest_framework.permissions import BasePermission class MyCustomPermission(BasePermission): def has_permission(self, request, view): return False class MyView(SomeMixin, DetailView): model = MyObject template_name = "my_template.html" permission_classes = [MyCustomPermission] def get_object(self): return MyObject.objects.get(id=123) This should always fail, but it doesn't. I can also put a breakpoint in there (e.g. import pudb; pudb.set_trace()) but that won't ever get hit either. I know that has_object_permission(...) needs to be explicitely called, but I thought has_permission(...) got called when the view first got called. -
How to generate a drill down data from highcharts table?
I am new to front end development and using django to build a dashboard. I am leveraging high charts library for data visualization. I want to create a click event table with drill down data of point triggered. I want to send the click point details back to my views and trigger the view function (with view points as variables) to generate the table in a new page. Please suggest what functionalities can i use to achieve this? Is there any other way to achieve this? Eg. If user clicks on first bar, he should be directed to a new webpage which will have detailed tabular data fetched from database of Q1 2019. Check the jsfiddle example: https://jsfiddle.net/VM001/90jpvdw3/2/ point:{ events:{ click: function () { location.href ="clickTable"; alert('Category:'+this.category+',values:'+this.y) alert(this.options.name) } } } -
get return the blank value of src width height in iframe
**views.py** def add(request): report_list = {} if request.method == "POST": src =request.POST['src'] width=request.POST['width'] height=request.POST['height'] name=request.POST['name'] #context = {'report_list': report_list} report_list={'src':src, 'width':width, 'height':height, 'name':name} return render(request, 'report_one.html', report_list) else: src=request.GET.get('src', '') width=request.GET.get('width','') height=request.GET.get('height','') name=request.GET.get('name', '') #report_list={'src':src, 'width':width, 'height':height, 'name':name} #report_list={'src':request.POST['src'], 'width':request.POST['width'], 'height':request.POST['height'], 'name':request.POST['name']} return render(request, 'report_two.html', report_list ) if part getting the value of src, width ,name of report, and height from the user and then created report name should shown in the dropdown. When user click on the report name the created report will display on the screen and i think this part is handle by else ...but the problem is that i got the blank page else part giving blank value of iframe src, width,height -
Django Admin not working on my custom user model and i can't even update users
here is my custom user model class User(AbstractUser): friends = models.ManyToManyField('User', blank=True) bio = models.CharField( max_length=400, default='I love this website!', blank=True, null=True,) avatar = models.ImageField( upload_to='profile_images', default='profile_images/DefaultUserImage.jpg',) is_online = models.BooleanField(default=False) # PRIVACY show_email = models.BooleanField(default=False) who_see_avatar_choices = [ ('none', 'No One'), ('friends', 'Friends only *Beta*'), ('everyone', 'Every One'), ] ... when i went to django admin i didn't find my new fields, so i had to cancel The default django user admin (WHICH WILL CAUSE A LOT OF PROBLEMS LATER) here is my admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model as user_model User = user_model() admin.site.register(User) I didn't face any issues when I was on my local machine, but when I went to production I found out that I can't even update users nor see their passwords, their hashed password is turned into bunch of dots......... I don't mind that, but Django does! whenever I save changes it tells me that the password can't be empty as shown in the image below If I were able to extend the Django default user model to include my new fields the problem would be fixed ( i guess ) and to make things even worse, in …