Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Fetching parent data using childs Foreign Key
I'm having trouble fetching my parent data using child. models.py class Company_Data(models.Model): company_name = models.CharField(max_length=254) company_address = models.CharField(max_length=254) company_tel_no = models.CharField(max_length=254) company_fax_no = models.CharField(max_length=254) class Requirements(models.Model): req_service = models.CharField(null=False, max_length=254) req_coverdate_from = models.DateField() req_coverdate_to = models.DateField() req_duedates = models.DateField() company = models.ForeignKey(Company_Data, on_delete=models.CASCADE) views.py def business_setup(request): req = Requirements.objects.filter(req_service = 'Business Setup') context = { 'req' : req , } return render(request, 'admin_template/content/admin_businesssetup_req.html', context) Template HTML {% for requirements in req %} <table> <tbody> <tr> <th style="width:50%">Company Name</th> <td>{{ requirements.company_id.company_name }}</td> </tr> <tr> <th> Covered Date From </th> <td>{{ requirements.req_coverdate_from }}</td> </tr> <tr> <th> Covered Date To </th> <td>{{ requirements.req_coverdate_to }}</td> </tr> <tr> <th> Due Date </th> <td>{{ requirements.req_duedates }}</td> </tr> </tbody> </table> {% endfor %} what im trying was requirements.company_id.company_name to display the related company name but no luck. what i have found was querying the Parent Company_Date to display the Child Requirements. but i want to filter the Requirements table and display it's parent, so those won't be applicable for me. Thank you.. -
Django queryset filter extremely slow, how to improve speed
I've been trying to optimize this Django query set search the last two days and have been unable to speed it up. My backend is MYSQL. There are three tables: Book, Bookstore and Category. Book has 1 million observations, Bookstore has 500 observations and category has 10k observations table = Book.objects.filter(Category=pk, bookstore__in=bookstore_objects).order_by('title').prefetch_related(Prefetch('bookstore', to_attr='bookstore_list'))[:50] The first time this query is run-in the shell it takes 20+ seconds and subsequently it takes about 3-5 seconds. Please help me speed up this query. I cannot understand why it's so slow. -
"TypeError: int() argument must be a string" when applying django migrations
I am getting the following error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'EventCategory' when trying to apply the migrations created by django. Since the migrations are files automatically generated what I have tried is to revert the migrations and running makemigrations again but that didn't work. For more context... Model: class Event(models.Model): name = models.CharField(max_length=100) longitue = models.DecimalField(max_digits=9, decimal_places=6) latitude = models.DecimalField(max_digits=9, decimal_places=6) from_datetime = models.DateTimeField() to_datetime = models.DateTimeField(blank=True, null=True) main_category = models.ForeignKey('even.EventCategory', default=EventCategory.get_default_category, on_delete=models.SET_DEFAULT) subcategories = models.ManyToManyField('even.EventCategory', related_name='subcategories') Migrations: # Generated by Django 2.2.6 on 2019-11-10 01:44 class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('even', '0005_eventcategory_default'), ] operations = [ migrations.AddField( model_name='event', name='subcategories', field=models.ManyToManyField(related_name='subcategories', to='even.EventCategory'), ), migrations.AlterField( model_name='event', name='main_category', field=models.ForeignKey(default=apps.even.models.eventCategory.EventCategory.get_default_category, on_delete=django.db.models.deletion.SET_DEFAULT, to='even.EventCategory'), ), ] Traceback: Running migrations: Applying even.0006_auto_20191110_0144.../usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py:1423: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/related.py", line 937, in get_db_prep_save return self.target_field.get_db_prep_save(value, connection=connection) File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 789, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 959, in get_db_prep_value value = self.get_prep_value(value) File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 968, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'EventCategory'TypeError: int() argument must be a string, a bytes-like object or a number, not 'EventCategory' -
How do I make django find css files?
I am creating my first Django project, and I wanted to create a page with a picture as the background. I have followed some tutorials on the internet, but then when I ran my code, it shows that the css file was not found. I have already tried to see if it was the path of "static" file, and maybe it still is and I did it wrong, but I don't know what else to do. There it is my settings.py """ Django settings for sitetcc project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o+7e$z&!3*#r3%*n$3(l7a3+(u18sj@33y(5p4_3*&*4l_lpfw' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "sitetcc/static"), # '/var/www/static/', ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', … -
Django Admin: Limit query-set selection for a inline form
I have a Django admin form with an inline form as follows. It has many to many field. models Place has photos = models.ManyToManyField(Photo), and Photo is another Django model. The trouble is that I have too many instances of Photo, click I edit the form under Django admin, I get a dropdown with all the Photo instance selection. How can I limit the selections that only has a relationship with Place? class Photoinline(admin.TabularInline): model = Place.photos.through extra = 1 readonly_fields = ('preview', 'my_order',) def preview(self, obj): if obj.photo: id = obj.photo_id photo = Photo.objects.get(id=id) return mark_safe('<img src="/media/%s" width="150" />' % (photo.photo)) else: return mark_safe('Empty, please upload an image') def my_order(self, obj): id = obj.photo_id photo = Photo.objects.get(id=id) if not photo.order: return "" return photo.order class PlaceAdmin(admin.ModelAdmin): list_display = ('name', 'city', 'state', 'country') exclude = ('photos',) formfield_overrides = { models.ForeignKey: {'widget': Select(attrs={'style':'width: 350px;'})}, models.FloatField: {'widget': Select(attrs={'style':'min-width: 350px;'})}, models.URLField: {'widget': TextInput(attrs={'style':'width: 350px;'})}, models.CharField: {'widget': TextInput(attrs={'style':'width: 350px;'})}, models.TextField: {'widget': Textarea(attrs={'style':'width: 350px;height: 38px;'})} } inlines = [ Photoinline, ] -
Django Admin: Custom form to add a link at top of the form
I have the admin form as below: class ItemAdmin(admin.ModelAdmin): list_display = ('name', 'city', 'state', 'country') On the edit form page /admin/my_app/item/1/change/, I want to add a custom link at the top of the page, so admin can click on the link to view the actual item page on a public-facing website. How can I achieve this? -
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model when trying to use another model with foreign key
I am very new to django and programming. I am seeing the below error when trying to run No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. below is my model definition class Group(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) group_description = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_absolute_url(self): self.save() return reverse('group-detail', kwargs={'pk': self.pk}) class GroupPost1(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) group1 = models.ForeignKey('Group', on_delete=models.CASCADE, null=True) def __str__(self): return self.title def get_absolute_url(self): self.save() return reverse('group-post-detail', kwargs={'group_pk': self.group1.id, 'group_post_pk': self.pk}) I have get_absolute_url def in my model. Why am I seeing this error?. any help would be appreciated Thank you -
Can't Start Django-Tailwind in Dev Mode
I am working with django-tailwind on Windows and am following the steps to install. The current step is to 'start tailwind in dev mode' using python manage.py tailwind start. This always fails and the following block of text is the resulting log file: ... 4 verbose run-script [ 'prestart', 'start', 'poststart' ] 5 info lifecycle django_tailwind@~prestart: django_tailwind@ 6 info lifecycle django_tailwind@~start: django_tailwind@ 7 verbose lifecycle django_tailwind@~start: unsafe-perm in lifecycle true 8 verbose lifecycle django_tailwind@~start: PATH: C:\Users\jpyth\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;c:\Users\jpyth\Django\hhs-robotics-website\theme\static_src\node_modules\.bin;C:\Users\jpyth\Django\hhs-robotics-website\venv\Scripts;C:\ActiveTcl\bin;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Program Files (x86)\Razer Chroma SDK\bin;C:\Program Files\Razer Chroma SDK\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Users\jpyth\AppData\Local\Microsoft\WindowsApps;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\jpyth\AppData\Local\Programs\Python\Python37\;C:\Program Files (x86)\Yarn\bin\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\Git\cmd;C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\GnuWin32\bin;C:\Program Files (x86)\Gpg4win\..\GnuPG\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\GCL-2.6.1\bin\;C:\ccl\launcher;C:\Program Files (x86)\ffmpeg\bin;C:\opencv\sources\3rdparty\ffmpeg\;C:\Users\jpyth\AppData\Local\Programs\Python\Python37\Scripts\;C:\ActiveTcl\bin;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Program Files (x86)\Razer Chroma SDK\bin;C:\Program Files\Razer Chroma SDK\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Users\jpyth\AppData\Local\Microsoft\WindowsApps;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\jpyth\AppData\Local\Programs\Python\Python37\;C:\Program Files (x86)\Yarn\bin\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\Git\cmd;C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\GnuWin32\bin;C:\Program Files (x86)\Gpg4win\..\GnuPG\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\GCL-2.6.1\bin\;C:\ccl\launcher;C:;C:\Users\jpyth\AppData\Local\Programs\Microsoft VS Code\bin 9 verbose lifecycle django_tailwind@~start: CWD: c:\Users\jpyth\Django\hhs-robotics-website\theme\static_src 10 silly lifecycle django_tailwind@~start: Args: [ '/d /s /c', "watch 'npm run build-postcss' ./src" ] 11 silly lifecycle django_tailwind@~start: Returned: code: 1 signal: null 12 info lifecycle django_tailwind@~start: Failed to exec start script 13 verbose stack Error: django_tailwind@ start: `watch 'npm run build-postcss' ./src` 13 verbose stack Exit status 1 13 verbose stack at EventEmitter.<anonymous> (C:\Users\jpyth\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16) 13 verbose stack at EventEmitter.emit (events.js:210:5) … -
I'm having trouble loading django templates that use sql database entries
I have some webpages that infinitely load. They both need information from an mssql database that I connected to through the Django settings which I presume is the problem. I've tried two different mssql django connector modules, django-mssql-backend(2.2.0) and django-pyodbc-azure(2.1.0.0). I'm also running it on Ubuntu 18.04 LTS with Apache 2.4 and mod_wsgi 4.6.8. It loads fine on my local machine and on a redhat6 server. 'asicbld': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database_name', 'HOST': 'hostname', 'USER': '*****', 'PASSWORD': '****', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'MARS_Connection': 'True', } I expect the webpage to load but it doesn't load. -
Pytest Django function mocking APITestCase
I am trying to create tests involving sending GET requests to my API using pytest-django and I need a function used in the views to be mocked. I have tried mocker from pytest-mock and unittest.mock.patch and every time I mock this function in some test case it remains mocked in the other tests as well. First .py test file: from unittest.mock import patch from rest_framework.test import APITestCase import pytest @pytest.mark.django_db class TestFirst(APITestCase): @classmethod def setUpClass(cls): cls.patcher = patch(app.some.module.function) cls.patcher.start() @classmethod def tearDownClass(cls): cls.patcher.stop() def test_something(self): get_data = self.client.get('/some/url') self.assertEqual(200, get_data.status_code) and then followed by a test in some completely different .py file: from rest_framework.test import APITestCase import pytest @pytest.mark.django_db class TestSecond(APITestCase): def test_something_else(self): get_data = self.client.get('/some/url') self.assertEqual(200, get_data.status_code) When debugging the first test case, the method is patched correctly. However when running the second test, the method remains patched and the mock object keeps the number of calls received. Am I missing something important? -
Keep data in the form after submit
I am implementing search by two fields in form in Django. I want to keep input data after search. For example I input "C++" and chose "IT" then I received Default values I tried to parse request variable --- e.g. data = request.POST.copy() but did not achieved result. What is the reason of this problem? How can I solve this problem? This is my code: models.py class Company(models.Model): name = models.CharField(max_length=200) about = models.TextField() def __str__(self): return self.name class Vacancy(models.Model): company_key = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField(max_length=200) salary = models.CharField(max_length=200, default='40.000') text = models.TextField(default="The text about vacancy") city = models.CharField(max_length=200, default='Москва') date_str = models.CharField(max_length=50, default='12 сентября') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) CHOICES = [ ('ALL', 'ALL'), ('IT', 'IT'), ('FINANCE', 'FINANCE'), ('OTHER', 'OTHER'), ] department = models.CharField( max_length=20, choices=CHOICES, default='ALL', ) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title urls.py urlpatterns = [ path('', HomePageView.as_view(), name='vacancy_list'), path('search/', SearchResultsView.as_view(), name='search_results'), path('vacancy/<int:pk>/', views.vacancy_detail, name='vacancy_detail'), path('accounts/login/', BBLoginView.as_view(), name='login'), path('accounts/profile/', profile, name='profile'), path('accounts/logout/', BBLogoutView.as_view(), name='logout'), views.py class HomePageView(ListView): model = Vacancy template_name = 'vacancy_list/vacancy_list.html' paginate_by = 2 page_kwarg = 'vacancy' context_object_name = 'vacancies' def vacancy_detail(request, pk): vacancy = get_object_or_404(Vacancy, pk=pk) return render(request, 'vacancy_list/vacancy_detail.html', {'vacancy': vacancy}) class SearchResultsView(ListView): model = Vacancy template_name … -
Django model is inheriting 'password' field from another model with it's PK and showing in PostgreSQL
While I was checking my code, i noticed that some models have the property "password" as a DB column in PostgreSQL and that those models don't have that attribute, the only relationship between the attribute "password" and the table is that the table's model has a FK pointing to a model which is a AbstractBaseUser extension. Ubuntu 16+ Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian django = ">=2.1.0" djangorestframework = ">=3.9.2" flake8 = ">=3.6.0,<3.7.0" autopep8 = "*" psycopg2 = "<2.8.0,>=2.7.5" django-organizations = "==1.1.2" django-countries = "*" [requires] python_version = "3.7" from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin import datetime from django.core.validators import MaxValueValidator from django_countries.fields import CountryField # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password = None, ** kwargs): "" "Creates and saves a new User" "" if not email: raise ValueError('Users must have an email address') user = self.model(email = self.normalize_email(email), ** kwargs) user.set_password(password) user.is_staff = False user.is_active = True user.is_doctor = False user.save(using = self._db) return user def create_superuser(self, email, password, ** kwargs): "" "Creates and saves a new super user" "" user = self.create_user(email, password, ** kwargs) user.is_staff = False user.is_active = True user.is_doctor = False user.is_superuser … -
Django 2 combine ListView and DetailView in my template page
i have two models "product" and "brand" product has brand field ManyToMany to link the products with the concerned brand ## models.py class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() brand = models.ManyToManyField(Brand) class Brand(models.Model): title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) ## url.py re_path(r'^brands/(?P<slug>[\w-]+)/$', BrandDetail.as_view(), name = 'branddetail'), ## views.py class BrandDetail(DetailView): queryset = Brand.objects.all() template_name = "brands/brand.html" ## brands/brand.html {{ object.title }} <br/> {{ object.description }} <br/> Now when am rendring brand.html it shows the brand title and description fine My question is if i want to render in the same page the list of products linked to specific brand "considering the brand slug already passed in the URL", how i can do that? the class is DetailsView and it has only Brand details in the query set as shown!! i need any solution not ne -
How to hide SECRET_KEY?
I put my SECRET_KEY in secrets.json, and that one in .gitignore; in settings.py I read the key from the file. Bottom line: my local server is reading the key. But when I want to produce a git push heroku master, an error is thrown, the file was not found. It is understandable! I added it to .gitignore. And accordingly the question: what to do? Why advise to hide SECRET_KEY in a separate file hidden from git, if then we can’t just push our changes to the server? I see this way out here: I can explicitly register my key in settings.py, push it on the server, hide it in the file again, push it in the github repository. But how safe is it? Is SECRETS_KEY hidden only for public repositories? -
How to send POST requests from dynamic fields?
I'm creating a quiz form to pass into a JSON file, but I'm having trouble sending the POST requests. I'm not sure which fields I can access, or how. This is the form: https://i.imgur.com/6xtmt3a.png <script> // input field $(document).ready(function() { var wrapper = $(".div1"); var newbutton = $(".add_form_field"); var fields = 1; $(newbutton).click(function(e) { e.preventDefault(); $(wrapper).append(' <div class="input-group"> <input type="text" value = "Question" class="form-control" placeholder="Recipients username" <div class="input-group-append" id="button-addon4"><button class="btn btn-outline-secondary" id ="delete" type="button">Delete</button><button class="btn btn-outline-secondary" id ="add" type="button">Add</button></div></div></div>'); //add input box //$(wrapper).append('<button type="button" id ="test1" class="btn btn-primary">Primary</button>'); //add input box //$(wrapper).append('<div><input type="text" value = "Question"name="mytext[]"/> <a href="#" id="delete">Delete</a> <a href="#" id="add">add</a> </div> '); //add input box var d = $(this).parent('form').serialize(); console.log(d); }); //delete buttons $(wrapper).on("click", "#delete", function(e) { e.preventDefault(); $(this).parent('div').remove(); fields--; }) // remove div $(wrapper).on("click", '#s1', function(e) { //$(this).parent('div').parent('div').remove(); var q= $(this).parent().serialize(); console.log(q); }) //add answer $(wrapper).on("click", "#add", function(e) { e.preventDefault(); $(this).parent('div').append('\n <div class="input-group flex-nowrap"><div class="input-group-prepend"><span class="input-group-text" id="addon-wrapping">-</span></div><input type="text" class="form-control" placeholder="Answer" aria-label="Username" aria-describedby="addon-wrapping"></div> ' ); var d = $(this).parent('form').serialize(); console.log(d); //$(this).parent('div').parent('div').append('<div class="input-group mb-3"><input type="text" class="form-control" placeholder="Recipients username" aria-label="Recipients username" aria-describedby="button-addon2"><div class="input-group-append"><button class="btn btn-outline-secondary" type="button" id="button-addon2">Button</button></div></div>' ); fields--; }) }); $( "#quizForm" ).submit(function( event ) { var $form = $( this ), path = $form.attr( "action" ); payload = … -
Apache server isn't responding (504 Bad Gateway)
Before setting up Apache production server, my development server was working on port :8000. After setting up Apache my server will not respond. Note: I am newer to deployment. Django Apache Ubuntu 19.10 ufw status: Status: active To Action From -- ------ ---- 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) netstat: Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 617/systemd-resolve tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 688/sshd tcp6 0 0 :::80 :::* LISTEN 9873/apache2 tcp6 0 0 :::22 :::* LISTEN 688/sshd udp 0 0 127.0.0.53:53 0.0.0.0:* 617/systemd-resolve systemctl status apache2 ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2019-11-09 19:14:25 UTC; 2min 49s ago Docs: https://httpd.apache.org/docs/2.4/ Process: 9858 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS) Main PID: 9873 (apache2) Tasks: 56 (limit: 2286) Memory: 12.4M CGroup: /system.slice/apache2.service ├─9873 /usr/sbin/apache2 -k start ├─9875 /usr/sbin/apache2 -k start └─9876 /usr/sbin/apache2 -k start sudo iptables -vL: Chain INPUT (policy DROP 45 packets, 1911 bytes) pkts bytes target prot opt in out source destination 1889 142K ufw-before-logging-input all -- any any anywhere anywhere 1889 142K … -
Integrating dropzone.js with django formsets
I have a page which allows users to create blog posts. I am using the class based view (CreateView) in the views. I have a post models which has all the fields the user will fill out. I also want the user to add multiple images to the post. So I made a separate Image model with a ForeignKey field to the post model. I then utilized django formsets in order to allow the user to submit a maximum of 10 images with the post. So far this is working exactly as desired. However, I would like to make it a bit easier for the user to upload the images on the front end. Currently there are 10 image input fields and the user needs to add each image one by one. I was thinking of utilizing dropzonejs as this is very user friendly. The issue is that I am struggling to wrap my head around how to set it up. In the dropzone.js docs it says that the form must get a class of "dropzone". The thing is that I don't want the entire form to be a dropzone as the user will also be inputting other Post form … -
Django and DjangoCMS View Management
I am trying to understand how Django in general and DjangoCMS in particular manage views. I have the following in project's urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('video/', include('video_uploader.urls')), path('user/', include('user_accounts.urls')), path('', include('cms.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) That is, there are a couple of specific routes and the rest is handled by DjangoCMS (cms.urls). Inside one of the apps (corresponding to /user/ path above), I have this: from django.urls import path from . import views app_name = 'user_accounts' urlpatterns = [ path('signup', views.user_signup, name='signup'), ] The view for this path is as follows: def user_signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) print('Is the form valid?') print(form.is_valid()) if form.is_valid(): user = form.save() login(request, user) return redirect('/') else: form = UserCreationForm() return render(request, 'user_accounts/signup.html', {'form': form}) So far, so good. Now we get to the interesting bits. user_accounts/signup.html {% extends 'base.html' %} {% block content %} <div class="container"> <h2>Sign up</h2> <form method="post" novalidate> {% csrf_token %} {% include 'includes/form.html' %} <button type="submit" class="btn btn-primary">Create an account</button> </form> </div> {% endblock %} The template above extends the base.html, which is the base template for the whole project. In other words, this sign-up form gets embedded into the content block of the page … -
Pagination did not work on the first page. The current path, &vacancy=2, didn't match any of these
I am implementing search with pagination in Django. When I clicked Next pagination button, received error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8001/&vacancy%3D2 Also, pagination works after search (e.g. I searched something, then clicked pagination and it works) I think that problem with views.py an urls.py How can I solve the problem? models.py class Company(models.Model): name = models.CharField(max_length=200) about = models.TextField() def __str__(self): return self.name class Vacancy(models.Model): company_key = models.ForeignKey(Company, on_delete=models.CASCADE) title = models.CharField(max_length=200) salary = models.CharField(max_length=200, default='40.000') text = models.TextField(default="The text about vacancy") city = models.CharField(max_length=200, default='Москва') date_str = models.CharField(max_length=50, default='12 сентября') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) CHOICES = [ ('ALL', 'ALL'), ('IT', 'IT'), ('FINANCE', 'FINANCE'), ('OTHER', 'OTHER'), ] department = models.CharField( max_length=20, choices=CHOICES, default='ALL', ) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title urls.py urlpatterns = [ path('', HomePageView.as_view(), name='vacancy_list'), path('search/', SearchResultsView.as_view(), name='search_results'), path('vacancy/<int:pk>/', views.vacancy_detail, name='vacancy_detail'), path('accounts/login/', BBLoginView.as_view(), name='login'), path('accounts/profile/', profile, name='profile'), path('accounts/logout/', BBLogoutView.as_view(), name='logout'), ... views.py class HomePageView(ListView): model = Vacancy template_name = 'vacancy_list/vacancy_list.html' paginate_by = 5 page_kwarg = 'vacancy' context_object_name = 'vacancies' def vacancy_detail(request, pk): vacancy = get_object_or_404(Vacancy, pk=pk) return render(request, 'vacancy_list/vacancy_detail.html', {'vacancy': vacancy}) class SearchResultsView(ListView): model = Vacancy template_name = 'vacancy_list/search_results.html' paginate_by = 5 page_kwarg = 'vacancy' context_object_name … -
Combining filters for a Django queryset
Lets say I have models that look like this: class Sauce(models.Model): ... class Topping(models.Model): ... class Pizza(models.Model): sauces = models.ManyToManyField(Sauce, related_name='pizzas') toppings = models.ManyToManyField(Topping, related_name='pizzas') geo_type = models.CharField(max_length=50, choices=(('NY', 'New York'), ('IT', 'Italy'))) Now, I have an endpoint which accepts URL parameters for filtering the pizza table. For example, one time I might get the following: { "sauces": [1, 4], "toppings": [4, 7], "geo_type": "NY" } Using this, I would simply filter using the following code: Pizza.objects.filter(sauces__in=url_params["sauces"], toppings__in=url_params["toppings"], geo_type=url_params["geo_type"]) And this would work perfectly fine. However, sometimes I might get URL parameters which look like this: { "sauces": [], "toppings": [4, 7], "geo_type": "NY" } Notice the empty array for the sauces parameter. This means that for this request, I don't care about sauces and it can be anything. Now the query would be something like this: Pizza.objects.filter(toppings__in=url_params["toppings"], geo_type=url_params["geo_type"]) Once again, this works as expected. However, the issues is that I have a lot of these fields to filter, and the number of combinations is huge. Is there some to just tell my queryset to ignore a filter if it is an empty array? And if the geo_type is an empty string or null, it should ignore those too. Hopefully … -
Function to take a Django object and return it wrapped in a QuerySet?
How do I take a Django object and wrap it to become a QuerySet with one item? m: SomeModel = SomeModel.objects.get(pk=8) However, later functions expect m to be a QuerySet (even with a length of 1). The answer below works for if you only need to wrap specific models, but is there a way to do something like the below pseudocode? def generic_model2qs(m: Model) -> "QuerySet[Model]": return m.get_model().objects.filter(pk=m.pk) Does Django have something like a .get_model() function? -
Nested Reverse Relation Serializers
How can I create a serializer that returns all the results for a family, with ALL the reverse relationships? Family | +------+------+ | | Student EmergencyContact | Fee e.g. {family: [{id: 1, student_set: [{id: 1, name: "bob Jones", fee_set: [{"Maths Fee": 3, "English Fee": 5}}], {id: 2, name: "Mike Jones", fee_set: [{"English Fee": 5}}], emergency_contact_set: [{id: 1, name:"Joe"}, {id: 2, name: "Mike"}] ] } I can get a single nested level of data using <model>_set in the fields, e.g. student_set, emergency_contact_set, but not deep nested, (the fee_set). class FamilySerializer(serializers.ModelSerializer): student = StudentSerializer(many=True, read_only=True) class Meta: model = Family fields = ["id", "name", "student", # returns nothing "student_set" # only returns the students WITHOUT the fees ] The output (does not have fees): {family: [{id: 1, student_set: [{id: 1, name: "bob Jones"}], {id: 2, name: "Mike Jones"}], emergency_contact_set: [{id: 1, name:"Joe"}, {id: 2, name: "Mike"}], ] } Ideally I would like to use a StudentSerializer and EmergencyContactSerializer inside Family, to get the nested sets. -
Why when I do 'runserver' it redirects me to a url path I haven't inside my project
I have just started to learn Django, and I have done a few tutorials by now. The last one I went through was this morning on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website. Now I am just starting my own project, I set up everything, but when I run 'python manage.py runserver', and I click on the link, it takes me to 'http://127.0.0.1:8000/catalog/' instead of 'http://127.0.0.1:8000/'. I haven't touched any URL, literally, I have typed into the terminal 'django-admin startproject my_app_project', and 'django-admin startapp my_app'. Also, I have run the migrations. If I just delete 'catalog/' from the URL to change it into ''http://127.0.0.1:8000/' it automatically sends me to the unwanted one. I don't know what it is. Have a look at my directories: This is the address it takes me to: Does anyone know what's wrong with it? I have already reinstalled Pycharm. -
Django: QuerySet filter doesn't work as expected
I have the following QuerySet. from myapp.events.models import Event from myapp.surveys import QuestionFocus from django.conf import settings event = Event.objects.get(pk=12) survey = event.surveys.get( template=settings.SURVEY_POST_EVENT ).questions.filter( focus=QuestionFocus.RECOMMENDATION_TO_FRIENDS, answers__answer="9" ).prefetch_related("answers") survey.first().answers.all() Now I expect only two of the answers (9). However, somehow my filter request is completely ignored. Do you see what I am doing wrong? >>> <QuerySet [Answer: 2, Answer: 9, Answer: 9, Answer: 10]> Answer model: class Answer(TimeStampedModel): question = models.ForeignKey( "surveys.Question", on_delete=models.CASCADE, related_name="answers" ) response = models.ForeignKey( "Response", on_delete=models.CASCADE, related_name="answers" ) answer = models.TextField(verbose_name=_("Answer")) choices = models.ManyToManyField( "surveys.AnswerOption", related_name="answers", blank=True ) -
App Configure - Module, not configured correctly? Help Divio
I'm using the Divio Platform to deploy a simple Django application and no matter i've done with this namespace, it's throwing an error. I have tried adding an init.py file in the folder, as well as out of the folder and i'm quite confused to be honest as I can't think how else my application would work. I've even tried renaming the folder, adjusting in main urls but nothing seems to be working. I have already reviewed the pep420 to see if it would help, also django but I think the issue is more towards Divio as folder structure goes like this. Might I know this is the first time im using this platform. ```urlpatterns = [ # Voyage application # path('/app', include('app.urls')), ] + aldryn_addons.urls.patterns() + i18n_patterns( # add your own i18n patterns here *aldryn_addons.urls.i18n_patterns() # MUST be the last entry! ) ``` django.core.exceptions.ImproperlyConfigured: The app module <module 'app' (namespace)> has multiple filesystem locations (['/app/app', './app']); you must configure this app with an AppConfig subclass with a 'path' class attribute