Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail/Django translations not showing
I am trying to develop bilingual Wagtail site, and having problems getting translations work. Translations compiled fine to myproject/myproject/locale/fi/LC_MESSAGES/django.mo however, translations in my templates don't show. also when i do, >>> from django.utils.translation import activate >>> from django.utils.translation import get_language >>> get_language() 'en-us' >>> activate("fi") >>> get_language() 'fi' >>> ugettext("PHOTOS") 'PHOTOS' settings file: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] LANGUAGES = ( ('en', _('English')), ('fi', _('Finnish')), ) LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(PROJECT_DIR, 'locale'), ) django.po: #: .\mysite\templates\base.html:63 msgid "PHOTOS" msgstr "KUVIA" base.html: {% trans "PHOTOS" %} any ideas how to troubleshoot further? -
ImproperlyConfigured at /admin/aldryn_newsblog/article/add/
Trying to follow the tutorial for integrating Django CMS into an existing application, Im also using cookiecutter. (the "project" is my homework) After installing aldryn-newsblog I have been stuck on the following error for quite some time : ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Request Method: GET Request URL: http://localhost:8000/admin/aldryn_newsblog/article/add/ Django Version: 2.1.5 Exception Type: ImproperlyConfigured Exception Value: ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Here is my backlog : Environment: Request Method: GET Request URL: http://localhost:8000/admin/aldryn_newsblog/article/add/ Django Version: 2.1.5 Python Version: 3.6.8 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_awesome_project.users.apps.UsersConfig', 'djangocms_admin_style', 'django.contrib.admin', 'cms', 'menus', 'treebeard', 'sekizai', 'filer', 'easy_thumbnails', 'mptt', 'djangocms_text_ckeditor', 'djangocms_link', 'djangocms_file', 'djangocms_picture', 'djangocms_video', 'djangocms_googlemap', 'djangocms_snippet', 'djangocms_style', 'djangocms_column', 'polls', 'polls_cms_integration', 'aldryn_apphooks_config', 'aldryn_boilerplates', 'aldryn_categories', 'aldryn_common', 'aldryn_newsblog', 'aldryn_people', 'parler', 'sortedm2m', 'taggit', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', 'cms.middleware.utils.ApphookReloadMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: Exception Type: ImproperlyConfigured at /admin/aldryn_newsblog/article/add/ Exception Value: ImportError my_awesome_project.users.apps.UsersConfig: No module named 'my_awesome_project.users.apps.UsersConfig'; 'my_awesome_project.users.apps' is not a package Running : django-cms 3.6.0 Django 2.1.5 alabaster 0.7.12 aldryn-apphooks-config 0.5.2 aldryn-boilerplates 0.8.0 aldryn-categories 1.2.0 aldryn-common 1.0.5 aldryn-newsblog 2.2.1 aldryn-people 2.2.0 aldryn-translation-tools 0.3.0 … -
How to delete the current profile Image while uploading the new image of a authenticated user in django
I want to delete the existing profile image( named as profile_pic in models.py) while uploading the new profile pic of a authenticated user.. Below is the code samples of views.py , forms.py and models.py How to implement the functionality to delete the existing image while uploading new one in views.py or forms.py views.py class UpdateUserProfilePic(UpdateView): template_name = 'accounts/signup.html' form_class = forms.UserProfilePicUpdateForm success_url = reverse_lazy('test') def get_object(self): return self.request.user ---------x-------------------------------------------- forms.py class UserProfilePicUpdateForm(forms.ModelForm): class Meta: model = User fields = ('profile_pic',) ---------x-------------------------------------------- models.py class User(AbstractBaseUser): ....... ....... profile_pic = models.ImageField( upload_to='profile_pics', default='default-profile.png') ....... -
How do I send a value of a variable from view to form in django?
I want a customized dropdown list as a choice field for a variable. This list depends on another variable in form How can I send a variable value to the variable in forms views.py z= somelist class HomeView(TemplateView): template_name='charts.html' form = HomeForm(z = z) def get(self, request): form = HomeForm() return render(request, self.template_name, {'form':form}) def post(self,request): form=HomeForm(request.POST) if form.is_valid(): text_11 = form.cleaned_data['post11'] global e e=text_11 text_1 = form.cleaned_data['post_1'] global z z=text_1 text = form.cleaned_data['post'] global b b=text text1 = form.cleaned_data['post1'] global c c=text1 text2 = form.cleaned_data['post2'] global d d=text2 args = {'form':form, 'text_11':text_11,'text_1':text_1,'text':text, 'text1':text1, 'text2':text2} return render(request, self.template_name, args) my forms.py class HomeForm(forms.Form): post11=forms.ChoiceField(choices=((None,None),('लिंग :','sex :'),('शिक्षण:','education:'))) post_1 = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=**somelist**) post = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'))) post1 = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'))) post2 = forms.ChoiceField(choices=((None,None),('bar','bar'),('horizontalBar','horizontalBar'))) I want the variable to be here post_1 = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=**somelist**) Thanks in advance :) -
Django save aggregation in master/detail (many to one relationship)?
I have two models, Order and OrderRow (1:n). What I would like is when something changes on the OrderRow (added, removed, price change, etc.) that that "effect" is calculated to the parent Order. In this case, sum the total of all the OrderRow in Order. The OrderRow (a admin.TabularInline subclass) is setup as inlines on Order. I did implement the django.db.models.signals.post_save but the problem here is that the Order post_save is fired before the OrderRow updates. Is there any nice way (besides implementing a db trigger) for updating this the 'django-way' ? All this under Django Admin -
How can I create a model in django that has a foreign key to one of multiple models?
I want to create a foreign key that can have a reference to exactly one of three other models. example: user fav_animal: foreign_key(bear, cat, dog) bear name cat name dog name How can I achieve this in django? Do I just create 3 nullable foreign keys? Then how do I enforce that always exactly one of them is set? -
How can I generate a rest viewset for all child models based on a parent model
I have the following models based on a shared base model: class Pet(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey('auth.User', related_name='pet', on_delete=models.CASCADE) name=models.CharField(max=100) class Meta: abstract = True ordering = ['-created'] def __str__(self): return str(self.id) class Dog(Pet): legs = models.BigIntegerField() class Bird(Pet): wings = models.BigIntegerField() cage = models.BigIntegerField() Now I would like to get a rest ViewSet that looks like this when I ask for a User: { username: "PeterSchmidt" email:"ps@gmail.com" pets{ { name="shaggy" type="dog" legs=4 } { name="Jaques" type="bird" wings=2 cage=1 } } } Basicly I want a way of having a baseclass model that has its own viewset (multiple serilizers are fine) that I can just use to get all the pets no matter what type they are. Can this be done within standard django rest? -
Why do i get an error when creating a charge with Stripe API in django?
I have a e-commerce app, where after a checkout i handle a payment with the following class-based payment view. But every time i submit a form and create a charge in a try block, it results in the Exception. Stripe secret and public keys are provided in settings, before a view i have '''stripe.api_key = settings.STRIPE_SECRET_KEY''' line. HTML, CSS and JS code was copied from Stripe documentation. class PaymentView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) except Order.DoesNotExist: messages.error(self.request, "You do not have an active order") return redirect('cart') context = { 'payment_option': self.kwargs['payment_option'] } return render(self.request, "payment2.html", context) def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST['stripeToken'] amount = int(order.get_total_price() * 100) # cents user = self.request.user try: charge = stripe.Charge.create( amount=amount, currency='usd', description='Example charge', source=token, ) payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total_price() payment.save() order.ordered = True order.ordered_date = datetime.datetime.now().date() order.payment = payment order.save() messages.success(self.request, "Your order was successful") return redirect("/") except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, … -
Django in docker cookiecutter - can't send email
I have following docker file version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_caddy: {} ghotel_cc_production_static_vol: {} services: django: &django restart: always build: context: . dockerfile: ./compose/production/django/Dockerfile image: ghotel_cc_api_production_django volumes: - production_static_vol:/app/static depends_on: - postgres env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start postgres: restart: always build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: api_production_postgres volumes: - production_postgres_data:/var/lib/postgresql/data - production_postgres_data_backups:/backups env_file: - ./.envs/.production/.postgres caddy: restart: always build: context: . dockerfile: ./compose/production/caddy/Dockerfile image: api_production_caddy depends_on: - django volumes: - production_caddy:/root/.caddy - ghotel_cc_production_static_vol:/app/static env_file: - ./.envs/.production/.caddy ports: - "0.0.0.0:8550:80" The problem is that email cannot be sent. There is no errors, Django part works well - i see correct output in console. But after Django sends email it is just lost - never arrives to recipient. How to correctly configure docker so the email can be sent ? -
drf-yasg - testproj - how to silent all the debug output
How can I silent the debug statements for drf-yasg - testproj ? https://github.com/axnsan12/drf-yasg This is how I set it up: $ git clone https://github.com/axnsan12/drf-yasg.git $ cd drf-yasg $ virtualenv venv $ source venv/bin/activate (venv) $ cd testproj (venv) $ python -m pip install -U pip setuptools (venv) $ pip install -U -r requirements.txt (venv) $ python manage.py migrate (venv) $ python manage.py runserver (venv) $ firefox localhost:8000/swagger/ But it keeps producing a lot of debug prints which makes it difficult for me test certain features. How do I silent these debug prints ? Thanks. Here are the debug prints: 2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/coreapi/exceptions.py first seen with mtime 1568447198.368635 2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/relations.py first seen with mtime 1568447200.446008 2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/requests/certs.py first seen with mtime 1568447203.023515 2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/coreapi/compat.py first seen with mtime 1568447198.368073 2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/utils/model_meta.py first seen with mtime 1568447200.529353 2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/django/contrib/auth/middleware.py first seen with mtime 1568447201.356465 2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/renderers.py first seen with mtime 1568447200.446478 -
Django Pyinstaller .EXE gives me ModuleNotFoundError: No module named 'app.urls'
I am trying to run a Django project using an EXE file compiled using Pyinstaller. But when I run the compiled .EXE file using this command I get ModuleNotFoundError: No module named 'app.urls' and another OsError: [WinError 123]. I will explain how I setup this stuff later. Here is the full error when I run the .EXE file: C:\Users\omen\Desktop\dist\dj>dj.exe runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "threading.py", line 917, in _bootstrap_inner File "threading.py", line 865, in run File "site-packages\django\utils\autoreload.py", line 54, in wrapper File "C:\Users\omen\Desktop\dist\dj\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "site-packages\django\core\management\base.py", line 390, in check File "site-packages\django\core\management\base.py", line 377, in _run_checks File "site-packages\django\core\checks\registry.py", line 72, in run_checks File "site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique File "site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces File "site-packages\django\utils\functional.py", line 80, in __get__ File "site-packages\django\urls\resolvers.py", line 584, in url_patterns File "site-packages\django\utils\functional.py", line 80, in __get__ File "site-packages\django\urls\resolvers.py", line 577, in urlconf_module File "importlib\__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "C:\Users\omen\Anaconda3\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module exec(bytecode, module.__dict__) File … -
Angular: differentiate between sessions in different tabs
I'm developing a web application. The front end is with Angular and back-end is a Rest API with django rest framework. For some customer requirements, I need that the django rest api is able to differentiate between polling requests with a sessionid. After some searches I found that I can identify the session in the REST API side with the value of: request.session.session_key But that isn't the best choice, because for two different tabs I get the same session_key and the desired sessionId that the rest api receives in the request should identify session for specific tab. So not sessionid for different PCs and host IP address, or browsers only, but also it should get two different sessionids for two different tabs. Does django request object contain other id to identify host tabs? I guess that the solution can be found in Angular side. Is there a way in Angular and typescript to identify tabs sessions? -
Django annotation with multiple rows in Subquery , is it possible?
I have a a question regarding annotation. Firstly, I have 2 related models, that are used in annotation subquery. Secondary model. class UserBriefcaseAttribute(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_briefcase_attributes') briefcase_attribute = models.ForeignKey( BriefcaseAttribute, on_delete=models.CASCADE, related_name='+' ) amount = models.IntegerField(default=0) and primary mode for this one class BriefcaseAttribute(models.Model): code = models.CharField(max_length=45) display_name = models.CharField(max_length=45) basically I want to do something like this: SomeModel.objects.filter(**filtering).annotate( result = Subquery(UserBriefcaseAttribute.objects.filter(user=self.request.user, briefcase_attribute__code__in=('silver', 'gold', 'black')).values(‘amount’)) ) Obviously, it doesn't work as subquery returns 3 rows instead of one. I dont know how to deal with it, tried a lot of things already. Expected result should be something like: {‘silver’: 30, ‘gold’: 20, ‘black’: 8} for example or any structure that would be possible to use in DRF serializer Dictfield, or JsonField or Lisfiled or any appropriate field that would be able to render pairs of code: amount (read_only=True). It is possible to do it in separate query but I would prefer to do it via annotation somehow to have only one query. Thanks. -
Wrong url in pagination. Django
I want to search by two fields (q1 and q2): home.html <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>RU</option> <option>Ukraine</option> <option>USA</option> </select> <button> Search </button> </form> When I click "search" I go to http://127.0.0.1:8001/search/?q=mos&q2=RU (it's OK) Then I click "next". I go to http://127.0.0.1:8001/search/?city=2&q=mos&q2=%20RU (ERROR: "Page not found) but I want http://127.0.0.1:8001/search/?city=2&q=mos&q2=RU How can I fix it? Why do I have "%20" ??? search results.html <h1>Search Results</h1> <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/search?city={{ page_obj.previous_page_number }}&q={{ query }}&q2= {{query2}}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="/search?city={{ page_obj.next_page_number }}&q={{ query }}&q2= {{query2}}">next</a> {% endif %} </span> </div> models.py from django.db import models class City(models.Model): name = models.CharField(max_length=255) state = models.CharField(max_length=255) COUNTRY = ( ('RU', 'Russia'), ('UKR', 'Ukraine'), ('US', 'USA'), ) category = models.CharField(max_length=100, choices=COUNTRY, default='RU') class Meta: verbose_name_plural = "cities" def __str__(self): return self.name urls.py urlpatterns = [ path('search/', SearchResultsView.as_view(), name='search_results'), path('', HomePageView.as_view(), name='home'), path('city/<int:pk>/', views.city_detail, name='city_detail'), ] views.py class HomePageView(ListView): model = City template_name = 'cities/home.html' … -
Error in Dockerizing Django react app together
I have successfully dockerized my Django app but going through the trouble to dockerized my react app that connected with Django apps. this is my Dockerfile below # Pull base image FROM python:3 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory, we can name it whatever we want WORKDIR /djangobackend # Install dependencies # Copy requirement file from the docker workdir we defined named djangodocker COPY requirements.txt /djangobackend/ RUN pip install -r requirements.txt # Copy project COPY . /djangobackend/ and this is my docker-compose.yml file version: '3.2' services: db: image: postgres:10.1-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /djangobackend/backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/djangobackend ports: - 8000:8000 depends_on: - db volumes: postgres_data: Above everything working fine. Later, I tried to dockerize react like below: Dockerfile below: # Pull base image FROM python:3 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory, we can name it whatever we want WORKDIR /djangobackend # Install dependencies # Copy requirement file from the docker workdir we defined named djangodocker COPY requirements.txt /djangobackend/ RUN pip install -r requirements.txt # Copy project COPY . /djangobackend/ # Use an official node runtime as a parent … -
How to fix this attribute object has no attribute error in django?
i am trying to learn django from https://docs.djangoproject.com/en/2.2/intro/tutorial02/ and i got an attribute error AttributeError: 'Question' object has no attribute 'question_text' as i typed Question.objects.all() the models.py is from django.db import models class Question(models.Model): # ... def __str__(self): return self.question_text class Choice(models.Model): # ... ``def __str__(self): return self.choice_text please help me to solve this issue and i coded as same as Playing with api -
How to update foreign keys in a nested resource with django?
I have two resources in a Django rest framework. Author and books. An author can have up to 3 books in a nested resource. Both resources are created independently and an author can later be assigned to book. My question is how to i represent this assign relationship? I have two main endpoints "author": "http://127.0.0.1:8100/author/", "books": "http://127.0.0.1:8100/book/" For basic CRUD operations. I'm currently trying to assign books to authors like this "author": "http://127.0.0.1:8100/author/{pk}/books" #views.py class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer @action(detail=True, methods=['post'], url_name='books', url_path='books') def assign(self, request, pk=None): author = self.get_object() serializer = Author(data=request.data) if serializer.is_valid(): author.assign_worker(serializer.data['books']) author.save() return Response({'status': 'books assigned'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And i have the following models class Books(models.Model): title = models.CharField(max_length=225) description = models.TextField() author = models.ForeignKey( 'Author', blank=True, null=True, on_delete=models.CASCADE, related_name='books') class Author(models.Model): name = models.CharField(max_length=225) Bio = models.TextField() birthday = models.DateField() Serializers class BookSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Books fields = ("title", "description", "authors") class Author(serializers.HyperlinkedModelSerializer): books = serializers.PrimaryKeyRelatedField(queryset=Books.objects.all(), many= True) class Meta: model = Author fields = ("name", "bio", "birthday", "books") I created an author with this { # "id":"4" "name":"John Smith", "bio":"He was a good man", "birthday":"1970-12-12" } And i created a book with this { #"id":"2" "title":"The … -
Custom Django Model Form Field that Aggregates Multiple Instances of an Input
I have created a custom field in a model form that I want to use to enable users to enter multiple instances of inputs into. For example, the custom field is a series of values that corresponds to multiple dates. Once the form is submitted I want to consolidate all of those values into a string and store them in a single database field. See code below. The cleaned_data fields are empty when I add multiple values to the inputs. I think I need to access the input data before it is passed to cleaned_data, but I'm not sure how. Any assistance would be appreciated. #forms.py class UpdateModelForm(forms.ModelForm): custom_field = forms.CharField() class Meta: model = Model def clean_custom_field(self): custom_field = self.cleaned_data['custom_field'] return custom_field def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #I've tried to access the input fields here without success #views.py class ModelView(UpdateView): model = Model form_class = UpdateModelForm template_name = 'model_edit.html' def form_valid(self, form): #not sure what to put here #model_edit.py <body> <form action="" method="post">{% csrf_token %} <table> <thead> <tr> <th>Amount</th> </thead> <tbody> {% for i in '12345'|make_list %} <tr> <td> {{form.custom_field}} </td> </tr> {% endfor %} </tbody> </table> </form> </body> -
How to build chained filter in django admin dashboard
I want chained filter in django-admin dashboard,Please help me to achieve it. I have 3 models:- Board, Grade and Chapter. Initially when dashboard loads then only board filter should appear and after selecting board filter the selected boards all filter should appear and after selecting grade all chapters of that grade should appear. I have tried RelatedDropdownFilter, but thats just normal, it does not modify the view part of dropdownfilter, It shows all results. My models:- class LmsBoard(models.Model): name = models.CharField(max_length=240) class LmsGrade(models.Model): name = models.CharField(max_length=240) board = models.ForeignKey(LmsBoard, models.DO_NOTHING) class LmsSubject(models.Model): name = models.CharField(max_length=240) grade = models.ForeignKey(LmsGrade, models.DO_NOTHING) board = models.ForeignKey(LmsBoard,models.DO_NOTHING) class LmsChapter(models.Model): name = models.CharField(max_length=240,default='None') subject = models.ForeignKey(LmsSubject, models.DO_NOTHING) My admin.py:- @admin.register(MyModel) class MyModel(admin.ModelAdmin): list_display = ( 'board', 'grade', 'chapter',) list_filter = ( ('board',RelatedDropdownFilter), ('grade', RelatedDropdownFilter), ('chapter', RelatedDropdownFilter), I am expecting the filter should appear one by one and should contain the filter list of last selectected item. -
'DeferredAttribute' object has no attribute 'startswith'
I keep on getting this error message and do not know how to fix this,.. This message shows up when I log in with stored id and password. Please help! dfasfsfsfdsfsfsfsdfasfsfdsfsdfsd dfsfdsfasdfsafsfdsafdsfsdfdsfsdsdf dsfdsfsdfsdafsafdsdfsafsdf sdafasfdsafsdafsdfdsfds models.py from __future__ import unicode_literals from django.db import models # Create your models here. class seanyorder(models.Model): customer = models.ForeignKey('seany_user.seanyuser', on_delete=models.CASCADE, verbose_name='customer') product = models.ForeignKey('seany_product.seanyproduct', on_delete=models.CASCADE, verbose_name='product') def __str__(self): return str(self.customer) + ' ' + str(self.product) class Meta: db_table = 'seany_order' verbose_name = 'order' verbose_name_plural = 'order' url.py from django.conf.urls import url from django.contrib import admin from seany_user.views import index, registerview, loginview urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index), url(r'^register/$', registerview.as_view()), url(r'^login/$', loginview.as_view()) ] view.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.views.generic.edit import FormView from django.shortcuts import render from seany_user.forms import registerform,loginform # Create your views here. def index(request): return render(request, 'index.html', { 'email': request.session.get('user') }) class registerview(FormView): template_name = 'register.html' form_class = registerform success_url = '/' class loginview(FormView): template_name = 'login.html' form_class = loginform success_url = '/' def form_valid(self, form): self.request.session['customer'] = form.email return super().form_valid(form) error message AttributeError at /login/ 'DeferredAttribute' object has no attribute 'startswith' Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 2.2.5 Exception Type: AttributeError Exception Value: 'DeferredAttribute' object … -
Reload only MultipleChoiceField of dajngo on jquery load
I have a popup-modal in the page to add new data with ajax, after the data is added i have to bring it to the django multichoicefield widget if I try it to bring it in selected portion it is dispalyed and works on submission but after that if user select and bring another data to selected side the one i have added will get destroyed it doesn't compile with the original data that are loaded. I also try to refresh only that portion to again load whole data so that it compile with js function. But now the multichoicefield will not construct through JS and will not display properly. Both of my method I can't work properly, I have changed little js of admin SelectFilter2 to load it in my popup-modal while ajax call that has worked but i didn't get what is causing js not to work on jquery load or addition of new data. Method 1: I append the data to selected side on ajax success $('#id_Course_Group_to').append(`<option value="`+ response.pk + `" title="` + id_InningGroup_Name + `" selected>` + id_InningGroup_Name + `</option>`); This data will not function like other data which are preloaded it will just disappear if … -
What does '|' in {{ services|pprint|safe }} mean in django?
I know that in views.py file: def index(request): person= {'firstname': 'Craig', 'lastname': 'Daniels'} weather= "sunny" context= { 'person': person, 'weather': weather, } return render(request, 'Articles/greeting.html', context) Then we can do in greetings.html: <h1>Hi {{ person.firstname }} {{ person.lastname }}</h1> <h1>Today it is {{ weather }}</h1> where {{ person.firstname }} is a variable defined in context. But what does '|' mean? {{ services|pprint|safe }} -
Is it possible to deploy django 2.2 on Google cloud engine?
I just began to learn Django recently. I am trying to deploy a django project on google cloud engine. But I stuck when following tutorial on google: https://cloud.google.com/python/django/appengine when I type: python manage.py makemigration I got: following error: mysqlclient 1.3.13 or newer is required; you have 0.9.3. After short research, aparently, I can't install mysqlclient 1.3.13 on Django 2.2 yet?? Is this a mistake? Am I missing something? Can I use mysqlclient 1.3.13 on django 2.2 ? Thank you for your time. -
assertEqual fails in Django test view
I'm testing whether the view returns in the context object all the database models that I've saved. The models actually render in the templates when the site is running but having had problems rendering them in the past, I need the view test to help with debugging. So the test collects then saves the site url to the variable resp using Client. I then assertTrue that the key value passed in the context exists. Then - and this is where the problem lies - i attempt to assetEqual that what's in the context object matches whats in my database and this is the resulting traceback: File "/Users/Sol/src/projects/portfolio/python_website/main/tests_models.py", line 24, in check_context_obj self.assertEqual(resp.context['projects'], Project.objects.all()) AssertionError: <Quer[20 chars] App>, <Project: Folium Web Map>, <Project: Personal Webiste>]> != <Quer[20 chars] App>, <Project: Folium Web Map>, <Project: Personal Webiste>]> You'll notice after the AssertionError the the values either side of the != operator are actually exactly the same (I actually checked that their types are the same). Here are my files: tests_views.py from django.test import TestCase from main.models import Project from django.urls import reverse def check_context_obj(self): url = reverse('site_index') resp = self.client.get(url) self.assertTrue(resp.context['projects']) self.assertEqual(resp.context['projects'], Project.objects.all()) views.py from django.shortcuts import get_object_or_404, render from main.models import … -
What is the difference between “return my_view” and “return redirect(my_view)” and how to get a mixed result?
I have a home in which I have a form that I get some info from students to suggest them some programs to apply to. The home view is as below: def home(request): template_name = 'home.html' home_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some stuff return programs(request) else: my_form = MyModelForm() home_context.update({'my_form': my_form, }) return render(request, template_name, home_context) In the second view, I have the same form and I want this form to be pre-occupied with the information I entered in the home page. That is why in the above, I passed my POST request to programs view that is as below: def programs(request): template_name = 'programs.html' programs_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some other stuff else: my_form = MyModelForm() programs_context.update({'my_form': my_form, }) return render(request, template_name, programs_context) The drawback of this strategy (passing the POST request in the home view to the programs_view) is that the url in url bar does not change to 'example.com/programs' and stays as 'example.com' . I will have some problems including problems in pagination of the programs. The alternative is that I do this: def home(request): template_name = 'home.html' home_context = {} if request.POST: …