Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create object by using normal editor?
in the beginning i want to apologize for my poor english I want to create/add to datbase an object and the problem is that i want to do this in editor in my IDE. for example: class Word(models.Model): text=models.CharField(max_length=20) num=models.IntegerField(default=1) author=models.CharField(max_length=30) and when i try to create(by using Word.objects.create(text="hello",author="john") an object in file e.g <models.py> Problem is that in my database object is double Do you have any ideas to solve this problem? (i know that i can add object to database in interactive terminal) -
Empty Reply from Openshift Origin Hosted Django Web Service when accessed from Outside of Openshift Cluster
I followed the instructions here to set up an OpenShift Origin deployment of a Django project I'm working on. Everything seems to be working. There is a Pod running a service with a route set up and the service is exposed. However, when I browse to the website, I get an error that the connection was reset. Using curl: curl http://my-openshift-website.com results in curl: (52) Empty reply from server Besides, I witness the following phenomena: I know the code that serves the index web page runs when I access it from my browser (or using curl) because when I add code to create an empty file when the '/' page is requested, I see in the pod's terminal that the file is indeed created. When I try to do the same curl command from the pod terminal (i.e. from within the cluster), everything works and I get the web page. The pod's log files don't register anything when I try to access the service from the web browser but do register access when I do so from the pod terminal. -
How to retrieve data from post request in Django?
I have the following post request: $('#table tbody').on( 'click', 'button', function () { var data = table.row( $(this).parents('tr') ).data(); console.log(data.fields.name) $.ajax({ url: "distribute/", type: "POST", data: {name:"data.fields.name"}, cache: false, processData: false, contentType: false, success: function(data) { }, error: function(XMLHttpRequest, textStatus, errorThrown) { } }); } ); This is my distribute method in views.py: def distribute(request): if(request.method == "POST"): print request return HttpResponse("") When I look at the output of print request I don't see the data that I sent at all. How can I access the data that I sent in the request? -
Assign friendly name to Django model field
Is there a way I can assign a friendly name to a database column in Django? I'm looking for something like this: class Person(models.Model): first_name = models.CharField(max_length=100, friendly_name='First Name') last_name = models.CharField(max_length=100, friendly_name='Last Name') In order to access in a manner similar to this: for f in Person._meta.get_fields(): print(f.friendly_name) Output: First Name Last Name I am using Django 2.1 and PostgreSQL 10. -
Django: Can we pass an argument "created" into the signal receiver function?If yes What is this argument used for?
I WAS FOLLOWING A TUTORIAL WHERE SOMEWHERE THE TUTOR USED CREATED ARGUMENT DIRECTLY WITHOUT EXPLAINING WHY? The arument created was passed and is used to specify if....else conditions -
Django : Page not found (404) Why...?
I'm a beginner Django. So I read the tutorials and following them. But. I see an Error page. 'What is the problem...?' (I installed the python 3.6.5 version) My error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: 1.polls/ 2.admin/ The empty path didn't match any of these. polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] polls/views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") And Finally!! mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] But run server says "Page not found !!, The empty path didn't match any of these!!!" So I need your help, plz help me....!! -
Django - how can I set default image for an ImageField model
I have an imagefield type for my model class Attendance(models.Model): face_image = models.ImageField() the question is if I have an image in static, how can i assign it to this imagefield ? if not it could be from a url the image, how can i assign to this imagefield For example this would be how I would create the object, what should be assigned to face_image_obj ? attendance_new = Attendance(face_image = face_image_obj) attendance_new.save() -
Thai Font in Django PDF
I generate pdf file by django but It's not work for Thai Font util.py from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None When I run , It's show ugly. Like This https://i.stack.imgur.com/e0OUg.png -
How can I set a Django GenericForeignKey pointing to multiple classes on ManyToManyField?
Still a newbie, I have to adapt a Django (v1.10) script. The original script uses a main class "initiative" which can have any number of "supporters". The adaptions I have to make include having another main class called "policy" along "initiative" (similar behaviours, different fields). I'm stuck with a ManyToManyField on "initiative" and "policy" which should point to Supporters where I'm trying to use a GenericRelation to support both main classes. I get the following error message: initproc.Supporter: (fields.E336) The model is used as an intermediate model by 'initproc.Initiative.supporters', but it does not have a foreign key to 'Initiative' or 'User'. initproc.Supporter: (fields.E336) The model is used as an intermediate model by 'initproc.Policy.supporters', but it does not have a foreign key to 'Policy' or 'User'. My models.py (removed everything irrelevant) BEFORE: # ------------------------------ Initiative ------------------------------------ class Initiative(models.Model): supporters = models.ManyToManyField(User, through="Supporter") # ------------------------------- Supporter -------------.---------------------- class Supporter(models.Model): class Meta: unique_together = (("user", "initiative"),) user = models.ForeignKey(User) initiative = models.ForeignKey(Initiative, related_name="supporting") and AFTER my modifications: # ------------------------------- Supporter ------------------------------------ class Supporter(models.Model): class Meta: unique_together = (("user", "target_type", "target_id"),) user = models.ForeignKey(User) target_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) target_id = models.IntegerField() target = GenericForeignKey('target_type', 'target_id') # -------------------------------- Policy -------------------------------------- class Policy(PolicyBase): supporters = models.ManyToManyField(User, … -
Django Admin: related_name Issues, AutoLogout and Hosting Doubts
This is the code that I have in my models.py. I'm trying to develop a small website using only the Django Admin. from django.db import models # Create your models here. from django.contrib.auth.models import User from django.db import models from django.core.mail import EmailMessage # Create your models here. class Project(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ('Completed', 'Completed') ) Project_Name = models.CharField(max_length=100) Project_Description = models.CharField(max_length=100) Admin_Name = models.CharField(max_length=100) Admin_Mail_ID = models.EmailField(max_length=50) Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Project_Manager_1_users') Project_Manager_1_Mail_ID = models.EmailField(max_length=50) Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Project_Manager_2_users') Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Technician_1_users') Technician_1_Mail_ID = models.EmailField(max_length=50) Technician_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Technician_2_users') Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Technician_3_users') Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Tester_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Tester_1_users') Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example@gmail.com') Additional_User_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Ad_1_users') Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True) Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Additional_User_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Ad_1_users') Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True) Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Additional_User_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='Ad_1_users') Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True) Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1) Created … -
Django Custom Login - Form is valid but no error
I currently try to figure out how to customize the Django user login to add e.g. simple-captcha, therefor i subclassed "AuthenticationForm" from django.contrib.auth.forms which first looks great but if i try to login i'm simply not able to. i already debugged the code but there is also no error to find at various breakpoints. custom login view: def login (request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.INFO, "You are now logged-In, welcome") return redirect(reverse('post_list')) else: print("hello error") form = LoginForm() args = {'form': form} return render(request, 'registration/login.html', args) else: form = LoginForm() args = {'form': form} return render(request, 'registration/login.html', args) login form of django.contrib.auth.forms subclassed (copied) to accounts/forms.py: class UsernameField(forms.CharField): def to_python(self, value): return unicodedata.normalize('NFKC', super().to_python(value)) class LoginForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive or blocked."), } def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data … -
Django: Serving SVGs
In my Django project, I have a JS library that also uses SVGs for icons. These files are in an S3 bucket - meaning not on my own domain. When the JS is initiated, it tries to load the SVG icons and that throws a browser error in Chrome: Unsafe attempt to load URL https://s3.amazonaws.com/<mydomain.com>/static/pixie/assets/icons/merged.svg from frame with URL <mydomain.com>/images/pixie/dcfcf90e-d4fa-4bde-bb6b-6cebe00e6d7a/. Domains, protocols and ports must match. Is there a way to serve these SVGs from my project directly? If the SVGs are served from my own domain, ex. <mydomain.com>/svgs/merged.svg, then I think the "unsafe attempt to load" error would be resolved. -
Django: Using Case and when separately for multiple new columns created by annotation
Can i use Django annotations to create extra columns first and then use Case and When to decide their values based on some conditions. Eg: SomeModel.objects.all() .annotate( extra_column_A , extra_column_B,....,extra_column_XYZ) .Case( When( Some_existing_column < 10, then extra_colum_A = somevalue1 * Some_existing_column extra_column_B = somevalue2 * Some_existing_column ... .. . extra_column_XYZ = somevalue3 * Some_existing_column ), When( Some_existing_column < 20, then extra_colum_A = somevalue * Some_existing_column extra_column_B = somevalue * Some_existing_column ... .. . extra_column_XYZ = somevalue * Some_existing_column ), ... When( Some_existing_column < 200, then extra_colum_A = somevalue * Some_existing_column extra_column_B = somevalue * Some_existing_column ... .. . extra_column_XYZ = somevalue * Some_existing_column ), default = False, output_field=IntegerField() ) Otherwise for each column i have to write Case and when , which is lot of repeating code. -
Django default CSS not getting applied
I am trying to build my first app in Django. I have done following: Installed Python 3.6, PIP, Django 2.1 Activity: Created a project Started web server using manage.py of a project Create a django app in the project folder Edited settings.py to include the app name (folder name) in INSTALLED_APPS list Edited models.py to create a class for my model 6) From CLI created the migrations files Applied the migrations Registered my model with django admin by modifying admin.py Create superuser from CLI Login to locahost:8000/admin At this stage I am able to login to admin but the CSS is not getting applied in the webpage. Admin Panel - Django I have tried on FF, Chrome, IE. I have checked that the CSS files in the web page source are accessible (able to download / view the CSS scripts). Admin Panel - CSS I also referred to the documentation Django 2.1 documentation for static file & the top two conditions are met for INSTALLED_APPS & STATIC_URL. Since I am not presenting any specific CSS of my own & these are all default files of Django I am not sure if I should be doing any other changes somewhere? -
Wagtail query - date range, type selection and limit
I am trying to make a site with this structure: Home page - Organisation (Page model) - Event (Page model) Now, on the Home page I want to display the events that will be from today, untill seven days ahead, or limited by 10 if there are many. I have given the events these two values: start = models.DateTimeField() end = models.DateTimeField() , and I would like to sort on start. My first attempt looks like this, but it is not working: def get_context(self, request): context = super().get_context(request) events = self.get_children().type(Event).filter(date__range=['2018-08-25', '2018-08-31']).live().order_by('start') context['events'] = events return context There should also be a limiter in there somewhere, so that it does not return more than 10. -
Django loop through a list and objects in the same time
I have encountered a problem when i wanted to display some information from my list and the some other information from my object. Here is what i have done so far. I have this class here : class Document(models.Model): title = models.CharField(max_length=100) description = models.TextField(help_text="some text for now") Here is my view def showDocuments(request, *args, **kwargs): documents = Document.objects.all() context = { "documents": documents, "files": [], # an empty list for now } # After writing some logic context["files"].append(item) return render(request, 'dashboard.html', context) and here is my html page: # i am stuck here ! {% if files %} <div class="container"> <div class="row"> {% for file in files%} <div class="col-sm-4 mt-4"> <div class="card"> <div class="card-header "> {{filename}} </div> <div class="card-body"> <h5 class="card-title">this is a text</h5> <p class="card-text">this is a text</p> <a href="http://127.0.0.1:8000/media/documents/{{filename}}/{{file}}" class="btn btn-success" download>Download</a> </div> </div> </div> {% endfor %} </div> </div> i want to show some real data instead of showing "here is some text" by using the Document Class i have shown above so i can use {{document.title}} and {{document.description}} but i can't find a way to do so any help will be appreciated -
Django - Using Subquery to annotate a Count
Please help me I've been stuck on this for way too long :( What I want to do: I have these two models: class Specialization(models.Model): name = models.CharField("name", max_length=64) class Doctor(models.Model): name = models.CharField("name", max_length=128) # ... specialization = models.ForeignKey(Specialization) I would like to annotate all specializations in a queryset with the number of doctors that have this specialization. My Solution so Far: I went through a loop and I made a simple: Doctor.objects.filter(specialization=spec).count() however this proved to be too slow and inefficient. The more I've read the more I realized that it would make sense to use a SubQuery here to filter the doctors for the OuterRef specialization. This is what I came up with: doctors = Doctor.objects.all().filter(specialization=OuterRef("id")) \ .values("specialization_id") \ .order_by() add_doctors_count = doctors.annotate(cnt=Count("specialization_id")).values("cnt")[:1] spec_qs_with_counts = Specialization.objects.all().annotate( num_applicable_doctors=Subquery(add_doctors_count, output_field=IntegerField()) ) The output I get is just 1 for every speciality. The code just annotates every doctor object with its specialization_id and then annotates the count within that group, meaning it will be 1. This doesn't make complete sense to me unfortunately. In my initial attempt I used an aggregate for the count, and while it works on its own it doesn't work as a SubQuery, I get this … -
How to remove certain fields when doing serialization to a Django model?
I have the following model in my Django app: class Policy(models.Model): class Meta: verbose_name_plural = "policies" name = models.CharField(max_length=45) last_update = models.DateTimeField() content = models.TextField() @classmethod def create(cls, name, last_update, content): policy = cls(name=name, last_update=last_update, content=content) return policy Now, I have a datatable, where I fill the rows using this function from views.py: def myModel_asJson(request): object_list = Policy.objects.all() #or any kind of queryset json = serializers.serialize('json', object_list) return HttpResponse(json, content_type='application/json') However, my data table doesn't contain content column. My question is - how can I omit the content field from my model when I do the serialization? Is there any other approach I can use to return JSON representation of my models without the content field? -
Should I use Django haystack? if not , are there any other ones?
I am going to implement search in my website and I am going to have use others apps for searching function. When I google for such apps haystack is the one that comes out. Do you recommend to use it? -
how can i make login required for an entire urlconf in django
I have the following code in root url conf path('dashboard/', include('frontend.urls')), so inorder to make a url login protected I have to go to the frontend->urls.py and add the following code (the login_required decorator) for each of the paths path('lists', login_required(EmailListView.as_view(),login_url='/login'), name="list"), which is quiet tedious, and we might forget as well. So my question is how can I enable login_required protection for a urlconf group? is there any way I can enable it from the root urlconf? like below? path('dashboard/', login_required(include('frontend.urls'))), #something like this? #for now I am not able to access any urls if I do this so that the entire set is protected !!, NB: I read this answer here Best way to make Django's login_required the default, still, this requires specification of urls in some other place, Django 2.1, Python 3.6 -
Python / Django generating PDF files using pdfkit
I'm trying to generate a PDF document from an .html file using pdfkit (https://micropyramid.com/blog/how-to-create-pdf-files-in-python-using-pdfkit/) in my Django web app. I'm getting a "HTTP 405 error" when I click the "Download as PDF" button in detail.html. Could someone please advise where I'm going wrong. views.py: from django.template.loader import get_template import pdfkit def pdf(request): if request.method == 'POST': ros = ResearchOutput.objects.all() template = get_template('detail.html') html = template.render({'ros': ros}) options = { 'page-size': 'Letter', 'encoding': "UTF-8", } pdf = pdfkit.from_string(html, False, options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="person.pdf"' return response detail.html: <form action="" method="post"> {% csrf_token %} <input type="submit" value="Download as PDF"> -
django - how to get the inbox of mail?
I already can send mail via django with this parameters EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.onlinemiveh.com' EMAIL_HOST_USER = 'info@onlinemiveh.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 How can I get the inbox? I tried with these in django mail box and all of these raise authentication failed error: imap+ssl://info%40onlinemiveh.com:password@smtp.onlinemiveh.com?archive=Archived imap://info%40onlinemiveh.com:password@smtp.onlinemiveh.com?archive=Archived pop3+ssl://info%40onlinemiveh.com:password@smtp.onlinemiveh.com?archive=Archived pop3://info%40onlinemiveh.com:password@smtp.onlinemiveh.com?archive=Archived -
Invalid block tag on line 5: 'static'. Did you forget to register or load this tag?
Hello there i am getting error in this line # < href="{% static 'css/style.css' %}" rel="style" /> location of my project is /Documents/Django_ptoject/helloworld/my_project/djnago_project/helloworld# ls manage.py my_app static setting.py of INSTALLED_APPS 'my_app', 'django.contrib.staticfiles', STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static"), ] STATIC_ROOT=os.path.join(os.path.dirname(BASE_DIR),"static") enter image description here urls.py file from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) and this is my style.css h1 { color:#FCA205; } thank you -
Error during GeoDjango tutorial documentaion
I am following through the GeoDjango tutorial from the official documentation. I have installed the required geospatial libraries, installed and enabled spatial functionality by extending the PostgreSQL via postgis. Downloaded the world borders data, and have unzipped the data. Created a GeoDjango model (WorldBorder) in the world app. Created the load.py inside the world app, as instructed in the documentation. But when I try to load module and call the run routine, I am getting an error: Failed to save the feature (id: 141) into the model with the keyword arguments: Traceback (most recent call last): File "/home/vagrant/.virtualenvs/testenv/lib/python3.6/site-packages/django/contrib/gis/utils/layermapping.py", line 577, in _save stream.write('%s: %s\n' % ('Updated' if is_update else 'Saved', m)) UnicodeEncodeError: 'ascii' codec can't encode characters in position 7-8: ordinal not in range(128) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "/vagrant/geo_project/world/load.py", line 30, in run lm.save(strict=True, verbose=verbose) File "/home/vagrant/.virtualenvs/testenv/lib/python3.6/site-packages/django/contrib/gis/utils/layermapping.py", line 627, in save _save() File "/usr/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/home/vagrant/.virtualenvs/testenv/lib/python3.6/site-packages/django/contrib/gis/utils/layermapping.py", line 586, in _save stream.write('%s\n' % kwargs) UnicodeEncodeError: 'ascii' codec can't encode character '\xc3' in position 62: ordinal not in range(128) I cannot figure out where I am wrong. Could … -
Fetch object that have existing many-2-many related objects in django
Posts may be assigned to one or more categories, and categories may contain multiple posts. Here are my models: class Category(models.Model): name = models.CharField(max_length=31) class Post(models.Model): title = models.CharField(max_length=127) content = models.TextField() category = models.ManyToManyField(Category) I don't know how to fetch all categories that have at least one post assigned to them without query all of them and checking in loop.