Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
css + xhtml2pdf : force only one table per page
trying to output one table per page in a pdf document generated with xhtml2pdf. Nothing in the doc really explains how to achieve this and front end stuff is not my strong suit here is what I got so far: {% load static %} <!DOCTYPE html> <html> <head> <style> @page { @frame header_frame { /* Static Frame */ -pdf-frame-content: header_content; left: 50pt; width: 512pt; top: 50pt; height: 200pt; } size: a4 portrait; @frame content_frame {/* Content Frame */ left: 50pt; width: 512pt; top: 230pt; height: 700pt; } } table { width:100%; } table.print-friendly tr td, table.print-friendly tr th { page-break-inside: avoid; } table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 2px; text-align: left; } table#t01 tr:nth-child(even) { background-color: #eee; } table#t01 tr:nth-child(odd) { background-color: #fff; } /* table#t01 th { background-color: black; color: white; } */ body{ font-size: 12px; } h1,h2,h3,h4,h5,h6,p{ padding: 0; margin: 0; } img{ float: left; } </style> </head> <body> <div id="header_content"> <th colspan="5" style="text-align: center;"> <div style="text-align: left"> <h3></h3> <p style="padding-bottom: 2px; margin: 0; font-size: 20px;">{{ my_company.name }}</p> <p style="padding-bottom: 2px; margin: 0; font-size: 10px;">{{ my_company.address }}</p> <p style="padding-bottom: 2px; margin: 0; font-size: 10px;">{{ my_company.city }}, {{ my_company.zip_code }}</p> … -
Pulling data from Django database and populating lists for user input
I'd like to preface this with first - thank you for anyone willing to listen to my question - it may be a bit complex and second I'm very new to web development so I'm sorry if I sound dumb. I'm making a website that essentially allows admins (Professors) to input courses based on specific majors, and allows users (Students) to select what courses they've taken so far - and based on that input - display what courses they must still take to complete their degree. In the Django admin page - it allows admins to create courses offered and one of the parameters is the major affiliated with the specific course. I then want the users (Students) to be able to select one of the majors (there are nine) - and dependent on what major they select - choose from the available courses provided affiliated with that major. After the user selects what courses they've taken it would redirect them to a page that displays all the remaining courses they must take. My question is, how do I take the data inputted by the admins, and based on the major they provide - send that data to a major … -
TypeError: 'class Meta' got invalid attribute(s): constraints
I have a project in django and when I try to do the migrations it sends me the following error: File "C:\andon\f2candon\venv\lib\site-packages\django\db\models\options.py", line 195, in contribute_to_class raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) TypeError: 'class Meta' got invalid attribute(s): constraints The code segment where the error sends me is the following, in the file options.py: # Any leftover attributes must be invalid. if meta_attrs != {}: raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) -
Django and requirejs issue
i have link problem, i can't link Require js in Django webs app. this is the HTML link: <script data-main="static/assets/js/app" src="static/assets/vendor/require/require.js"></script> and this is Function call: <script> require(['app'], function () { require(['modules/menu']); }); </script> this is the Requirejs code: "use strict"; //scripts availabel require.config({ baseUrl: 'static/assets/', paths: { //PLUGINS 'jquery': 'vendor/jquery/jquery.min', 'plugins/modernizr': 'vendor/modernizr/modernizr', 'plugins/bootstrap_v3': 'vendor/bootstrap/v3/js/bootstrap.min', 'plugins/slick': 'vendor/slick/slick.min', 'plugins/progress': 'vendor/progress/dist/circle-progress.min', 'plugins/magnificPopup': 'vendor/magnificPopup/dist/jquery.magnific-popup.min', 'plugins/bridget': 'vendor/jquery/jquery-bridget', 'plugins/isotope': 'vendor/isotope/isotope.pkgd.min', 'plugins/datePicker': 'vendor/datePicker/js/datepicker', //MODULES 'modules/main': 'js/modules/main', 'modules/player': 'js/modules/player', 'modules/progress': 'js/modules/progress', 'modules/upload': 'js/modules/upload', 'modules/userToggle': 'js/modules/user-toggle', 'modules/menu': 'js/modules/menu', 'modules/statistic': 'js/modules/statistic', 'modules/posts': 'js/modules/posts', 'modules/googleCharts': 'js/modules/google-charts', 'modules/datePicker': 'js/modules/datepicker', }, shim : { //PLUGINS 'plugins/modernizr': { exports: 'Modernizr' }, 'plugins/bootstrap_v3': { deps: ['jquery'], exports: 'Bootstrap' }, 'plugins/datePicker': { deps: ['jquery'], exports: 'datePicker' }, } }); The HTML File in -> home/templates/index.thml The Requirejs Files in -> root/static/assets/js/* -
Is there any function to count a particular choice field from feedback model in django?
I am new to Django framework: The model Feedback I have created is this: class Feedback(models.Model): customer_name = models.CharField(max_length=120) email = models.EmailField() Place = models.CharField(max_length=120) Area_Type = models.ForeignKey(Product, on_delete=models.CASCADE) Electricity = models.CharField(max_length=3, choices=[('1','Excellent'),('2','Good'),('3','Bad')]) Water_Supply = models.CharField(max_length=3, choices=[('1', 'Excellent'), ('2', 'Good'), ('3', 'Bad')]) details = models.TextField() Satisfactory_locality = models.BooleanField() date = models.DateField(auto_now_add=True) From this I want to count number of feedback choices are Excellent for Electricity field. Please also tell about how to view this count. -
Rendering to Home Page when a Slug is not available (DJANGO)
I have created a webpage where an admin can create random pages via admin page using slug adding the name into the slug field. What I am trying to do is if a user tries to render to random page it should to go a "404" page. Model class CustomPage(models.Model): title = models.CharField(max_length=20, blank=True) subtitle = models.CharField(max_length=50, blank=True) slug = models.SlugField(max_length=500,blank=True) content = RichTextField() displayOnFooter = models.BooleanField(default=False) def __str__(self): return f'{self.title}' def get_absolute_url(self): return reverse('custom-page', kwargs={'slug': self.slug}) views.py def custom_page(request, slug): context = { 'all': CustomPage.objects.filter(slug=slug), 'toBePublished': CustomPage.objects.all() } all_querry = CustomPage.objects.all() count = 0; for i in all_querry: if i.slug == slug: return render(request, 'member/custom_page.html', context) elif count < len(all_querry): count += 1; else: return render(request, 'member/home.html',context) urls.py path('register/', views.register, name='member-register'), path('login/', auth_views.LoginView.as_view(template_name='member/login.html'), name = 'login'), path('logout/', auth_views.LogoutView.as_view(template_name='member/logout.html'), name = 'logout'), path('forgot-password/', auth_views.PasswordResetView.as_view(template_name='member/forgot-password.html'), name = 'member-forgot-password'), path('profile/', views.profile, name = 'profile'), path('accounts/login/', auth_views.LoginView.as_view(template_name='member/login.html')), path('groups/', views.groups, name='member-group'), path('groups/<slug:slug>/', views.groups_detail, name='member-group-detail'), path('<slug:slug>/', views.custom_page, name='custom-page'), When I add a random string myself at the end so for example: http://127.0.0.1/dasada/ I get a ValueError at /dasada/ The view member.views.custom_page didn't return an HttpResponse object. It returned None instead. Thanks Onur -
ImportError: cannot import name 'docker_config' from 'geodjango'
I have a settings.py file that I must add the following whitenoise code to it. Whitenoise is just simplifying the deployment of static files for my django application. import socket STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = "/static/" if socket.gethostname() =="your_laptop_hostname_goes_here": DATABASES["default"]["HOST"] = "localhost" DATABASES["default"]["PORT"] = docker_config.POSTGIS_PORT else: DATABASES["default"]["HOST"] = f"{docker_config.PROJECT_NAME}-postgis" DATABASES["default"]["PORT"] = 5432 # Set DEPLOY_SECURE to True only for LIVE deployment if docker_config.DEPLOY_SECURE: DEBUG = False TEMPLATES[0]["OPTIONS"]["debug"] = False # ALLOWED_HOSTS = ['.your-domain-name.xyz', 'localhost',] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True else: DEBUG = True TEMPLATES[0]["OPTIONS"]["debug"] = True ALLOWED_HOSTS = ['*', ] CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False I also have to create a docker_config.py file with a boolean variable which I have done so. I try to import the file to my settings.py using: from geodjango import docker_config And I get the described error in the title after I run: python manage.py migrations My project folder looks like this: -
Django pass object to model of antother form
I have implemented a python form/view/template that lets you configure different notifications for a product: models.py class PNotification(models.Model): add = models.BooleanField(default=False, help_text='Receive messages when an engagement is added') delete = models.BooleanField(default=False, help_text='Receive class Product(models.Model): forms.py class PNotificationForm(forms.ModelForm): class Meta: model = PNotification exclude = [''] class ProductForm(forms.ModelForm): The PNotification has an own view and template: <h3> Edit Notifications for {{ product.name }}</h3> <form class="form-horizontal" method="post">{% csrf_token %} {% include "dojo/form_fields.html" with form=form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input class="btn btn-primary" type="submit" value="Submit"/> </div> </div> </form> When I call the page (edit/product_id/notifications) to edit an products notifications, the h3 is set correct, so the product is passed to the form/template. My problem is: I need to link PNotification with a product. Can someone help me to pass product.id to my PNotificationForm so I can save it there? This field should be the primary key of PNotification. Thanks a lot :) -
Django User Registration Authentication Problem
Please I am new to Django and user registration is giving me serious headache. The UserCreationForm displays on the page but does not display any errors even when I deliberately pass in wrong and submit passwords.It just refreshes. It does not show errors like password too short etc unlike the login page. Urls.py for Main Project from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/',include('django.contrib.auth.urls')), path('',include('account.urls')), ] Urls.py for account_app from django.urls import path from .views import home,register urlpatterns = [ path('',home,name='home'), path('register/',register,name='register'),] Views.py for account_app from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate,login def home(request): return render(request,'base.html') def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user =authenticate(username=form,password=password) login(request,user) return redirect('home') else: form = UserCreationForm() form = UserCreationForm() return render(request,'registration/register.html',{'form':form}) Template folder looks like this +templates +registration +register.html Register.html code <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Register</title> </head> <body> <h1>Registration Page</h1> <form method="POST" action="{%url 'register' %}"> {%csrf_token %} {% if form.errors %} <p>There are errors in the form </p> {% endif %} {{form}} <button type="submit" name="button">Submit</button> </form> </body> </html> -
Ranking system with ForeignKey in Django
I want to have ranking for university model. There can be several ranking types for each university. Admin should be able to add and delete the ranking type and score as needed. For example: Harvard will have 3 different rankings and different scores in those rankings. But X University will have none. But some other university can have totally different ranking type and more than three. Universities should be filterable according their score in each ranking type. I tried this: class University(models.Model): title = models.CharField(_("title"), max_length=250) about = models.CharField(_("about"), max_length=450) logo = models.CharField(_("logo"), max_length=150) ranking = models.ManyToManyField("program.Ranking") def __str__(self): return self.title class Meta: verbose_name_plural = 'Universities' class Ranking(models.Model): title = models.CharField(_("Title"), max_length=250) scope = models.ForeignKey("program.Scope", on_delete=models.DO_NOTHING) score = models.IntegerField(_("Score")) def __str__(self): return f'{self.title} {self.score}' class Scope(models.Model): title = models.CharField(_("Title"), max_length=350) def __str__(self): return self.title I see it as not well-optimized (because of repetitiveness) and think there should be better way of doing it. Is there better way of doing it? If yes, please add some code and give explanation why it is better idea than mine. -
Is there a way to disable some checkboxes through django view?
In a MultilpleChoiceField form, I'm trying to let enabled only some fields. For example, the customer will send the name that he want to search in the database, after that, I would like that the form bellow shows checked and enabled only the checkboxes where were found information about the customer. #forms.py class ResultadoForm(forms.Form): TRIBUNAIS_FEDERAIS_CHOICES = ( ('trf1', 'Tribunal Regional Federal da Primeira Região'), ('trf2', 'Tribunal Regional Federal da Segunda Região'), ('trf3', 'Tribunal Regional Federal da Terceira Região'), ('trf4', 'Tribunal Regional Federal da Quarta Região'), ('trf5', 'Tribunal Regional Federal da Quinta Região'), ) tribunais_federais = forms.MultipleChoiceField( choices=TRIBUNAIS_FEDERAIS_CHOICES, widget=forms.CheckboxSelectMultiple ) TRIBUNAIS_JUSTIÇA_CHOICES = ( ('tjes', 'Tribunal de Justiça do Espírito Santo'), ('tjmg', 'Tribunal de Justiça de Minas Gerais'), ('tjrj', 'Tribunal de Justiça de Rio de Janeiro'), ('tjsp', 'Tribunal de Justiça de São Paulo'), ) tribunais_estaduais = forms.MultipleChoiceField( choices=TRIBUNAIS_JUSTIÇA_CHOICES, widget=forms.CheckboxSelectMultiple ) I'm trying to do that in the views.py: class ResultadoView(LoginRequiredMixin, FormView, TemplateView): template_name = 'resultado.html' form_class = ResultadoForm success_url = "resultado.html" def get(self, request, *args, **kwargs): cnpjs = request.session['lista'] # cnpjs = pd.read_json(cnpjs) current_user = request.user print(current_user.id, current_user.first_name) form = self.form_class(initial=self.initial) a = pd.read_html(form.as_table()) print(a) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): return render(request, … -
Trying to upload CSV for testCase and getting " MultiValueDictKeyError: "'file'""
trying to upload my csv for testing and I keep getting " MultiValueDictKeyError: "'file'" Not sure what I am doing wrong here. def test_import_existing_order(self): data = File(open('TestCSV - OrderTest.csv', 'rb')) upload_file = SimpleUploadedFile('data.dump', data.read(),content_type='multipart/form-data') request = self.seller_client.put( IMPORT_ORDERS_URL, {'file':upload_file,}, format="multipart", content_disposition="attachment; filename=data.dump") def importOrdersToDict(request): import csv line_count = 0 response_data = {"orders":{}, "orderCount":0, "dropOffLocations":0, "totalCases":0, "locations":{}, } csv_file = request.FILES['file'] csv_file.seek(0) csv_reader = csv.DictReader(csv_file) -
Change root url in Django
I'm building a Django application that I'm running on two servers and I would like to be able to change what it considers its root url when it's building urls. For example, if one instance is running on 127.0.0.1 and the other is at 127.0.0.2/abc/, using path('home/', views.home, 'home') on the second instance will point to "127.0.0.2/home" instead of "127.0.0.2/abc/home" I currently have something like this set up in my urls.py file site_patterns = [ path('home/', views.home, 'home')] urlpatterns = [ path('abc/', include(site_patterns)), # root ] Which works fine, but it seems like there should be a more elegant way to do this, like maybe a setting? I just can't seem to figure out how. -
Register celery periodic tasks to see it within django admin
I am trying to code some periodic background tasks within Django and Celery. My tasks are working well, I manage to start those periodically when launching my celery worker with beat scheduler : celery -A parifex worker -B -l info Discovered tasks by the worker As you can see in the above image, my tasks are well discovered. However, the autodiscover on INSTALLED_APPS was not working as expected, so I had to include the path to the app where I want to find tasks in Celery instantiation. Requirements pip freeze |grep "celery\|Django" celery==4.4.1 Django==3.1.2 django-celery==3.3.1 Into the base app where settings stands: celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'parifex.settings') # Define the Celery configuration and include <app>.tasks to discover it app = Celery('parifex', include=['device.tasks']) # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True) @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') settings.py djcelery.setup_loader() CELERYD_HIJACK_ROOT_LOGGER = False # http://celery.readthedocs.org/en/latest/configuration.html#celery-redirect-stdouts-level CELERY_REDIRECT_STDOUTS = True # par défaut CELERY_REDIRECT_STDOUTS_LEVEL = 'DEBUG' CELERY_BROKER_URL = 'redis://:Redi$DB_withCelery@127.0.0.1:6234' # store schedule in the DB: … -
Determining Site Language in Django Model
I am writing a get_absolute_url method for a model in Django. This method is later used in building a sitemap. I am trying to form a url, but there is an issue in that I do not know how to get the language argument at the model stage. That is, the urls in the sitemap end up looking like example.com/news/123, whereas I would like them to look like example.com/en/123. How can this be done? class News(models.Model): title = models.CharField(_("Название"), max_length=255) body = HTMLField(configuration='CKEDITOR_SETTINGS_BODY') image = models.ForeignKey(NewsImageModel, on_delete=models.CASCADE) background_image = FilerFileField(on_delete=models.SET_NULL, null=True, blank=True) created = models.DateTimeField(default=datetime.now) author = models.ForeignKey(User, on_delete=models.CASCADE) view_count = models.PositiveIntegerField(default=0) @property def full_name(self): return '%s %s' % (self.author.last_name, self.author.first_name) @property def short_description(self): return truncatewords(self.body, 10) @property def clear_date(self): return date(self.created, "d.m.y") def __str__(self): return self.title def get_absolute_url(self): return "/news/" + str(self.id) We are using DjangoCMS, so in settings.py, we have something like this: LANGUAGES = ( ('ru', gettext("ru")), ('en', gettext("en")), ) CMS_LANGUAGES = { 'default': { 'public': True, 'hide_untranslated': False, 'redirect_on_fallback': True, }, 1: [ { 'public': True, 'code': 'ru', 'hide_untranslated': False, 'name': gettext("ru"), 'redirect_on_fallback': True, }, { 'public': True, 'code': 'en', 'hide_untranslated': False, 'name': gettext("en"), 'redirect_on_fallback': True, }, ], } -
I keep getting and error Nameerror in my urls
Running Django 3.10 I keep getting NameError: name 'products_api_detail_view' is not defined Urls re_path(r'api/products/(?P\d+)/', products_api_detail_view), views def product_api_detail_view(request, pk, *args, **kwargs): try: obj = Products.objects.get(pk=pk) except Products.DoesNotExist: return JsonResponse({"message": "Not found"}) # return JSON with HTTP status code of 404 return JsonResponse({"id": obj.id}) -
How can I take my docker web application and host it using IIS?
I have created django-react web application that I am currently running on my localhost using docker containers (one for front end and one for backend). I also use a cloud hosted mongodb cluster to store data. I would like to deploy the web app using IIS. I have an IIS server configured in a virtual environment. The web app is also running locally in that same virtual environment. I run the web app locally by using "docker-compose build" and "docker-compose up". How can I deploy the app so that it is running in that IIS server? I have two dockerfiles, one for the frontend and one for the backend. Can I simply change the directories that these dockerfiles COPY into to the C:\inetpub\wwwroot directory? -
How to Add "lang" Attribute to a <pre> Tag in python-markdown?
I'm using django-pygmentes in order to highlight my code-blocks. I'm writing the contents with markdown and convert it to HTML in the view part. Everything is ok. Now, I want to implement the highlighting side. The Pygmentes package needs something like this in order to apply the colors: <pre lang="python">...</pre> But, it's what I get when I write a code block in my post: <pre><code clas="language-python">...</code></pre> Here is my markdown: ```python print('Hey') So, Pygments could not find the element. Is there any way to override any method and apply the changes? -
How can I disable a Django cache?
I have written a small django app and in it I can upload some documents and at another point I can make a reference from a payment to the corresponding document. But my problem is that the list of documents is always outdated. But when I kill my gunicorn and start the webserver again, then the dropdown list with documents loads correctly and also shows the newest file uploads. Do you have an idea why Django behaves like that? Best regards -
how to get setup python app icon on cpanel on bluehost
I want to deploy django app. I tried with apache in manual and Iam failing to do that. I want to deploy through setup python app icon by following this video - https://www.youtube.com/watch?v=Y1jJPVhanzU&t=528s But no such icon is present on my bluehost filemanager. The support chat person said that has to install from my side. Python and apache are installed on whm but how to get that icon -
Gunicorn reflect changed code dynamically
I am developing a django web application where a user can modify the code of certain classes, in the application itself, through UI using ace editor (think of as gitlab/github where you can change code online). But these classes are ran by celery worker at some point. Once code changes are saved, the changes are not picked by django or celery due to gunicorn (running it locally using runserver works fine and changes are picked by both django and celery). Is there a way to make gunicorn reflects the changes of certain directory that contain the classes without reloading the whole application? and if reloading is necessary, is there a way to reload gunicorn's workers one-by-one without having any downtime? the gunicron command: /usr/local/bin/gunicorn config.wsgi --bind 0.0.0.0:5000 --chdir=/app The wsgi configuration file: import os import sys from django.core.wsgi import get_wsgi_application app_path = os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir)) sys.path.append(os.path.join(app_path, 'an_application')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = get_wsgi_application() -
Get choice django with post request
I have found many solutions to get choice in Django field but they work when using a template such as get_foo_display CATEGORY_CHOICES = ( ('M', 'Male'), ('F', 'Female'), But what I have to do if I need to get Male or Female with request.POST in views.py. Currently I am using request.POST['gender'] But this is giving me M or F -
Django Dynamic initial values for current user file upload
I've be struggling the last to days. I want the current user to be able to add a file without selecting himself the user of the file being uploaded. For now, I need to manually select a user from the list to add a file related to him. Big thanks in advance! Hugo Here's models.py from django.db import models from django.contrib.auth.models import User class Client(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class fichier4(models.Model): user = models.ForeignKey(Client, on_delete=models.CASCADE) file = models.FileField() date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file my view.py code form3 = FichierUpload() initial_data = { 'user' : request.user } if request.method == 'POST': form3 = FichierUpload(request.POST or None, request.FILES, initial=initial_data) if form3.is_valid(): form3.save() return redirect('allfiles') forms.py class FichierUpload(ModelForm): class Meta: model = fichier4 fields = '__all__' -
Good practice to use javascript
I am currently working on a Django project and I have some invoice section. I am using javaScript and jQuery for adding items, price, quantity, discount, taxes, etc. My main concern is that javascript loads on browsers and users can edit JS code and I want to prevent that. I know that it is not possible to completely protect js code but what are some good practices to use javascript. Will obfuscation and minification work? (I know about them but haven't tried yet). I am curious to know what techniques do experienced developers use while working on javascript. And what technique should I use in my case? Thanks in advance. (New web developer looking for some help from experienced seniors :) ) -
Redirecting to folder inside public html from a django app hosted in cpanel
I have a django app hosted in cpanel outsite public html folder running on https://example.com. And also I have a codeigniter site inside the public html folder say name "abc". When I try to access abc using "https://example.com/abc" it shows django page not found error. How can I add a redirect url in urls.py file so that I can redirect to this link.