Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template Query Set and filters
In my view, I have a model that returns all instances of a model that has a foreign key to user. This view renders a profile page where the model.user is checked against the request.user, if it matches, it prints out information on that model on the profile page. This is what I have in my views.: @login_required(login_url='loginpage_company') @allowed_users_company(allowed_roles=['company']) def profile_company(request): print(request.user) companies = Company.objects.all() responses = Response.objects.all() context = { 'companies': companies, #'company_reviews': company_reviews, #'total_reviews': total_reviews, 'responses': responses, 'info': "No company claimed yet", 'infor': 'Not Available', } return render(request, 'companyusers/profile_company.html', context) for my models I have the following. class Company(models.Model): Online_Merchant = 'merch' Education = 'edu' Transportation = 'trans' Hospitalism = 'hosp' Healthcare = 'health' Construction = 'const' Blog = 'blog' Finance = 'fin' Media = 'media' Government_Agency = 'agency' Other = 'other' Manufacturing = 'manufacturing' sector = [ (Online_Merchant, 'Online Merchant'), (Education, 'Education'), (Transportation, 'Transportation'), (Hospitalism, 'Hospitalism'), (Healthcare, 'Healthcare'), (Construction, 'Construction'), (Blog, 'Blog'), (Finance, 'Finance'), (Media, 'Media'), (Manufacturing, 'Manufacturing'), (Government_Agency, 'Government Agency'), (Other, 'Other') ] Free = 'Free' Premium = 'Premium' package = [ (Free, 'Free'), (Premium, 'Premium') ] Abuja = 'Abuja' Abia = 'Abia' Adamawa = 'Adamawa' Akwa_Ibom = 'Akwa Ibom' Anambra = 'Anambra' Bauchi = 'Bauchi' … -
How to download a file from a Django template?
Hello Community! I'm working on a small Django project that consists of creating a website that allows you to download multimedia content from YouTube, through the "youtube-dl" library. I summarized the code as much as possible, remaining with the following directory structure: In the file "views.py": from django.shortcuts import render import youtube_dl def home(request): return render(request, 'TestApp/index.html') def download_success(request): url = request.GET.get('url') obj = Media(url) return render(request, 'TestApp/thanks.html', {'content': obj}) class Media(object): '''Class where the logic implemented with "youtube-dl" is found ''' def __init__(self, url): self.url = url ydl_opts = { 'format': 'best' } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([self.url]) In the file "urls.py": from django.urls import path from TestApp import views urlpatterns = [ path('', views.home, name='Home'), path('Thanks', views.download_success, name='thanks'), ] In the directory "/templates/TestApp" are the HTML templates, which have the following structure: "index.html": <!DOCTYPE html> <html lang="es"> <head> {% block title %} <title>misiteweb.com</title> {% endblock %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1"> {% load static %} <!-- CSS --> <link rel="stylesheet" type="text/css" href="{% static 'TestApp/css/styles.css' %}"> <!-- BOOTSTRAP --> <link rel="stylesheet" href="{% static 'TestApp/vendor/css/bootstrap.min.css' %}"> </head> <body> {% block content %} <div class="container"> <br></br> <center><h1> Download Panel </h1></center> <form action="Thanks" method="get"> <br> <div class="form-group"> <input … -
I am using Django password reset view but I am getting error after the password confirm page
Error Page accounts/urls.py password_reset_complete.html -
Python-Pulp: How to store the objective function and constraints in a database for user modification/recall?
I'm building a Django app that allows a user to save their models as different "Scenarios" where they can use a web interface to manually adjust the objective function and some of the constraints. The whole app is built and functioning fine, except for figuring out how to store the OBJ/Cons in the db/table and how to show them back to the user. For the sake of example, let's use the Two stage production program found in the docs. Right now, the model is hardcoded as a .py file and that should transition somehow into a DB. My question becomes, how would you design the table to store the objective function and constraints for access, review, modification, and run by the user? -
How to adjust datatables fonts in Django
Does anybody know how to adjust the field size of Show xx entries in DataTables? Recently my datatables started showing a larger font for the number and for the life of me I can't figure out the CSS to control the size of the field. Is it possible? -
What happens if I run django migrations multiple times in parallel?
So, I often am working with projects where there will be multiple dockerized django application servers behind a loadbalancer, and frequently I will need to deploy to them. I frequently use Watchtower to do pull-based deploys. I build a new image, push it to dockerhub, and watchtower is responsible for pulling those images down to the servers and replacing the running containers. That all works pretty well. I would like to start automating the running of django migrations. One way I could accomplish this would be to simply add a run of the manage.py migrate to the entrypoint, and have every container automatically attempt a migration when the container comes online. This would work, and it would avoid the hassle of needing to come up with a way to do a lockout or leader election; but without some sort of way to prevent multiple runs, there is a risk that multiple instances of the migration could run at the same time. If I went this route, is there any chance that multiple migrations running at the same time could cause problems? Should I be looking for some other way to kick off these migrations once and only once? -
MySQL connection problem using Python/Django
Working on a Python(Django web framework, PyCharm Professional IDE) application and having a difficult time trying to resolve why I cannot connect to my DB when I execute the application. Here is the error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on....) Oddly enough this works fine in my Windows Environment, but for some reason not working on my Mac. Same code, same DB server (MySQL Community server 8.0.16), and same MySQL workbench(also 8.0.16). Something else that is odd, when using the DB Pane in my PyCharm IDE I can see my DB, can run queries, can refresh my DB and log in with my root password with no problem. The following is a code snippet from my Settings.py file... # Local: 'default': { # MySQL database engine class. 'ENGINE': 'django.db.backends.mysql', # MySQL database host ip. 'HOST': '127.0.0.1', # port number. 'PORT': '3306', # database name. 'NAME': 'my_db', # user name. 'USER': 'root', # password 'PASSWORD': 'password', # connect options 'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", } }, } Python 3.7.3 Django==2.2.2 mysqlclient==1.4.4 mysql==0.0.2 mysql-connector-python==8.0.22 PyMySQL==0.10.1 MySQL Community server 8.0.16 MySQL workbench 8.0.16 Note: In regards to Python packages, I prefer to stick mysqlclient since that is what I'm using on my … -
New Apache Server is causing Ajax 500 internal error
So the ajax call worked perfectly before I tried to replace the Django Dev Server with the Apache server. This Apache server is being set up in a docker-compose container along with the website source code. The Ajax Error: I'm going to list all the changes I made to the previously working code. Partial Dockerfile: ... RUN apt-get -qq update && \ apt-get install --yes apache2 apache2-dev && \ pip install mod_wsgi && \ cat httpd.conf >> /etc/apache2/httpd.conf && \ cat envvars >> /etc/apache2/envvars I'm not sure if that's the correct path for the configuration files though. Partial docker-compose.yml: ... web_service: ... command: bash -c "mod_wsgi-express start-server /jackwu_ca/jackwu_ca/wsgi.py --port=80 --user www-data --group www-data" In local httpd.conf: Alias /static/ /jackwu_ca/static/ <Directory /jackwu_ca/static> Require all granted </Directory> WSGIScriptAlias / /jackwu_ca/jackwu_ca/wsgi.py WSGIPythonHome /jackwu_ca/venv WSGIPythonPath /jackwu_ca WSGIDaemonProcess jackwu_ca python-home=/jackwu_ca/venv python-path=/jackwu_ca WSGIProcessGroup jackwu_ca <Directory /jackwu_ca/jackwu_ca> <Files wsgi.py> Require all granted </Files> </Directory> In local envvars: export LANG="en_US.UTF-8" export LC_ALL="en_US.UTF-8" I'm fairly certain I did not set up the Apache server properly, thus, the error. But the site is running, and I can navigate around it. -
Django Test for tutorial not working as expected
I am working on going through the tutorial at - https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing.I am working on AuthorCreateViewTest to create a test for the AuthorCreate view and I have an issue that I can't figure out. Please see the issue that I facing below. I have attached the code from the project also that I think is relevant to this issue. I am sure that it is simple but I am new at coding with Python and Django. Please help if you can so I can continue my training. Issue/Result C:\Project\django_projects\locallibrary>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ...............[(41, 'Set book as returned')] F[(41, 'Set book as returned')] .[(41, 'Set book as returned')] .......... ====================================================================== FAIL: test_logged_in_with_permission (catalog.tests.test_views.AuthorCreateViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Project\django_projects\locallibrary\catalog\tests\test_views.py", line 459, in test_logged_in_with_permission self.assertEqual(response.status_code, 200) AssertionError: 403 != 200 ---------------------------------------------------------------------- Ran 27 tests in 5.632s FAILED (failures=1) Destroying test database for alias 'default'... Views.py class AuthorCreate(PermissionRequiredMixin, CreateView): model = Author fields = '__all__' ###################################################### # You can set the initial values like this ###################################################### initial = {'date_of_death': '05/01/2018'} ###################################################### permission_required = 'catalog.can_mark_returned' test_views.py class AuthorCreateViewTest(TestCase): """Test case for the AuthorCreate view (Created as Challenge).""" def setUp(self): # Create … -
Sum an array of integers found in a JSONField in a Django query
I've got a JSONField in Django and Postgres that looks something like this: { "abc": [1, 3, 2, 1, 0], "bcd": [2, 3, 1], } This is in the data field of a Person model. I'd like to get the total of abc and annotate that total on the query. Something like this: people = Person.objects.annotate(abc_sum=Sum('data__abc')) Such that I have an annotation on my people results that provides the sum of the array value. -
DJANGO - class Meta / varibales db_table
I would like to get a variable in my meta class class Meta: abstract = True db_table = 'bikes_table' managed = False I want to get a variable from self like above : class Meta: abstract = True db_table = 'bikes_table' if self.customers=True else 'cars_table' managed = False Is it possible de get variable ? Thank you -
How to fetch time from database as local time
I created a model in django for postgresql this is my models.py class Other(models.Model): poster = models.ImageField(upload_to="articlepic", blank=True) text = models.CharField(max_length=300, blank=False) created_at = models.DateTimeField("created at", auto_now_add=True) I fetched the date(created at) by using axios in react.when I used below code <p className="mb-0"><small>{item.created_at.toLocaleString()}</small></p></div> then I am getting this 2020-10-21T19:14:34.864421Z But I need in format (Ex:- 2 June 2020).Then how should I write it? -
How i can change the name of the variable in Django?
i added 'Avaliação' to my test site, and, when i migrate the new function i noticed that the name of the variable that receives the TextField, appears in the site, so 'cause of aesthetics reasons, i try change the name of the variable. before: from django.db import models class Avaliação(models.Model): ava = models.TextField(max_length=250) data_ava = models.DateTimeField(auto_now_add=True) after: from django.db import models class Avaliação(models.Model): Deixe_sua_sugestão = models.TextField(max_length=250) #leave_your_suggest in pt-br# data_ava = models.DateTimeField(auto_now_add=True) And gave an OperationalError 'cause "no such columns" or something like that. Someone know how i can change the name of the variable WITHOUT open the file django.db and delecting the tables? -
ican't correct the error no such column in django
my directory What do i have to do? from django.db import models class Product(models.Model): a = models.CharField(max_length=200) b = models.CharField(max_length=200) c = models.CharField(max_length=200) d = models.CharField(max_length=200) my error is no such column and i"ve tried several times. -
Dynamically setting path to static file in Django
In Django, I'm trying to dynamically set the path to a static JavaScript file in a subfolder parsed from the URL. Not sure if this a good way to do it in Django (i.e. best practice), or if I am completely off. It seems like way too many steps and not very DRY, especially the views.py code. Will Django allow me to parse the request in the view (base.html) template and bypass the views.py step? I could use JavaScript, but is it possible in Django? Static file configuration has been defined in myproject/myproject/settings.py as: STATIC_URL = '/static/' My static files are set up as follows Note: each main.js file contains scripts specific to that page. /static/ └── js/ ├── global.js ├── home/ │ └── main.js ├── projects/ │ └── main.js └── users/ └── main.js If this is my URL: http://example.com/projects Views.py: I set a file path relative to my STATIC_URL path def projects(request): context={'js_file':'js/projects/main.js'} return render(request, 'pages/projects.html',{'context':context}) Which I use in my base.html layout template to set the JavaScript path {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- template head content --> </head> <body> <!-- template content --> <script src="{% static context.js_file %}"></script> </body> </html> This renders the … -
Using django-stripe's built-in webhook support
I'm using Django 3.0, Django-Stripe 2.0, and the Stripe CLI. django-stripe provides native support for Stripe webhooks, and their documentation says to include the following in my django project's main urls.py file to expose the webhook endpoint: url(r"^stripe/", include("djstripe.urls", namespace="djstripe")), I have done this, but how do I now leverage the endpoint? As a separate experiment, I created a payments app, setup the URL conf, and successfully called the view when triggering the non django-stripe webhook endpoint via the Stripe CLI. But it doesn't use any djstripe functionality: # project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('stripe/', include("djstripe.urls", namespace="djstripe")), path('payments/', include("payments.urls", namespace="payments")), ] # payments/urls.py from django.urls import path from . import views app_name="payments" urlpatterns = [ path("", views.my_handler, name="my-handler"), ] # payments/views.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_handler(request, **kwargs): print(request.body) return HttpResponse(status=200) Running stripe listen --forward-to localhost:8000/payments/ and, in a separate window, stripe trigger product.created returns a 200 response. But stripe listen --forward-to localhost:8000/stripe/webhook/ and stripe trigger product.created returns a 500. Thank you in advance for your help. -
Django - Create model object with Foreign Key object
I don't feel like I get an idea on how it should work... I do have 2 models: Group is my custom model I wanna save. class Group(models.Model): name = models.CharField(max_length=40) subject = models.CharField(max_length=40) user = models.ForeignKey('User', on_delete=models.CASCADE) User is a standard user model for the application. I'm skipping UserManager for now. Simply said User can have multiple groups. class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=40, null=True, blank=True) surname = models.CharField(max_length=40, null=True, blank=True) objects = UserManager() A serializer for the custom model: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name', 'subject', 'user') And a viewset with overwritten create method: class GroupViewSet(viewsets.ModelViewSet): serializer_class = GroupSerializer def create(self, request, *args, **kwargs): group = group.objects.create(user=self.request.user) serializer = GroupSerializer(group) return Response(serializer.data) When calling a POST a new Group is created. The Group has relation to the User, but other fields (name, subject) are empty. -
'Entry' object has no attribute 'topic' problem in Django, Can anyone help please?
I'm working with Django and I'm stuck in editing entries in views app because of this error: ('Entry' object has no attribute 'topic') from django.shortcuts import render, redirect from .models import Topic, Entry from .forms import TopicForm, EntryForm def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if request != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topic', topic_id=topic.id) context = { 'entry':entry, 'topic':topic, 'form':form } return render(request, 'learning_logs/edit_entry.html', context) It says the problem is from line: topic = entry.topic but I can't figure it out!! -
How to add custom filename to django static file
This is a django jinja2 template code to download static file with a name of Final_Outliers.csv but I want the same functionality but add an extra name i.e. filepath which will be returned by views.py in django. {% load static %} <a href={% static '/Final_Outliers.csv' %} id="button4" class="btn btn-primary">Export to CSV</a> I am returning this filepath fom views.py: return render(request, 'home.html', {'DataFrame': var4, 'path': path, 'message1': True, 'filepath':z[0]}) -
Django: Initialize date input dynamically
I'm building a simple web app where users can log new entries that have a name (CharField) and a date. By default, the date is set to the current date: class EntryForm(forms.Form): entry_name = forms.CharField(label='New Entry', max_length=100) entry_date = forms.DateField(initial=datetime.date.today, widget=forms.widgets.DateInput(attrs={'type': 'date'})) If users select a different date and add an entry with that date, I want the selected date to persist as new initial value when the page reloads. I know there are a lot of related questions on setting initial values dynamically, but unfortunately, I still could achieve setting an initial value dynamically. My view with the form looks like this: @login_required def index(request): if request.method == 'POST': form = EntryForm(request.POST) if form.is_valid(): # get the label name and strip and convert to lower before saving it entry_name = form.cleaned_data['entry_name'].strip().lower() entry_date = form.cleaned_data['entry_date'] entry = Entry.objects.create(name=entry_name, date=entry_date, owner=request.user) return HttpResponseRedirect(reverse('app:index')) else: form = EntryForm() # other, unrelated stuff stuff ... context = { 'form': form, } return render(request, 'app/index.html', context) Even setting the initial value of a form field to a fixed value inside the view's else branch didn't work. I tried EntryForm(initial={'entry_name': 'test'}) (also for entry_date) without success. Also form.fields['entry_name'].initial = 'test', which didn't work either. In … -
403 forbidden access is denied nginx django in plesk
I am using plesk while deploying django https://www.plesk.com/blog/guides/django-hosting-latest-plesk-onyx/ . I am failed to deploy and i am trying to resolve but unable to do it. I am using vps with centos 8 and plesk But i am getting 403 forbidden While checking the logs i am getting [Wed Oct 21 19:51:06.344607 2020] [ssl:warn] [pid 34641:tid 140441160681792] AH01909: mrcric.com:443:0 server certificate does NOT include an ID which matches the server name [Wed Oct 21 20:20:17.381151 2020] [autoindex:error] [pid 55629:tid 140128584320768] [client 162.158.166.34:0] AH01276: Cannot serve directory /var/www/vhosts/mrcric.com/httpdocs/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive I have applied chmod 777 to the www directory but nothing has been resolved -
datatables server-sided smart search
I'm using a server-sided Datatable on Django,once i got the table to be server-sided i lost the smart search. I already did a search on datatable's forums but with no luck at all. Using django, django-rest-framework and Datatables. JS code: <script> $(document).ready(function() { var table = $('#bibs').DataTable({ "serverSide": true, "ajax": "/api/livros/?format=datatables", "columnDefs": [ { "targets": [0,1,2,3,4,5], // "visible": false, "searchable": true, "orderable": true, } ], "columns": [ { "className": 'details-control', "orderable": false, "data": null, "defaultContent": '', "render": function () { return '<i class="fa fa-plus-square" aria-hidden="true"></i>'; }, width:"25px" }, {"data": "autor"}, {"data": "ano"}, {"data": "titulo"}, {"data": "referencia"}, {"data": "tema"}, {"data": "tipo"}, ], "dom":'<"toolbar">Brtip', }); </script> -
How can I add both milliseconds and timezone to Django's logs?
Currently my settings.py file has the following: 'formatters': { 'debug': { 'format': f'%(asctime)s.%(msecs)03d - %(filename)s [%(lineno)4d] - %(levelname)s - %(message)s', 'datefmt': '%m/%d/%Y %I:%M:%S' } } which prints out the following format: 10/21/2020 08:13:34.257. This allows me to see milliseconds, but unfortunately it doesn't let me see the timezone. If I change the datefmt to include the timezone 'datefmt': '%m/%d/%Y %I:%M:%S %Z' then the timezone will show up before the milliseconds like so: 10/21/2020 08:13:34 UTC.410. I wasn't able to find a flag that allows me to add milliseconds to the datefmt portion. How can I add both milliseconds and timezone to Django's logs and have them in a proper order? I want the output to look like this: 10/21/2020 08:13:34.410 UTC. -
Redirect to login page with middleware is causing 'too many redirects" issue
What I want is redirect users to login page if they aren't authenticated. I made a middleware but the redirect is not working. Could someone give me a help? My urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('contas/', include('django.contrib.auth.urls'), name='login'), # I want call this path('', include('apps.props.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my middleware.py from django.http import HttpResponseRedirect from django.urls import reverse class AuthRequiredMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) # Here I call login response = self.get_response(request) return response and finally, my settings.py 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', 'middleware.AuthRequiredMiddleware', # Registering middleware ] What I am getting is this page with "too many redirects" My log: -
The command 'makemigrations' don't make migrations, but i write some lines in models.py
i write this code in models.py: from django.db import models class Avaliação(models.Model): ava = models.CharField(max_length=250) data_ava = models.DateTimeField(auto_now_add=True) And i register this in admin.py with: from django.contrib import admin from .models import Avaliação admin.site.register(Avaliação) But when i try run the code python manage.py migrate and later python manage.py makemigrations, returns to me the answer : 'no changes detected', nothing change in my local site, nothing created in migrations.py. So i write the 0001_init.py my self, he must be auto_generated by Django but it happens when the commands work. The 0001_init.py generated by me, below: from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name = 'Avaliação', fields = [ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ava', models.CharField(max_length=250)), ('data_ava', models.DateTimeField(auto_now_add=True)),] ) ] Running the code python manage.py showmigrations returns to me the 0001_init.py, but nothing changed in my site...