Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Start a Django Channels Worker within the same process
I have to set up a worker which handles some data after a certain event happens. I know I can start the worker with python manage.py runworker my_worker, but what I would need is to start the worker in the same process as the main Django app on a separate thread. Why do I need it in a separate thread and not in a separate process? Because the worker would perform a pretty light-weight job which would not overload the server's resources, and, moreover, the effort of making the set up for a new process in the production is not worth the gain in performance. In other words, I would prefer to keep it in the Django's process if possible. Why not perform the job synchronously? Because it is a separate logic that needs the possibility to be extended, and it is out of the main HTTP request-reply scope. It is a post-processing task which doesn't interfere with the main logic. I need to decouple this task from an infrastructural point-of-view, not only logical (e.g. with plain signals). Is there any possibility provided by Django Channels to run a worker in such a way? Would there be any downsides to … -
Effecient way to fetch related models count in Django ORM
I'm working on Django 1.10 and PostgreSQL9.6 I have two models in my project: Order and Customer. Also I'm using Django's auth.User to store login credentials. Here is a code snipped: from django.contrib.auth.models import User from django.db import models class Order(models.Model): created_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='created_orders') # ... other fields ... class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # ... other fields ... Now, I need to show a table of customers and show a number of orders created by each of them. The staight forward code is: for customer in Customer.objects.all(): print(customer.user.created_orders.count()) Now I need to avoid N+1 problem and make Django to fetch all data with constant number of queries. I've tried to write something like: query = Customer.objects.select_related('user').annotate( orders_count=Count('user.created_orders') ) But this gives me an error like Cannot resolve keyword 'user.created_orders' into field. Can you help me with this? -
How to set SECRET_KEY environment variable in the development platform of Saleor
I'm setting up a Saleor in my local machine. I need more instructions how and where to place environment variable for SECRET_KEY. I have installed the additional software needed to run Saleor, and completed steps 1-3 in the installation process. I am new to this platform. Please advise how to go about setting SECRET_KEY environment variable. The guide has no detailed process. Please help, thank you in advance! -
How to create a dropdown menu in django which is to be populated from database
Can anyone please provide me the minimal example for creating a drop down menu in django template whose values are to fetched from a database using orm. -
Is it possible to create an edit form using crispy form?
I've a form named "CarForm". I 've created a "Create Form" to create car record using crispy form. I would like to ask is it possible to display the detail and update the car record using the same form? Here is the code for CarForm: from .models import * from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, HTML, Row, Column from crispy_forms.bootstrap import PrependedAppendedText, PrependedText, FormActions from django.urls import reverse class CarForm(forms.ModelForm): note = forms.CharField(widget=forms.Textarea()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['note'].required = False self.fields['policy_num'].required = False self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_action = reverse('create') self.helper.layout = Layout( Row( Column('reg_num', css_class='form-group col-md-6 mb-0'), Column('make', css_class='form-group col-md-6 mb-0'), Column('year', css_class='form-group col-md-4 mb-0'), Column('color', css_class='form-group col-md-4 mb-0'), Column('cc', css_class='form-group col-md-4 mb-0'), Column('engine_num', css_class='form-group col-md-6 mb-0'), Column('chasis_num', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), 'note', Row( Column(PrependedAppendedText('price_buy', 'RM','.00'), css_class='form-group col-md-6 mb-0'), Column(PrependedAppendedText('price_sell','RM','.00'), css_class='form-group col-md-6 mb-0'), Column('policy_num', css_class='form-group col-md-12 mb-0'), Column('owner_name', css_class='form-group col-md-4 mb-0'), Column('owner_ic',css_class='form-group col-md-4 mb-0'), Column('owner_phone', css_class='form-group col-md-4 mb-0'), css_class='form-row' ), FormActions( Submit('submit', 'Create'), ) ) class Meta: model = Car exclude = ['date'] -
How to clear input formatting in ckeditor django?
Need to format all input data to the ckeditor rich field. Tried to do next in my config.js config.pasteAsPlainText = true; and config.forcePasteAsPlainText = true; but all my input text doesn't clear its formatting. I need to clear all styles, colors, etc. How I can implement this ? -
Hosting a Kerberos-enabled Python/Django Web Application on Windows Server
.. I am moving to Python/Django from .NET for my upcoming project. The application must be Kerberos enabled for SSO login and the credentials need to be further delegated to another server where my Oracle DB resides. I would like to find out the best way to setup my Kerberos in a Django app hosted on Apache2.4 on my Windows Server 2012. So far i have managed to deployed a bare Django app on an Apache web server on my Windows Server VM. I need to get the client web browser to negotiate with the Apache web server and achieve the handshake. I have also tried to look into mod_auth_kerb, however it seems that it is mainly compatible with Linux. Would appreciate if any experts can provide their expertise especially in the area of Kerberos auth with Django/Apache on Windows Server. Thanks a lot. -
Making stored function based confirmation / callback system work with multiple processes in django + nginx
Our callback system worked such that during a request where you needed more user input you would run the following: def view(req): # do checks, maybe get a variable. bar = req.bar() def doit(): foo = req.user do_the_things(foo, bar) req.confirm(doit, "Are you sure you want to do it") From this, the server would store the function object in a dictionary, with a UID as a key that would be send to the client, where a confirmation dialog would be shown. When OK is pressed another request is sent to another view which looks up the stored function object and runs it. This works in a single process deployment. However with nginx, if there's a process pool greater than 1, a different process gets the confirmation request, and thus doesn't have the stored function, and can no run. We've looked into ways to force nginx to use a certain process for certain requests, but haven't found a solution. We've also looked into multiprocessing libraries and celery, however there doesn't seem to be a way to send a predefined function into another process. Can anyone suggest a method that will allow us to store a function to run later when the request … -
How to add CSRF token to Angular 8 post request from Django 2.2
I have an application with Django backend and angular frontend. Now, these are connected with each other, I can get data from Django and show in Angular. As well Send a post request to Django. But the issue is with CSRF token in Django. I disable the CSRF middleware in Django and the request process completely, but I know this is insecure. Method to do a post request. loadQuestion(id): Observable<any> { const body = {'choice': 'teseted with post method'}; return this.http.post(this.baseUrl + id + '/vote', {headers: this.header, withCredentials: true, }); } I did some changes according to this link. HttpClientXsrfModule.withConfig({ cookieName: 'csrftoken', headerName: 'X-CSRFToken' }) but I get this error. app.module.ts:26 Uncaught TypeError: _angular_common_http__WEBPACK_IMPORTED_MODULE_3__.HttpClientXsrfModule.withConfig is not a function So I changed it based on this Link HttpClientXsrfModule.withOptions({ cookieName: 'csrftoken', headerName: 'X-CSRFToken' }) This is my Django function to return data, as I said when I disabled CSRF middleware is working fine So I should fix the CSRF issue and passing it with Angular request. def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=4) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return HttpResponse("You didn't select a choice.") else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect … -
Static files on password_reset_confirm in django project page do not load
I am trying to load static files in a django project. I make a system of registration, login and password change. In the case when I go to the pages of my project, static files are loaded. However, if I reset my password and later go to the password change page (http://127.0.0.1:8000/password_reset_confirm/MQ-set-password/) django does not load static files. I am using django 2.2.6, python 3.7.3. Project structure -project -core models.py forms.py views.py ... -settings settings.py urls.py ... -static ... -templates ... manage.py ... urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth.views import PasswordResetView, PasswordResetCompleteView, PasswordResetConfirmView from django.conf.urls import url from core import views urlpatterns = [ path('', views.home, name='home'), path('signup/', views.signup, name='signup'), path('login/', views.LoginView.as_view(), name="login"), path('password_change_form/', views.LoginView.as_view(), name='password_change_form'), path('password_change_confirm/', views.LoginView.as_view(), name='password_change_confirm'), path('password_reset/', PasswordResetView.as_view(), name='password_reset'), url(r'password_reset_confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset_done/', PasswordResetCompleteView.as_view(), name='password_reset_done'), path('secret/', views.secret_page, name='secret'), path('admin/', admin.site.urls) ] password_reset_confirm {% extends 'base.html' %} {% block content %} <h2>Set new password</h2> {% if validlink %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> {% else %} <p style="color:red;">Invalid token.</p> <p> <a href="{% url 'password_reset' %}">Request a new password reset token</a> </p> {% endif %} {% endblock %} -
How to get image url or download url of images in pages API where image is created by a streamfield?
In my wagtail application I have a streamfield that is used to upload an image using ImageChooserBlock along with a title and text. That means in the single streamfield I have a title, a text and an image upload inputs. I'm trying to get the image url in the rest framework's pages API (localhost:8000/api/v2/pages/[page-id]). But this pages api only gives the image id of the uploaded images as follows { "type": "avengers", "value": { "title": "Tony Stark", "avengers": [ { "image": 1, /******* this is the image id returned ********/ "title": "Iron Man", "text": "Iron man is now in framework" } ] }, "id": "2f27cb24" } If I access the images api(http://localhost:8000/api/v2/images/1/) I'm getting the download_url as follows { "id": 1, "meta": { "type": "wagtailimages.Image", "detail_url": "http://localhost/api/v2/images/1/", "tags": [], "download_url": "/media/original_images/avenger.jpeg" }, "title": "avenger.jpeg", "width": 400, "height": 400 } My question is how I can get the download_url or the image url in the pages API (localhost:8000/api/v2/pages/[page-id]) My streamfields blocks.py for the avengers block is as follows class AvengersBlock(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text="Add your title") Avengers = blocks.ListBlock( blocks.StructBlock( [ ("image", ImageChooserBlock(required=True)), ("title", blocks.CharBlock(required=True, max_length=40)), ("text", blocks.TextBlock(required=True, max_length=200)) ] ) ) class Meta: # noqa template = "streams/Avengers_block.html" icon = … -
How to limit the number of items in a ListBlock?
I want to limit the number of entries a ListBlock can have. I know this is possible in StreamField with max_num but I can't see a way to do the same for ListBlocks. We need to use ListBlocks as they are more user friendly for our users than StreamField. An example of the code: class TextQuestionBlock(blocks.StructBlock): question_text = ShortcodeRichTextBlock() correct_answer = blocks.CharBlock(label="Correct Answer", required=True) false_answer = blocks.ListBlock(blocks.CharBlock(label="False Answer(s)", required=True)) We want to limit the number of false answers a user can inout I want to limit the user tro 3 false answers. Currently they can add as many as they like. -
Hide Django's staticfiles from GitHub stats
To understand what I'm talking about, I call GitHub stat this line: I have my Django project on GitHub repository and, I use Heroku to deploy this project. To deploy my project to Heroku, I need first to run python manage.py collectstatic that will generate a lot of CSS and JS like on screenshot above. So, I want to hide this folder not ignore, because Heroku needs it to work properly. -
Testing non-abstract method of an abstract class in python
I have an issue similar to the one mentioned here. However, I believe that my classes slightly differ. Here is what i have: A.py: from [...] import B class A(ABC): def __init__(self): self.b = B() def get_data(self): for-loop: x = self.b.methodA(x) @abstractmethod def update(self): pass B.py: class B: def methodA(self, x): # Do something here I am trying to test class A's get_data() without using any of its subclass(es). In my test method, I am patching methodA() as I do not want to test the api call. In order for me to test a non abstract method in an abstract class without the instantiation of a subclass, i used the following code: abstract_concreter.py: def concreter(A): if "__abstractmethods__" not in A.__dict__: return A new_dict = A.__dict__.copy() for abstractmethod in A.__abstractmethods__: new_dict[abstractmethod] = lambda x, *args, **kwargs: (x, args, kwargs) return type('dummy_concrete_{}'.format(A.__name__), (A,), new_dict) My test method looks like this: @patch('<path>.A.B.methodA', spec=True) def test_get_data(self, mock_fn): concreter(A).get_data(self, x=123) print(mock_fn) # <MagicMock name='methodA' spec='function' id='74741552'> mock_fn.assert_called_with(123) Yet i get the following error: AssertionError: Expected call: methodA(123) Not called I am still pretty new to unittest and the whole patch/mocking usage, I believe I am missing something or I am not writing it in the … -
What's the best approach to have a second authentication in Django Rest Framework?
Well, I have a django application one single user account can have more than one profile. I made a custom authentication where users can log in with e-mail and password to get authenticated via Jason Web Token. After that, with this Jason Web Token (account related) they can request another extended JWT just sending the ID of the profile in the request. I made a custom middleware to get the token in every request and succesfully get the user and the profile and insert it to the request object to access the wanted data from any other point, for example views and permissions. What's the best way to get the second call asking for a password when I want to switch between profiles? (just same behaviour of the first request) In other words, What's the best approach to have a second authentication system for my profiles (only available when the account is authenticated? The options I'm considering so far: 1) A second custom authentication backend. 2) A pincode in the profiles model (barely secure) -
What is SilentPrint ahead of main url?
Currently I am not able to load my website page in firefox because of silentprint preceding ahead of main url. My website working perfectly in chrome browser but in firefox only I am getting error because of silentprint. .js file var manaulPrintURL = "SilentPrint:"+ printURL; $(this).attr('href', manaulPrintURL); document.getElementById(this.id).click(); After loading website in firefox my url become like "silentprint:http://192.168.1.192:8010/test/419/" & getting error saying as below screenshot. Why I am getting above kind of problem only when using firefox browser & what will be solution of it. Thanks. -
django runserver, skiping/caching? requests when multiple executed at the same time
When running django-admin runserver and executing multiple PATCH requests at the same time, I see logs for all but only one is executed when I debug. The problem disappeared when using django-admin runserver --nothreading. I am using Pycharm debugger, maybe because runserver is by default using multithreading, so when 2 requests come at the same time a second thread is created which is not seen/debugged by Pycharm. So thats why I cannot debug it but I see logs. But the second thing is that only one request is successful with PATCH update, I know django-admin runserver is not aim for production but is there any data race condition ? I have tried to use django.db.transaction.atomic but it didn't make any change ? My initial conclusion is that runserver is not thread save if we consider database updates, so if testing multiple updating requests --nothreading flag should be used. I would appreciate any help/explanation here. Best, Igor P.S. I haven;t any code as I think it doesn't help here in any way: -
how to load css file in html file already extends another html file (base.html) in django
I'm new to django, so i get difficulty in dealing with django template in relation to adding css file into django template.My code is as follows: base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static 'portfolio/main.css' %}"> {% if title%} <title>Django Portfolio - {{title}}</title> {% else %} <title>Django Portfolio</title> {% endif %} </head> <body> <div class="topnav"> <a class="active" href="{% url 'portfolio-home' %}">Home</a> <a href="{% url 'portfolio-page' %}">Portfolio</a> <a href="{% url 'portfolio-about' %}">About</a> <a href="#blog">Blog</a> <a href="#account">Account</a> </div> <div class="container"> {% block content %} {% endblock content %} </div> </body> </html> This is my base.html file in which all my other html files inherit it.It works perfectly fine.Note:-I create the static file inside django app and put two static files; main.css and home.css for now. But i want to design homepage, and i av done this with the file known as home.html and use the home.css in static file.My code is as follows: home.html {% extends 'portfolio/base.html' %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href=" {% static 'portfolio/home.css' %}" /> <h1>My homepage</h1> {% endblock content %} The problem is, the line <link … -
create Field with specific persimmons in django
i want to add a field in my module to give the user some persimmons like is_superuser field but with customize persimmons how can i do this ? class CustomUser(AbstractUser): username = models.CharField(max_length=100,unique=True) email = models.EmailField(_('email address'), unique=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics ') date_joined = models.DateTimeField(_('date joined'),default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = CustomUserManager() -
Django User model: When using set_password, it seems model is being saved before pass validation
Sometimes i want to set the password programitically. So i try the following https://docs.djangoproject.com/en/2.2/topics/auth/default/#changing-passwords You can also change a password programmatically, using set_password(): >>> from django.contrib.auth.models import User >>> u = User.objects.get(username='john') >>> u.set_password('new pass') >>> u.save() I wanted to see how things are implemented in save() when we run >>> u.save() Bsically I am trying to undestand the save() method used in AbstractBaseUser # ./.venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py class AbstractBaseUser(models.Model): password = models.CharField(_('password'), max_length=128) ........ # Stores the raw password if set_password() is called so that it can # be passed to password_changed() after the model is saved. _password = None def save(self, *args, **kwargs): super().save(*args, **kwargs) if self._password is not None: password_validation.password_changed(self._password, self) self._password = None ........ def set_password(self, raw_password): self.password = make_password(raw_password) self._password = raw_password Here in def save(self, *args, **kwargs): super().save(*args, **kwargs) will save the password set by set_password before the next lines password_validation.password_changed which validate the password So what is the point in saving the password first and then checking. Because its gone into database. -
converting html to pdf using pisa
I am trying to generate a PDF using an already existing DJANGO HTML template. I am passing context data dynamically into the template then trying to convert it to HTML. I however keep on running into this File "C:\Users\EliteBook\Desktop\Virtual_Environment\app\lib\site-packages\reportlab\platypus\tables.py", line 265, in init raise ValueError("%s data error - %d rows in data but %d in row heights" % (self.identity(),nrows, len(rowHeights))) ValueError: with cell(0,0) containing ' size=x' data error - 16 rows in data but 15 in row heights when this line of code is executed... pdf = pisa.pisaDocument(BytesIO(html.encode("cp1252", 'ignore')), result) I have looked into PISA and REPORTLAB forums but do not seem to find a suitable solution. Below is the code that attempts to generate the PDF def make_pdf(student): entry = Transaction.objects.filter(student=student) credits = entry.filter(t_type='C') debits = entry.filter(t_type='D') c_count = entry.filter(t_type='C').count() d_count = entry.filter(t_type='D').count() e_count = entry.count() name = student.name context = { 'entries':entry, 'student':student, 'credits' : credits, 'debits':debits, 'c_count': c_count, 'd_count': d_count, 'e_count': e_count, 'name':name } return render_to_pdf('payment/statement.html', context) The return to render is defined in different file as thus: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template 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 … -
I want to use django-hitcount to count hits on my Class based view
I want to use django-hitcount to count the hits to my Class based views. I was following this documentation https://django-hitcount.readthedocs.io/en/latest/ and it's not clear to me how I could achieve that. I have gone as far as using the HitCountMixin like so class HomeView(TemplateView, HitCountMixin): template_name = 'home/index.html' def get(self, request): sections = Section.objects.all() return render(request, self.template_name, {'sections': sections }) I have gone through every installation step, but the hits are not appearing on the admin interface. -
How to pass a model to a base.html that all templates extend from base.html
I have a Django project which I have a base.html that all templates inheritance from that. Then I include a category.html file in base.html which is just my navigation bar. So I have a model named Category and I want to pass this model to category.html to show my categories. I don't know how to do that? base.html: <!DOCTYPE html> {% load static %} <html lang="en" style="height: 100%;"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}{% endblock %}</title> <!-- Google Fonts --> {% comment %} <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- Bootstrap core CSS --> {% endcomment %} <link href="{% static 'fontawesome/css/all.css' %}" rel="stylesheet"> <!--load all styles --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Material Design Bootstrap --> <link href="{% static 'css/mdb.min.css' %}" rel="stylesheet"> <!-- Your custom styles (optional) --> <link href="{% static 'css/style.min.css' %}" rel="stylesheet"> <!-- Mega menu style --> <link href="{% static 'css/bs4megamenu.css' %}" rel="stylesheet"> {% block extra_head %} {% endblock %} {% block slideshow %} {% endblock slideshow %} </head> <body> <!-- Category Navbar --> {% include 'category_navbar.html' %} <!-- Category Navbar --> <!-- Body Content --> {% block content %}{% endblock %} <!-- Body Content --> <!-- Footer and scripts--> … -
How to set logout url in django-registration?
Log out works okay, but I can't set redirect logout url using django-registration. In html: <h3> <a style="color:white" href="{%url 'logout' %}">"Logout"</a></h3> In settings.py: LOGOUT_REDIRECT_URL = "accounts/logout" I can access login page using accounts/login in browser, but it doesn't work for accounts/logout(Page not found.,but this page is in registration folder). -
'UserUpdateForm' object has no attribute 'field'
Error during template rendering In template C:\Users\jaimin patel\PycharmProjects\WEBPROJECT\venv\lib\site-packages\crispy_forms\templates\bootstrap4\field.html, error at line 6 'UserUpdateForm' object has no attribute 'field' from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile 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']