Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is django overkill for building a simple python-based local web app to control cameras on a network?
Disclaimer: I don't a whole lot about web app development, but i've been tasked with building one and I want to make sure i'm on the right path here. Goal: There are a bunch of cameras on a network and I want to build a local web app that allows the user to click on a button (there's a button for each camera) and it will trigger an alarm on that camera. The idea I had in mind: 1) First create the functionality to be able to connect to the camera and send the command to trigger the alarm 2) Next, start building a front end to make it look nice (I think this is the more intensive part). I planned on building the front end using python and django, but is django overkill for this? I read that bottle is a very simple web app framework, and I'm wondering if I should go with something smaller and more lightweight? -
AttributeError: 'NoneType' object has no attribute 'find', cache error
In my local environment the django development server works fine with no errors. When I run the app on a production environment with nginx & gunicorn I get this error: AttributeError: 'NoneType' object has no attribute 'find' This is the source of the error: if cache.get('ratings').find(name_input) == -1: result = food.objects.get(name = name_input) I have memcache imported: from django.core.cache import cache and in my settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } I expect the webpage to work without errors -
Session logout at random intervals while using django in the project
While I am doing some operation in my project the session will be logged-out automatically in the middle.I have used Angular-6 as front-end,django as back end technology. In the setting.py I have changed all possible value for SESSION_IDDLE_TIMEOUT. SESSION_IDLE_TIMEOUT = 30 * 60 -
Why am i getting ConnectionResetError: [WinError 10054] while running the server?
I am developing a website with Django. I get an error "ConnectionResetError: [WinError 10054]" while running a server. Despite that, everything continues to work as if there is no error at all. So is this error a problem? Should this problem be fixed before my project going into production? Traceback (most recent call last): File "C:\Users\Igor\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Igor\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Igor\AppData\Local\Programs\Python\Python37-32\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Igor\Desktop\django\berdyansk\venv\lib\site-packages\django\core\servers\basehttp.py", line 169, in handle self.handle_one_request() File "C:\Users\Igor\Desktop\django\berdyansk\venv\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Igor\AppData\Local\Programs\Python\Python37-32\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host``` -
Display ForeignKey field as simple input filed and show only the assigned choice as simple string
I try to display readonly information and would like to display the ForeignKey fields as simple strings, which display the current state of the model. I am aware of how to limit choices to only the one I need. However, it is still possible to chose between that choice and None (-----). Also I don't want a <select> field, I only want an <input> field Currently I solved it by defining extra fields in my ModelForm class and manually butchering everything together inside the HTML; as shown below. Well, that's rather horrible. class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: for field in self.fields: self.fields[field].required = False self.fields[field].widget.attrs['readonly'] = True self.fields['colour'] = { 'value': self.instance.batch_colour, } self.fields['type'] = { 'value': self.instance.shellfish_type, } self.fields['supplier'] = { 'value': self.instance.supplier, } class Meta: model = Batch fields = '__all__' If I use widgets and define CharField() I only get their IDs class Meta: model = Batch fields = '__all__' widgets = { 'colour': forms.CharField(), 'type': forms.CharField(), 'supplier': forms.CharField(), 'comment': forms.Textarea( attrs={ 'rows': 3, 'readonly': True, } ), } I also tried to overwrite the values in def __init__(self, *args, **kwargs): with the shown … -
Django: Query multiple models based on parent model
I'm creating a blog website in Django where I have a base model PostType which I then extend in to several subclasses for different types of content on the website. For example CodeSnippet and BlogPost. The idea is that these content types looks mostly the same, they all have an author, a title, a slug, etc, but they also have a few unique fields that I don't need to give all the content types. For example a blog posts has a field for the text content, while a code snippet has a related field for programming language. Something like this: class PostType(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) created = models.DateTimeField( auto_now_add=True, ) published = models.DateTimeField( null=True, blank=True ) modified = models.DateTimeField( auto_now=True, ) title = models.CharField( max_length=255, unique=True, ) slug = models.SlugField( max_length=255, unique=True, ) description = models.CharField( max_length=255, default='', ) class BlogPost(PostType): content = models.TextField( default='', verbose_name='Post Content' ) category = models.ForeignKey( to=Category, verbose_name='Category', on_delete=models.CASCADE ) class GitHubRepo(PostType): url = models.URLField( verbose_name='URL', unique=True ) class CodeSnippet(PostType): language = models.ForeignKey( to=Language, on_delete=models.CASCADE, ) code = models.TextField( verbose_name='Code' ) Now what I want to know is if there's any good/prefered way to query all objects in the database that are … -
Combine Q object and prefetch_related in Django?
I'm trying to implement a keyword search like so: keyword = request.GET['keyword'] books = Book.objects.all() books = books.filter( Q(title__contains=keyword) | Q(summary__contains=keyword) | Q(author__name__contains=keyword) | Q(author__biography__contains=keyword) | ) With the following models: class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField() summary = models.CharField() author = models.ManyToManyField('Author', through='BookToAuthor') class BookToAuthor(models.Model): id = models.AutoField(primary_key=True) book_id = models.ForeignKey('Book') author_id = models.ForeignKey('Author') class Author(models.Model): id = models.AutoField(primary_key=True) name = models.CharField() biography = models.CharField() Everything works as expected, but the query execution alone is taking a significant amount of time (10-15 seconds). I know I can use prefetch_related in order to cache/join the relational fields in Python and improve performance. But I'm having trouble getting this to work in combination with the (Q() | Q() ...) filtering. Any suggestions on how to incorporate prefetch_related? Or an alternative method that would improve performance? -
OperationalError at /profile/ (1054, "Unknown column 'users_profile.user_id' in 'field list'")
I have created a working update page and I can't access it and get this operational error! I can access other pages fine but not the update profile page. I have tried creating a new project and exporting all the code but it still doesn't work views.py request profile code @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, 'users/profile.html', context) forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] class UserUpdateForm(forms.ModelForm): email = forms.CharField(max_length=50) id = forms.CharField(disabled=True) phone_number = forms.CharField(max_length=30, required=False) first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) class Meta: model = User fields = ['username', 'email', 'id', 'phone_number', 'first_name', 'last_name'] models.py class UserUpdateForm(models.Model): id = models.CharField(max_length=30, primary_key=True) first_name = models.CharField(max_length=100, verbose_name='first name') last_name = models.CharField(max_length=100, verbose_name='last name') phone_number = models.CharField(max_length=100, verbose_name='phone number') email = models.CharField(max_length=100, verbose_name='email') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') class ProfileUpdateForm(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') This is the error code OperationalError at /profile/ (1054, "Unknown column … -
Find blocking function in python/django app
When serving a request my gunicorn worker times out. This is a big app and I'm not sure where it happens. Is there an easy way to log all function calls so I can see the last call in which it blocked? -
login_user issue when Sign Up on Django
I wrote some code for Register step, i made all the verification on my code in models.py, forms.py, views.py but when i try to signup i have an error i can't register the data in my database(postgresql)/ And i verified, there is non "login_user" in my code my app is called login. So this is my /login/models.py code: from django.db import models from django.core.validators import RegexValidator from django.contrib.auth.models import AbstractUser, PermissionsMixin # Create your models here. class User(AbstractUser, PermissionsMixin): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) otp = models.IntegerField(null=True) phone_regex = RegexValidator(regex=r'^[+][3][3][6-7][0-9]{8}$', message="Le numéro de téléphone doit être au format: +33xxxxxxxxx\ '0622920182 devient +33622920182'") phone = models.CharField(validators=[phone_regex], max_length=12) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) def __str__(self): return self.username This is the error i have : ERREUR: la relation « login_user » n'existe pas LINE 1: SELECT (1) AS "a" FROM "login_user" WHERE "login_user"."user... -
Cannot import views in Django (2.1.4, Python 3.7.0, Win 7)
I am building a site with django and cannot import views into my URL file. My URL file: from django.contrib import admin from django.urls import path from django.conf.urls import include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] Error: ImportError: cannot import name 'views' from 'blog' (..\blog\blog__init__.py) If I try "from blog import views", I get the same error. If I try "from blogapp import views" (blogapp is the name of the app within the blog foler), I get: RecursionError: maximum recursion depth exceeded while calling a Python object. Essentially, it bounces back and forth between line 23 in check_resolver (django\core\checks\urls.py) and line 397 in check (django\urls\resolvers.py). If I try just: "import views", I get "ModuleNotFoundError: No module named 'views'" My project structure: Main directory is "blog", contains two folders (blog and blogapp) as well as the db.sqlite3 and manage.py files. Subfolder blog contains pycache folder, and these files: init.py, settings.py, urls.py, wsgi.py. Subfolder blogapp contains pycache folder migrations folder, and these files: init.py, admin.py, apps.py, models.py, tests.py, views.py. Both blog and blogapp are in my INSTALLED_APPS in settings.py. I checked several similarly named questions (and their suggested answers) and could not figure out what is … -
Why is this code showing me the following error: ModuleNotFoundError: No module named 'cride'?
Im doing the platzi advanced django course. This course use docker-compose, the thing is, when i call "$docker-compose -f local.yml up" using the bash it shoms me the "ModuleNotFoundError : No module named 'cride'" i have no idea why this erros is happening version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: cride_local_django depends_on: - postgres volumes: - /c/users/jeanpython/desktop/cride/cride:/cride env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: cride_production_postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres redis: image: redis:3.2 celeryworker: <<: *django image: cride_local_celeryworker depends_on: - redis - postgres ports: [] command: /start-celeryworker celerybeat: <<: *django image: cride_local_celerybeat depends_on: - redis - postgres ports: [] command: /start-celerybeat flower: <<: *django image: cride_local_flower ports: - "5555:5555" command: /start-flower I expect the output to be "starting developming server at http://0.0.0.0:8000/" -
MacOS installing psycopg2
I run pip install psycopg2 and get errors. I've googled several things and click on the first 10 links but none relate to this specific error. (gymvantage) Matthews-MBP-3:gym-vantage matthewjdennis$ pip install psycopg2 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/23/7e/93c325482c328619870b6cd09370f6dbe1148283daca65115cd63642e60f/psycopg2-2.8.2.tar.gz Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error ERROR: Complete output from command /Users/matthewjdennis/gymvantage/bin/python3 -u -c 'import setuptools, tokenize;file='"'"'/private/var/folders/v3/8n09b4hd4xb5v4hp7pwv25lh0000gn/T/pip-install-y05e2olh/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/v3/8n09b4hd4xb5v4hp7pwv25lh0000gn/T/pip-record-9qk2q1lz/install-record.txt --single-version-externally-managed --compile --install-headers /Users/matthewjdennis/gymvantage/include/site/python3.7/psycopg2: ERROR: running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/compat.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/_lru_cache.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/init.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/errors.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.macosx-10.9-x86_64-3.7 creating build/temp.macosx-10.9-x86_64-3.7/psycopg gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.2 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=110003 -DHAVE_LO64=1 -I/Users/matthewjdennis/gymvantage/include -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -I. -I/usr/local/Cellar/postgresql/11.3/include -I/usr/local/Cellar/postgresql/11.3/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-x86_64-3.7/psycopg/psycopgmodule.o gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.2 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=110003 -DHAVE_LO64=1 -I/Users/matthewjdennis/gymvantage/include -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m … -
Wagtail - How To Remove Sub-Menu Items From Settings Menu
Wagtail includes a "settings" menu item by default, with some default settings items, such as "sites" and "redirects". I know that you can register a new setting with the register_setting decorator, and that various hooks are available for customizing the top level menu items, but not sub-menu items. How can I REMOVE (or hide the display of) the default settings items? -
How to turn a variable into a module with sys.modules hack?
import os from glob import glob from importlib import import_module from django.urls import re_path as _re_path, path as _path def _glob_init(name): name = name.replace('.', os.sep) path = os.sep + '**' modules = [] for module in glob(name + path, recursive=True): importable = os.path.splitext(module)[0].replace(os.sep, '.') if '__' in importable: continue try: module = import_module(importable) except ModuleNotFoundError: module = import_module(importable[:-1]) modules.append(module) return modules class UrlManager: def __init__(self, views_root): self.views_root = views_root self._url_patterns = [] def _path(self, route, kwargs=None, name=None, is_re=None): func = _re_path if is_re else _path def decorator(view): _view = view # keep the original view if isinstance(view, type): view = view.as_view() self._url_patterns.append( func(route, view, kwargs=kwargs, name=name or view.__name__) ) return _view return decorator def path(self, route, kwargs=None, name=None): return self._path(route, kwargs=kwargs, name=name, is_re=False) def re_path(self, route, kwargs=None, name=None): return self._path(route, kwargs=kwargs, name=name, is_re=True) @property def url_patterns(self): if isinstance(self.views_root, str): _glob_init(self.views_root) else: for root in self.views_root: _glob_init(root) return self._url_patterns Basic usage: # app.urls.py app_urls = UrlManager('app.views') # app.views.py from models import SomeModel from urls import app_urls @app_urls.path('foo/', name='foo') def view(request): return response # project.urls.py from django.urls import include from app.urls import app_urls urlpatterns = [ path('', include(app_urls.urlpatterns)) ] Okay, now: Everything works when you already have the migrations up and running, … -
How to Modify Emailfield in AbstractUser Model so that Email is Required
How to set emailfield to required when extending AbstractUser? I was wondering how to override the AbstractUser's emailfield model to set it as required. Currently my form list the email field but does not set as required. By default shouldn't all models be required? From the documentation it shows an example of how to set a field to required when creating a super user but I am not sure how to complete the task from the AbstractUser model without using AbstractBaseUser. model.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): display_name = models.CharField(max_length=50, unique=True) bio = models.CharField(max_length=500, blank=True, null=True) authorization_code = models.CharField(max_length=20) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta (UserCreationForm): model = CustomUser fields = ('username', 'email', 'display_name', 'authorization_code') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'bio') admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'display_name', 'bio'] list_display_links = ('username', 'display_name') fieldsets = ( (None, {'fields': ('username', 'display_name', 'email', 'bio', 'password')}), ('Permissions', {'fields': ('is_staff', … -
How to do a union of multiple queryset from a clickhouse ORM
In a Django search app, I want to query a clickhouse database (using the infi.clickhouse_orm library) for pairs of values such as (a=1 AND b>=1.5) OR (a=2 AND b>=1). In SQL this could be done with select * from table where a == 1 and b >= 1.5 UNION ALL select * from table where a == 2 and b >= 1 Looking at other exemples I have tried: With the queryset defined as qs = TABLE.objects_in(db) qs_1 = qs.filter(A__eq=1, B__gte=1.5) qs_2 = qs.filter(A__eq=2, B__gte=1) The | operator qs_union = qs_1 | qs_2 which returns unsupported operand type(s) for |: 'QuerySet' and 'QuerySet' The UNION operator qs_union = qs_1.union(qs_2) which returns 'QuerySet' object has no attribute 'union' and the Q objects qs_union = qs.filter(Q(A__eq=1, B__gte=1.5) | Q(A__eq=2, B__gte=1)) which returns 'Q' object has no attribute 'to_sql' From a clickhouse models, how do you perfom a union of 2, or more, queryset? Thanks! -
How to query 2 different tables with only one query in Django?
I have two models called One and Two. Both models have an attribute called producer. I am querying them using the following code: >>> from itertools import chain >>> from django.db import connection >>> producer = 'something' >>> a = One.objects.filter(producer=producer) >>> b = Two.objects.filter(producer=producer) >>> results = list(chain(a, b)) >>> len(connection.queries) 2 Unfortunately, this approach hits my database twice, as the length shows. How can I do this using just one single query. I have lots of different models, and I want to query them all at once in a view. Hitting the database once will greatly help performance. I have no need to sort anything, and the filters themselves are the same for all the models. -
Why executing form.is_valid() cause deleting of the instance fields that aren't in the form?
Suppose this view that is for edit record: def edit_post(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == "POST": form = AddPostForm(request.POST, request.FILES, instance=post) # 1 if form.is_valid(): # 2 new_post = form.save(commit=False) new_post.save() return redirect('administrator:view_admin_post') ... Now assume these: I have field1 that is exist in POST model. field1 has default value and suppose that the current value of field1 depends on previous. Also suppose that I don't want to pass the field1 to user. As a result, I will not have it in request.POST. In this situation when I write print(post.field1) In line # 1 I have previous value but when I print that in line # 2 I got None! What is going on?And how can I have my post.field1 ? Notice: I know I can define a middleware variable and save the previous value in this variable.But is there a better way to do this? -
Save of form in database
I try to fill in a standard form. Only the saving of the model does not work. It then changes to the default error page on save (). What could be the mistake? urls.py: path('user/ereignis/wohnungHinzufuegen', views.wohnungHinzufuegen,name="wohnungHinzufuegen"), models.py: class Wohnungseinheiten(models.Model): wohnungsnummer = models.AutoField(primary_key=True) strasseHausnummer = models.CharField("strasseHausnummer",max_length=100) adresszusatz = models.CharField("adresszusatz",max_length=100) plz = models.CharField("plz",max_length=100,blank=True) ort = models.CharField("ort",max_length=100) views.py: @login_required def wohnungHinzufuegen(request): if request.method == 'POST': form4 = WohnungHinzufuegenForm(request.POST) if form4.is_valid(): #Here he definitely goes in and fills in the test variables: tmpadresszusatz=form4.cleaned_data['strasseHausnummer'] #contains values tmpadresszusatz=form4.cleaned_data['adresszusatz'] #contains values try: form4.save() #this doesn't save -> it shows the default error page then except Exception as e: return HttpResponse(str("done."+e)) #returns never return HttpResponse(str("done."+tmpLogin +"|"+tmpPassword)) return redirect('user/ereignis') forms.py: class WohnungHinzufuegenForm(forms.Form): strasseHausnummer = forms.CharField(required=True,max_length=100) adresszusatz = forms.CharField(required=False,max_length=100) plz = forms.CharField(required=True,max_length=100) ort = forms.CharField(required=False,max_length=100) class Meta: model = Wohnungseinheiten fields = ('strasseHausnummer','adresszusatz','plz','ort') -
Django: How to Create Dependent Dropdown List
I want to create dependent drop-down menus, but I am unsure as to how to best implement the solution. Based on the value selected in the first drop-down menu, I want to populate the subsequent drop-down menus using that value in my query. Despite the work I have already completed, I am not returning any data after selecting a value in the first drop-down menu. Please let me know if there is any other information I may provide to better illustrate my problem. Models.py class Location(models.Model): city = models.CharField(max_length=50) company = models.ForeignKey("company", on_delete=models.PROTECT) def __unicode__(self): return u'%s' % self.name class Company(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return u'%s' % self.name Views.py def opportunities(request): companies = cwObj.get_companies() context = {'companies': companies} return render(request, 'website/opportunities.html', context) def new_opportunity(request): source = request.GET.get('selected_company') result_set = [] all_locations = [] string = str(source[1:-1]) selected_company = cwObj.get_locations(string) all_locations = selected_company for location in all_locations: result_set.append({'location': location}) return HttpResponse(json.dumps(result_set), mimetype='application/json', content_type='application/json') Opportunities.html <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script> <script> $(document).ready(function(){ $('select#selectcompanies').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' : country_name }; ajax('/new_opportunity',data,function(result){ console.log(result); $("#selectlocations option").remove(); for (var i = result.length - 1; i >= 0; i--) { … -
Is there a way to override the delete_selected method in ModelAdmin but keep confirmation?
I have: class Person(admin.ModelAdmin): actions = ['delete_selected'] def delete_selected(modeladmin, request, queryset): # Show confirmation page. for obj in queryset: obj.custom_delete() That comment I left there is where I'm struggling. I still want to show the confirmation page before I perform my custom delete. -
Importing Django 2.0 utility functions (vs. django 1.1)
I'm upgrading my application from Django 1.1 to Django 2.0. I understand from the documentation on utility functions in v.2.0: from django.core.urlresolvers import reverse needs to change to from django.urls import reverse But does this also apply to importing resolve? For example, should from django.core.urlresolvers import resolve be changed to from django.urls import resolve? -
Django - how to pass a list in the URL?
This is a beginners question...but here it goes. I have a url subject_owner?owner_ids=61,62,63 What should be the urls.py entry to forward this url to the attached view? I have tried few options...but none of them work and give an error back, the following will not work, but something similar to that should do the trick. url(r'^v1/subject_owner/(?P<owner_id>[a-z0-9]+)$', views.SubjectByOwnerViewSet.as_view({'get': 'list'})) -
how to connect url with the code saved in models.py
sorry the title is vague. so here's what I'm trying to do. the notification is displayed, and I want this notification to be inside tag href to post.get_absolute_url. I'm using django notification hq app, https://github.com/django-notifications/django-notifications. Here's my code class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, def save(self, *args, **kwargs): if self.post.author == self.author: super(Comment, self).save(*args, **kwargs) if self.post.author != self.author: notify.send(self.author, recipient=self.post.author, action_object=self.post, verb="commented on " + str(self.post.title), ) super(Comment, self).save(*args, **kwargs) class Post(models.Model): def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'pk': self.pk }) my html is {% live_notify_list %} and javascript of function fill_notification_list(data) { var menus = document.getElementsByClassName(notify_menu_class); if (menus) { var messages = data.unread_list.map(function (item) { var message = ""; if(typeof item.actor !== 'undefined'){ message = item.actor; } if(typeof item.verb !== 'undefined'){ message = message + " " + item.verb; } if(typeof item.target !== 'undefined'){ message = message + " " + item.target; } return '<li>' + message + '</li>'; }).join('') for (var i = 0; i < menus.length; i++){ menus[i].innerHTML = messages; } } }