Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What are good choices for setting up asynchronous django?
I need to set up a system where actions taken by client A can trigger events for client B. Our project is written with a python server and javascript/react client. Previously, we used Flask and Socketio to get the asynchronous configuration. However, we have recently switched flask out for django. I've googled around a bit, but most of what I've found is three or more years old: asynchronous web development with django. too much technologies Can I use Socket.IO with Django? -
Git subtree fails to push to Heroku
I tried to push my Django app to Heroku git subtree push --prefix TEST heroku master It gives me something like this 'TEST' does not exist; use 'git subtree add' If I use git subtree add, it gives me Working tree has modifications. Cannot add. I am not sure what is the problem and how to fix it. Has Anyone encountered the same problem before? -
Could not login using created normal user in Django website
I use python 3.7 in widows 7. I have created a Django website. I used superuser to create some normal user. But the normal user account could not login the website, nothing happens when I click login after entering into the normal user details . view.py: @login_required def index(request): if request.user.is_hop(): return redirect(reverse('bms:inbox')) ccs = ContentChecklist.objects.prefetch_related( Prefetch('material_set', queryset=Material.objects.select_related('book').select_related('semester_course__course'))).all() context = {'object_list': ccs, 'course_count': CourseInfo.objects.all().count(), 'material_count': Material.objects.all().count(), 'book_count': Title.objects.all().count(), 'publisher_count': Publisher.objects.all().count()} return render(request, 'bms/index.html', context=context) -
AWS S3 alternatives for heroku deployment for a Django project
I tried signing up for AWS but unfortunately couldn't verify my payment method,and in my country I have to take some steps first to get my card to work with international payments before I can use it,and due to COVID 19 outbreak,I can't carry out those steps yet,so I wish to know if there's an alternative (probably a Google alternative since it's probably going to be free),I would also appreciate if you can give detailed steps on how to use it for Django file upload storage. -
geocoder.ip('me') work locally but not on heroku
I am using Django and need to get user' current location, so I use geocoder.ip('me'). It works fine locally, but after I deploy it on heroku, it seems not working. Is that because the ip address or something else? How could I fix it? Or is there any way else that is easier for me to access user current location in views.py? Thank you. -
How to build CASCADE on_delete warning in Django DeleteView?
I'd like to create a view (that inherits DeleteView) that warns the user if the record they're about to delete will cascade-delete other records. I would also like to get the queryset of those records so I can display them. I think most of the work can be done overwriting the get_context_data method. So far this is what I tried: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) current_object_model = apps.get_model(app_label=self.kwargs['app_name'], model_name = self.kwargs['model_name']) for field in current_object_model._meta.fields: # I also tried # for field in current_object._meta.get_fields(include_hidden=True): if field.get_internal_type() == 'ForeignKey': print(field) print(type(field)) return context Unfortunately the related model whose object's would be deleted isn't actually one of current_object_model's fields and therefore not listed here. I might be able to answer this by iterating over every single model and checking to see if current_object_model is related to any/each them. But I was wondering if there are any built-in methods that can get me closer to this quicker and/or more efficiently. -
How to place two smaller buttons beneath a bigger button - html, css
I have been trying to make a website from scratch using the django framework in Python. I am trying to make a split screen landing page and on each side, I want three buttons: Read More, Sign up, Log in. I want the "sign up" button and "log in" button to be underneath the bigger "read more" button, but I have been unsuccessful for many hours. I am very much a beginner in web development so please forgive me for any silly errors. HTML code for buttons "Read more" and "Sign up"(so far): <div class="container"> <div class="split left d-flex justify-content-center align-items-center"> <h1> The Business </h1> <a href="#" class="button"> Read More </a> <div class="Buttons"> <div class="SignUp"> <a href="#" class="button"> Sign up </a> </div> </div> </div> <div class="split right d-flex justify-content-center align-items-center"> <h1> The Artist </h1> <a href="#" class="button"> Read More</a> </div> </div> CSS code for button: .button { display: block; position: relative; left: 50%; top: 40%; height: 2.5rem; padding-top: 1.3rem; width: 15rem; text-align: center; color: #fff; border: #fff solid 0.2rem; font-size: 1rem; font-weight: bold; text-transform: uppercase; text-decoration: none; transform: translateX(-50%); } This is the way the sign up and read more buttons are currently showing on one side of my split … -
Django | Could not parse the remainder: '{{y' error (Django HTML Template Language)
So essentially I'm creating a N x N grid out of the table format in HTML and Python Django Template Language. Lets assume grid size is 3, and val_list = [ [2,1,2],[1,0,1],[2,1,2] ] <br> <table> {% for y in g_sizelist %} <tr name="{{y}}"> {% for x in g_sizelist %} <td name="{{x}}_{{y}}">{{val_list.0.0 }}</td> {% endfor %} </tr> {% endfor %} </table> With this code I get the output: 222 222 222 So... with numbers it seems to work.. but when I try this where I replace val_list.0.0 with y and x values: <table> <br> {% for y in g_sizelist %} <tr name="{{y}}"> {% for x in g_sizelist %} <td name="{{x}}_{{y}}">{{val_list.{{y}}.{{x}} }}</td> {% endfor %} </tr> {% endfor %} </table> I get this error: Could not parse the remainder: '{{y' from 'val_list.{{y' I've tried to find the format for it but int({{y}}).int({{x}}) would work if they where strings, still didn't work.. Does anyone know the proper documentation for it? -
django + celery + redis : windows os for development: send email alerts
I am developing a django project on windos 10 os , where i have to send email alerts. I am thinking to use celery for that. But now celery page mentions that its not supported on windows. Now the only option left is to use subprocess.Popen() Can some one guide me whats the best way. -
Django: Unable to migrate a model change using migration.apply() : doesnt work; nor schema_editor.create_model() : Error Table exists
My migrations are not applied when done programmatically. I am Unable to migrate a model change using migration.apply() : doesnt work; nor schema_editor.create_model() : Error Table exists The model definitions have been defined using: type("SampleModel", (models.Model,), attrs) I have a new change for model and the definition of model to migrate looks like this: {'__module__': 'testmodule', 'app_label': 'testmodule', '__unicode__': <function ModelScript.model_create_config.<locals>.<lambda> at 0x000001B3CDF4FA60>, '__bases__': (<class 'django.db.models.base.Model'>,), '__doc__': 'SampleModel(id)', '_meta': <Options for SampleModel>, 'DoesNotExist': <class 'testmodule.SampleModel.DoesNotExist'>, 'MultipleObjectsReturned': <class 'testmodule.SampleModel.MultipleObjectsReturned'>, 'id': <django.db.models.query_utils.DeferredAttribute object at 0x000001B3CDFD9970>, 'objects': <django.db.models.manager.ManagerDescriptor object at 0x000001B3CDFD99A0>} My code looks like this from django.db.migrations.state import ProjectState from django.db.migrations.migration import Migration from django.db.migrations.state import ModelState from django.db.migrations import operations # Model state printed from DB looks like this # This how the table was Created. The table is created before the change is required # <CreateModel name='SampleModel', fields=[('id', <django.db.models.fields.AutoField>)]> model_state = ModelState.from_model(model_definition) # Create a fake migration with the CreateModel operation cm = operations.CreateModel(name=model_state.name, fields=model_state.fields) migration = Migration("fake_migration", model_state.app_label) migration.operations.append(cm) state = ProjectState() with db_conn.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor: # Following does not work - ERROR thrown saying 'Table exists' and the DB user is root mysql user # schema_editor.create_model(model_definition) # Following runs but the migration is not applied # Probably … -
How to share a serial connection handler across Django?
I'm currently developing a project where I'm controlling a device through a serial connection created with pyserial. I'm using Django Rest Framework to expose this control through a REST API. Is there a way for me to establish the serial connection only once during Django's startup and share it across my views/endpoints as it happens, I believe, with the database connection? -
Redirect back to list view with page number
I have a function to withdrow some recored I can click the withdrow from the list page and the details..So,I want to check first what is the current path inorder to getback to it after showing message. I have used the next method to handle that it is working fine for the details page but for the list page it is not working if the url contain ex.?page=2 it will show Page not found 404 template <a href="{% url 'records:withdrow-record' pk=record.id %}?next={{ request.path }}">withdrow record </a> view.py def withdrowRecord(request, pk): if condition: do stuff... else: messages.error(request, _('cannot withdrow a recored without permission')) url_name = resolve(request.GET.get("next")).url_name if url_name == 'record-details': return HttpResponseRedirect(reverse('records:record-details', args=(pk,))) elif url_name == 'record-list': return HttpResponseRedirect(request.GET.get("next")) I have tried to change request.path in the template to ?next={{ request.get_full_path }} and it is not working same error -
In Django polling application, how can I allow users to select and vote multiple options in a multiple choice poll
So I followed a video by Traversy Media, 'Python Django Crash Course', which is basically the Django basic application tutorial on creating a polling application. It works well but I wanted the user to be able to select more than one option to vote on. Can that be done with the way the code is setup right now? The models are from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text The views are from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import Question, Choice # Get questions and display them def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) # Show specific question and choices def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', { 'question': question }) # Get question and display results def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', { 'question': question }) # Vote for a question choice def vote(request, question_id): # print(request.POST['choice']) question = get_object_or_404(Question, … -
Replace html content by axios within view, then load it's javascript dependancy
I have bootstrap nav contents generated by a vue instance. When I navigate to an other item, I want to load HTML content from an API, and place it in my page. However, this content requires some external javascript to work on document ready. How to make my instance load external javascript after vue component is ready ? Vue.js script <script type="text/javascript"> // Map services with urls to get html by ajax (axios) and put the content into the correct tag let service_list = []; service_list.push({ nav_id: 'nav-cal_fr-tab', content_id: 'nav-cal_fr', title: 'Calibration feu rouge', service_url: '{% url 'device/cal_fr' object.pk %}', service_scripts_url: ['https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js', '{% static 'device/js/cal_fr.js' %}'], method: 'GET' }); let services_section = new Vue({ delimiters: ['[[', ']]'], // /!\ HIGHLY IMPORTANT : avoid conflicts with jinja2 el: '#services', data: { services: service_list, }, created() { // Declare a request interceptor to show modal before requesting the service content axios.interceptors.request.use(config => { // console.log('Request was sent on ', config.Response was receivedurl); const service = this.services.find(x => x.service_url === config.url); $('#loading-modal').modal('show'); $('#loading-modal #modal-loading-text').html('<strong>Chargement du service:</strong> ' + service.title) return config; }, error => { // handle the error return Promise.reject(error); }); // Declare a response interceptor to hide modal after service response … -
django: get total of modelformset fields values
I am coming accross an issue that I can't find a solution for nowhere. I have a modelformset with the following fields as such: form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount', 'customer_name')) ...more stuff in this view... request.session['sale'] = formset.cleaned_data Now I access the data inside of another template doing this: def generate_pdf_assembly(request): data = request.session['sale'] my_company = MyCompany.objects.get(id = 1) context = {'data' : data, 'my_company' : my_company} print(context) return render(request, 'pdf/invoice_generator_assembly.html', context) what I want is sum up the NetAmount values of the modelformset inside of generate_pdf_assembly but cannot find a way to do so manipulating the data variable. How can this done inside of a Django view? -
How to authenticate the entire frontend with DRF without user interaction
I have built a blog using Angular and Django, DRF. I have set permission_classes to IsAuthenticated however I am confused about how to authenticate my frontend with the backend. I have setup CORS, and I most certainly don't want anyone to call upon an endponit. sample_views.py class BlogModelViewSet(ModelViewSet): queryset = Blog.objects.all().order_by('-id') serializer_class = BlogModelSerializer permission_classes = [IsAuthenticated, ] sample_component.py export class BlogComponent implements OnInit { constructor(private allBlogService: BlogsService) {} allBlogs: any; ngOnInit(): void { this.allBlogService.getAllBlogs().subscribe((response) => { this.allBlogs = response; console.log(this.allBlogs.results[0].slug); }); } } all_blog_service.py export class BlogsService { constructor(private http: HttpClient) {} getAllBlogs(): Observable<any> { return this.http.get<any>(environment.API_PREFIX + 'blog'); } } What I thought of was create a service that will get the credentials to authenticate with DRF, from the environment variables, and then use that service in app.component.ts to obtain a JWT and then use that JWT to pass in the Authorization header. But the concern with this method is that the JWT token can be sniffed and misused. What are your thoughts? -
Ignore form field on condition
I have this form: class TableCheckInForm(forms.Form): table_id = forms.IntegerField(label= "Table No.", min_value =0, required=False, disabled=True, widget=forms.HiddenInput()) guest_count = forms.IntegerField(label= "No. of Guests", min_value =0) In my template, there are two submit buttons that send a POST on this form: <div class="checkin-modal-body"> <div id="table-checkin-form"> <form class="checkin-form-container" method="post"> {{ checkin_form.as_p }} {% csrf_token %} <button type="submit" class="button-table-checkin" name="confirm-checkin">Check In</button> <button type="submit" class="button-table-checkin-cancel" name="cancel-checkin">Cancel</button> </form> </div> </div> In my view: def table_checkin_view(request, table_pk): if request.method == 'POST': checkin_form=TableCheckInForm(request.POST) if 'confirm-checkin' in request.POST: if checkin_form.is_valid(): cd = checkin_form.cleaned_data table.set_availability(False) return redirect(reverse('menu:menu_category_view', args=[table_pk])) else: return redirect(reverse('table:table_view')) else: checkin_form = TableCheckInForm(initial={'table_id': table_pk}) return render(request, ...) When the button Check In is clicked, the form requires the field (guest_count) to be filled. However, if the user click Cancel, there is no need for this field to be populated. Yet, in order to redirect to table:table_view, it requires the user to populate guest_count. How do I make it ignore this field in the Cancel situation? Thanks. -
Post method in forloop is not working properly
Here when i click on like button it toggle only the first post which is on the top, But when i click on the like button of other posts, that shows nothing ,no post method, and perform no function, but it is completely working fine for the first post of queryset as i said. {% csrf_token %} {% for post in object_list.all %} <div class="cardbox"> <div class="cardbox-heading"> <!-- START dropdown--> <div class="dropdown pull-right"> <button class="btn btn-secondary btn-flat btn-flat-icon" type="button" data-toggle="dropdown" aria-expanded="false"> <em class="fa fa-ellipsis-h"></em> </button> <div class="dropdown-menu dropdown-scale dropdown-menu-right" role="menu" style="position: absolute; transform: translate3d(-136px, 28px, 0px); top: 0px; left: 0px; will-change: transform;"> <a class="dropdown-item" href="#">Hide post</a> <a class="dropdown-item" href="#">Stop following</a> <a class="dropdown-item" href="#">Report</a> </div> </div><!--/ dropdown --> <!-- END dropdown--> <div class="media m-0"> <div class="d-flex mr-3"> <a href="#"><img class="img-responsive img-circle" src="{{post.username.avatar.url}}" alt="User"></a> </div> <div class="media-body"> <p class="m-0">{{post.username}}</p> <small><span>{{post.create_date|timesince}}</span></small> </div> </div><!--/ media --> </div><!--/ cardbox-heading --> <div class="cardbox-item"> <a href="{% url 'posts:post_detail_final' pk=post.pk slug=post.slug %}" data-toggle="modal"> <img class="img-responsive" src="{{post.image_data.url}}" alt="MaterialImg"> </a> </div><!--/ cardbox-item --> <div class="cardbox-base"> <ul> {% for likes in post.likes.all %} <li ><a href="{% url 'profiles:detail' username=likes.username %}"><img src="{{likes.userprofile.avatar.url}}" class="img-responsive img-circle" alt="User"></a></li> {% endfor %} </ul> </div><!--/ cardbox-base --> <div class="cardbox-like"> <ul> <li> <span class="" id="like_count">{{post.likes.count}}</span> <button class="btn btn-link … -
Django allauth customized templates not working
I am using Django allauth for authentication, and I have customized templates(with styles), in the templates/account directory. When I initially did this, everything was working fine, but after a while, I tried testing it out again, and I found out that only the customized templates for login, and signup are working: the others are using the default template. I don't even know what the problem is. Could it be because I recently installed django-admin-honeypot, or django-cleanup? Take a look at my settings.py: from pathlib import Path import dj_database_url from decouple import config, Csv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ # Default 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # 3rd party 'crispy_forms', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', 'django_cleanup.apps.CleanupConfig', 'admin_honeypot', 'allauth', 'allauth.account', 'allauth.socialaccount', # Local 'pages', 'users', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djangoprojecttest_config.urls' TEMPLATES = [ … -
Django form: Custom filter 'addclass' not working
I tried to use the second answer to this question: CSS styling in Django forms I am trying to add class to inputs so I can style my form. Working with a custom filter seemed reasonable to me. The problem is, that when I run the server I get the error: addclass requires 2 arguments, 1 provided This is my code: myfilters.py: from django import template register = template.Library() @register.filter(name='addclass') def addclass(value, arg): return value.as_widget(attrs={'class': arg}) contact.html: <form method="post"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.nome_completo.errors }} {{ form.nome_completo.label_tag }} {{ form.nome_completo | addclass: 'form_nome-completo' }} <span class="helptext">{{ form.nome_completo.help_text }}</span> </div> </form> Thanks! -
Cannot render views in template in Django
I cannot render my views in templates. I think I've tried everything. everything works except data rendering on template. My model.py: from django.db import models class Driver(models.Model): name = models.CharField(max_length=150) surname = models.CharField(max_length=150, default='') def __str__(self): return self.name My views.py: from django.shortcuts import render from zoo.models import Driver def MyView(request): drivers = Driver.objects.all() return render("zoo/base.html", {"drivers": drivers}) My template: {% load staticfiles %} {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Example</title> {% render_bundle 'app' 'css' %} </head> <body> {{ drivers }} {{ drivers.name }} {% for driver in drivers %} {{driver.name}} </body> </html> My database got 315 drivers, contains names and surnames for drivers. Project structure: Project app setting.py __init__.py ... zoo templates base.html __init__.py models.py views.py ... -
data doesn't appear in my html page when i add new record - Django
when i add new record from admin panel it should appear in html page , but it doesn't do that how to fix it models.py : class BestArticals(models.Model): name = models.CharField(max_length=240) url = models.URLField(default="",max_length=240) image = models.ImageField(upload_to='images/',null=True, blank=True) def get_image(self): if self.image and hasattr(self.image, 'url'): return self.image.url else: return '/path/to/default/image' def __str__(self): return self.name views.py : from .models import BestArticals def Best_Articals(request): best_posts = BestArticals.objects.all() context = {'best_posts' : best_posts} return render(request,'android/side_bar_good_posts.html',context=context) html page : {% for post in best_posts %} <div class="card rounded mx-auto d-block" style="width: 18rem;margin-bottom:50px;border-color:#7952b3"> <div class="card-body" id="mobile_design_card"> <a href="{{post.url}}"><p class="card-text" id="mobile_design_card_name">{{ post.name }}</p></a> </div> <a href="{{post.url}}"><img src="{{ post.get_image }}" class="card-img-top" alt="..." height="290px" width="300px"></a> </div> &nbsp;&nbsp; {% endfor %} i didn't add Best_Articals in urls.py because i don't want create url for it , i just want show data in other html page from side_bar_good_posts.html for example i add this line in other html page : {% include 'android/side_bar_good_posts.html' %} -
How to extend gettext_lazy to translate strings in variables?
There is a code that works fine: from django.utils.translation import gettext_lazy gettext_lazy('Hello!') But this, does not work: from django.utils.translation import gettext_lazy greetings = 'Hello!' gettext_lazy(greetings) Also this, does not work: from django.utils.translation import gettext_lazy def custom_gettext_lazy(content): return gettext_lazy(content) custom_gettext_lazy('Hello!') It seems, that makemessages scans for all files as plain text and searches for gettext_lazy imports and then its explicit usage Is it possible to force makemessages grab strings from custom functions like custom_gettext_lazy that performs some additional stuff? -
Haystack index_queryset filter not working when updating object from Admin panel
I'm indexing a model with some conditions. It works fine. But, when I'm updating some info from Admin panel the conditions are not working. SearchIndex: class QuestionBankIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True, template_name='search/question_bank_text.txt') question_id = indexes.IntegerField(model_attr='id') owner = indexes.CharField(model_attr='owner', null=True) def get_model(self): return QuestionBank def index_queryset(self, using=None): return self.get_model().objects.filter(active=True) So, while I'm changing an object from Admin panel, this object is indexing even if it's active=False I'm using Haystack==3.0 with Realtime_Signal_Processor configuration. -
Different PostgreSQL database: local and remote | Django
I've just configured my remote PostgreSQL database @ Elephant but now I'd like to also set the local PostgreSQL connection in order to make some tests before going online (remote db). This is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': 'lallah.db.elephantsql.com', 'PORT': '5432', } } How can I update the settings.py to also let me use the localhost PostgreSQL connection without erasing the elephant configurations? Thank you!