Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Yubikey OTP via Yubicloud not working in DJANGO behind nginx
Using the package django-otp-yubikey to provide Yubikey 2FA for the admin panel in a DJANGO application works without any problems when using GUNICORN, but as soon as we using GUNICORN and NGINX in front of it, the package doesn't work anymore. Tried contacting different versions of the Yubicloud API (1, 1.2, 2). Also tried contacting them with SSL disabled / enabled. This is the nginx configs: location /...../ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/home/../.../...sock; allow X.X.X.X; deny all; } Getting a 504 gateway timeout when NGINX is in front of the django application, making me believe it might be blocking a the request made to the yubicloud servers. -
Filtering data before rendering- django-filters
I am using django-filters, and i want that data only with status = 1 should be displayed. I will not be showing status in my diplayed table. filters.py class ActiveSimFilter(django_filters.FilterSet): type = django_filters.CharFilter(field_name='name', lookup_expr='icontains') phone_number = django_filters.CharFilter(field_name='phone_number', lookup_expr='icontains') class Meta: model = Sim fields = { } order_by = ["type"] def get_initial_queryset(self): return Sim.objects.exclude(sim_status=1) -
Containerized nginx server return 503 error
I am trying to use nginx as a reverse proxy for running multiple web apps. My files' contents are as below: Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 ENV APP_ROOT /mysite/subdomain.mysite ENV PROD True ADD requirements.txt /requirements.txt ADD Pipfile /Pipfile ADD Pipfile.lock /Pipfile.lock RUN pip install pipenv RUN pipenv install --system --deploy --ignore-pipfile RUN pip install --upgrade pip RUN mkdir -p ${APP_ROOT} WORKDIR ${APP_ROOT} ADD . ${APP_ROOT} COPY mime.types /etc/mime.types EXPOSE 8001 RUN if [ -f manage.py ]; then python manage.py collectstatic --noinput; fi CMD ["gunicorn", "-b", "0.0.0.0:8001", "subdomain.wsgi"] docker-compose.yml: version: "3.7" services: postgres: container_name: subdomain-postgres image: postgres:9.6 ports: - 5432:5432 volumes: - ./pgdb:/var/lib/postgresql/data # .env file contains postgres username, database name and password env_file: .env webapp: container_name: subdomain build: . restart: "always" env_file: .env environment: - VIRTUAL_HOST=subdomain.mysite.com,www.subdomain.mysite.com - VIRTUAL_PORT=8001 - TIMEOUT=300 - HTTP_PORT=8001 - STATS_PORT=8046 volumes: - .:/subdomain.mysite ports: - "8001:8001" depends_on: - "postgres" networks: default: external: name: nginx-proxy As you see from above files I am running services postgres and webapp that are built on python image. My web app is a django project and .env file referenced in above docker files just contain postgresql related variables (username, database name, password and etc.). As of nginx-proxy network, it is … -
I'm not getting all the records for specific month
I'm trying to get all the posts from each month, like July has 11 and August has 1. But at this point when it loops I'm getting one of each month. This will be the result: 2019 Aug (1) Time Lapse Video vs. Time Lapse Photo Test Jul (11) A simple Tutorial about how to add Facebook login in your website. This is my code on the template: {% regroup events by timestamp.year as year_list %} {% for year in year_list %} {{ year.grouper }} {% regroup events by timestamp.month as month_list %} {% for month in month_list %} {{ month.list.0.timestamp|date:"M"}} ({{ month.list|length }}) {% for post in events %} {% if post.timestamp == month.list.0.timestamp %} {{post.title}}<br> {% endif %} {% endfor %} {% endfor %} {% endfor %} I expect to get the rest of month of July. thank you. -
A tourist place can have multiple themes. How to implement this in django models?
This is my current django models . How can I store multiple Themes for a place name Themes are like adventure , beaches , heritage , hill stations etc A place can be both under adventure , beaches from django.db import models class places(models.Model): place_id = models.AutoField(primary_key=True) place_name = models.CharField(max_length=50) city = models.CharField(max_length=50) state = models.CharField(max_length=50) country = models.CharField(max_length=50) description = models.TextField() theme = models.ForeignKey('Theme',on_delete=models.CASCADE) class Theme(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name -
ModuleNotFoundError: No module named 'AppName' in Django
I did install django in server. Instead of installing apps next to the django project folder, I installed them inside the django project folder. (I put them next to the settings.py and wsgi.py) This is structure of django project: BaseFile |__django | |___administrator | | |___ views.py | | |___ urls.py | | |___ ... | | | |___blog | | |___ views.py | | |___ urls.py | | |___ ... | | | |___ __init__.py | |___ settings.py | |___ urls.py | |___ wsgi.py | |___ env |___ manage.py |___ media |___ static |___ templates And this is my settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # MY APPS: 'administrator.apps.AdministratorConfig', 'blog.apps.BlogConfig', ] And when I want to makemigrations I got this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "BaseFile/env/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "BaseFile/env/lib64/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "BaseFile/env/lib64/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "BaseFile/env/lib64/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "BaseFile/env/lib64/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, … -
How to show live sensor data using django
I have a production Django application that is being used to view a dashboard of sensor data. Currently my sensors are sending their values to my database via Django REST framework. So I am passing the sensor values in JSON format using python requests, which then saves a record each time it receives the data. This works well when I am sending sensor data every 30 minutes, however I want to see certain sensor data as real-time as reasonable. Would it be practical to keep my existing setup, but just post the sensor data every 2 seconds, and use AJAX to update the page every 2 seconds? Or should I be taking a completely different approach here. Any help is appreciated! -
How to pass extra context (which is base on filtered qs) to django's change list admin view?
Here is how to pass extra context: Django how to pass custom variables to context to use in custom admin template? But what if I need to calculate extra context based on filtered queryset? Django calculates queryset inside changelist_view and doesn't allow to touch that qs afterwards. My current solution is to copy-paste django's changelist_view and inject hook with extra_context_2 which can be calculated based on queryset. But for obvious reasons it's bad approach. Any other ideas? -
AttributeError: 'tuple' object has no attribute 'get'
I have a problem in Django, I really don't know what the error is. The error happens in an UpdateView view, when putting severalinputs in the view, to know precisely where the error is, because I did not find it, the error does not happen in the view as such, I think it is the form : class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['title', 'subtitle', 'image', 'description', 'status'] widgets = { 'title': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Titulo'}), 'subtitle': forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Subtitulo'}), 'image': forms.FileInput(attrs = {'class': 'custom-file-input'}), 'description': forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Descripcion'}), 'status': forms.Select(attrs = {'class': 'custom-select'}), } labels = {'title': '', 'subtitle': '', 'image': '', 'description': ''} def __init__(self, *args, **kwargs): self.title_valid = False if 'title_valid' in kwargs: self.title_valid = kwargs.pop('title_valid') super().__init__(args, kwargs) def clean_title(self): title = self.cleaned_data['title'] if self.title_valid: if Course.objects.filter(title = title).exists(): raise forms.ValidationError('Ya existe un curso registrado con ese titulo, elige otro.') return title I could also see that the clean_title method is not executed, layers there the error happens ... View: class CourseUpdateView(UpdateView): model = Course form_class = CourseForm template_name = 'instructor/course_update_form.html' success_url = reverse_lazy('instructor:course:list') success_message = 'Se modificó con éxito el curso "{}".' def get_form(self, form_class … -
Keeping items per page static while paginating
I posed a question and got a quick response (thanks, Bob!) on how to do pagination in Django: Change value for paginate_by on the fly However, as outlined below, I'm having an issue getting the items per page to remain set. I modified my ProdListView.html template to show buttons with page numbers, but, while it works, I'm getting an odd behavior. I have a for loop that I use to put out the page numbers as buttons: {% for i in DataPaginated.paginator.page_range %} {% if DataPaginated.number == i %} <button class="w3-button w3-amber">{{ i }} </button> {% else %} <a href="?page={{ i }}" class="w3-button">{{ i }}</a> {% endif %} {% endfor %} If the pagination is set to the default of ten this works properly and shows three pages (there are 24 items). If I change the pagination to 20, it looks correct at first and shows two pages. However, if I click on the second page, it changes my pagination back to 10, shows three pages again, and places me on the 2nd of the three pages. In the interest of space, you can find the code I'm using in the views.py file and template file, besides the fragment above, … -
Need help on nested Django Rest Framework
I am working on DRF first time and got stuck at one place. This is just a hypothetical example related to issue I am facing: models.py class Manufacturer(models.Model): manufacturer_id = models.CharField(max_length=25, primary_key=True) manufacturer_name = models.CharField(max_length=25) class Car(models.Model): manufacturer = models.ForeignKey( Manufacturer, related_name='manufacturerCars', on_delete=models.CASCADE) car_id = models.CharField(max_length=25, primary_key=True) car_name = models.CharField(max_length=25) Serializers.py class ManufacturerSerializer(serializers.ModelSerializer): class Meta: model = Manufacturer fields = ("manufacturer_id", "manufacturer_name", "manufacturerCars",) class CarSerializer(serializers.ModelSerializer): manufacturer = ManufacturerSerializer() class Meta: model = Car fields = ("car_id", "manufacturer") When I access /api/cars/ endpoint, I get all the details about car including it's manufacturer: car_details = [ { "car_id": "1", "car_name": "abc", "manufacturer": { "manufacturer_id": "1", "manufacturer_name": "XYZ", "manufacturerCars": [ "1", "7", "3", "5" ] } } ] Question: What approach should I take to list all the cars associated with current car's manufacturer -manufacturerCars field in above output- (i.e. details about cars with id 1, 7, 3, 5) ? Do I need to iterate over all the data that I got from /api/cars i.e. car_details to extract details about car id 1, 7, 3, 5 ? Highly appreciate your help! -
Django will not send email confirmation
So I am setting up a site. Users can register but after registration, they are required to verify their email. I have everything set up and it worked fine yesterday. However, today when I went to the site and created a new user, the browser gets stuck on trying to send the confirmation email, it says waiting for 127.0.0.1. at the bottom left of the screen. But the user was created because I can see them in my database. settings.py EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email' EMAIL_HOST_PASSWORD = 'password' views.py # Create your views here. def register(request): if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): # Create an inactive user. User will be unable to login until email is verified: user = form.save(commit=False) user.is_active = False user.save() # Send an email to the user with the token using the email template in the template folder. current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string('acc_active_email.html', { 'user': request.user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) # The email is being sent using the SMTP configuration in settings.py to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please confirm … -
Summary of Django nested foreign keys
I have the following models in my Django 2.2 project: class ModelA(models.Model): ModelA_id = models.UUIDField('ModelA ID', default = uuid.uuid4) class ModelB(models.Model): ModelB_id = models.UUIDField('ModelB ID', default = uuid.uuid4) ModelA = models.ForeignKey(ModelA, on_delete=models.CASCADE) class ModelC(models.Model): ModelC_id = models.UUIDField('ModelC ID', default = uuid.uuid4) ModelB = models.ForeignKey(ModelB, on_delete=models.CASCADE,) class ModelD(models.Model): ModelD_id = models.UUIDField('ID', default = uuid.uuid4) ModelC = models.ForeignKey(ModelC, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) As you can see, the models are nested like: ModelD has FK to ModelC ModelC has FK to ModelB ModelB has FK to ModelA If I do this: ModelD.objects.filter(pk=0).select_related('ModelC__ModelB__ModelA') does this mean that all data is queried at once in a single (or limited) data base request? I assume this also means it puts all data references starting at ModelD into memory, correct? My end goal is to summarize how many ModelDs reference ModelC, what (not how many) ModelCs reference ModelB, and lastly what ModelBs reference ModelA. -
ModuleNotFoundError: No module named 'django' in AWS ElasticBeanstalk
I'm getting 500 Internal Server Error when running my python webapp through AWS EBS. The following is shown in the server logs: [:error] Target WSGI script '/opt/python/current/app/ipsite/ipsite/wsgi.py' cannot be loaded as Python module. [:error] Exception occurred processing WSGI script '/opt/python/current/app/ipsite/ipsite/wsgi.py'. [:error] Traceback (most recent call last): [:error] File "/opt/python/current/app/ipsite/ipsite/wsgi.py", line 12, in <module> [:error] from django.core.wsgi import get_wsgi_application [:error] ModuleNotFoundError: No module named 'django' The requirements.txt file is present in the root folder and contains Django==2.2.4 The app works when run on my local machine. It does not work when uploaded to AWS. I have tried creating the environment from the beginning but still get the same error. wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ipsite.settings') application = get_wsgi_application() My main directory structure: -.ipsite/ -ipget/ -__init__.py -models.py -tests.py -views.py -ipsite/ -__pycache__/ -__init__.py -settings.py -urls.py -wsgi.py -.ebextensions/ -django.config -.elasticbeanstalk/ -config.yml -.git/ -manage.py -mysite.db -requirements.txt How do I make my AWS environment recognize django? -
django-formtools, saving data between form steps
I am trying to create a multi-step form wizard using django-formtools. I have a main model called Report and several ModelForms as follows: class ReportFormP1(forms.ModelForm): class Meta: model = Report fields = [ 'company', 'address_line_1', 'address_line_2', 'responsible_person', 'person_consulted', 'assessor_name', 'previous_assessment_date', 'review_date', ] # section 1 class ReportFormP2(forms.ModelForm): class Meta: model = Report fields = [ "premise_num_floors", "premise_floor_area", "premise_occupancy", "premise_occupancy_comments", ] in my views, I have created the following view: class ReportWizardView(SessionWizardView): template_name = 'reporting/report_create2.html' form_list = [ReportFormP1, ReportFormP2] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) And my relevant template looks as follows: {% extends '_base.html' %} {% load static %} {% load i18n %} {% load crispy_forms_tags %} <!-- templates/home.html --> {% load socialaccount %} {% block title %}Create a report{% endblock title %} {% block extra_css %} {{ wizard.form.media }} {% endblock extra_css %} {% block content %} <div class="container"> <h1>Create a report</h1> <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post"> {% csrf_token %} {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form|crispy }} {% endfor %} {% else %} {{ wizard.form|crispy }} {% endif %} <div class="text-center"> {% … -
FileUploadHandler writing on Uploaded File when calling .read()
Does TemporaryUploadedFile (class from UploadedFile) write on the uploaded data? I have an XML file here when reading the whole file it starts off with text like: "b'----------------------------507481440966899800347275\r\nContent-Disposition: form-data; name=""; filename="sampleXML.xml"\r\nContent-Type: application/xml\r\n\r\n". The original XML file does not contain this. I am trying to use ElementTree to read through the Uploaded XML File. But am stuck at this part which keeps causing a syntax error. Not sure if it is the class file who edits the data or Postman (used this to upload the file to my REST API). If I read the XML file directly from my PC by getting the path, ElementTree reads it with no issue. Its only getting syntax error when reading from the Uploaded File. I have tried ElementTree.fromString() and parse(). Issue isn't on the actual ElementTree. Tried opening the Temporary file and reading from there (same issue, where there is a the text specified above is shown). I basically want to know if the Django inbuilt FileUploadHandler write on the data when running .read() or somewhere along the process? class FileUploadView(APIView): parser_classes = (FileUploadParser, XMLParser,) def post(self, request, filename, format=None): print(request.FILES) file_obj = request.FILES['file'] fileHandler(file_obj) return Response(status=204) def fileHandler(file): filepath = file.temporary_file_path() print(file.read()) tree … -
How to use Django ORM for multiple inner joins on nested foreign keys
I would like to do multiple joins on some django models with a filter on one of the joined tables. Here is what the raw SQL would look like: SELECT DISTINCT c.id, c.description FROM public.customer_customerhiernode AS c INNER JOIN public.territory_management_territorycustomer AS tc ON tc.customer_id = c.id INNER JOIN public.territory_management_territorynode AS tn ON tn.id = tc.territory_node_id INNER JOIN public.territory_management_territoryuser AS tu ON tu.territory_node_id = tn.id INNER JOIN public.authentication_user AS u ON u.id = tu.user_id WHERE u.username = %s This is what I've tried so far, it is filtering correctly at territorycustomers, but when I fetch the CustomerHierNode, it gets all of them. users = TerritoryUser.objects.select_related('user').filter(user__username=username) territorycustomers = TerritoryCustomer.objects.prefetch_related(Prefetch('territory_node__territoryuser_set', queryset=users)) customers = CustomerHierNode.objects.prefetch_related(Prefetch('territorycustomer_set', queryset=territorycustomers)) I want to join these tables and get all their fields as a flat dictionary. Is this possible with the ORM? I also want this to be as efficient as possible. -
Can't set virtualenv - problem with source activation.ps1
Fallowing the freecodecamp's django tutorial I'm stack on the very beginning - I can't set up virtualenv. Everything goes great until it's time to make final step - activate virtualenv and download Django. I'm working on Windows 10, and tried a lot of ways to solve it. Everything ends up with to results, but first things first. Here is what i did: Ran powershell as administrator and set up ExecutionsPolicy as unrestricted Create new folder called 'Dev' Inside Dev created another folder for project with virtualenv - everything by command 'virtualenv name of the folder Tried to activate it by "name_of_project's_folder\Scripts\activate" After this I'm getting error which says that I must "source this script". I tried to make path to the Scripts folder and type only activate but it doesn't work. When I tried to type "name_of_project's_folder\Scripts\activate" but with ".bat" added on the end, nothing happens. Like, literally nothing. I really hope for making this work because I'm slowly getting frustrated coz of tons of research I made today nad a lot of blind tries to solve this. Python was downloaded via powershell and pip if it's important. -
Django: How can I access and display details about the single "child" in the one-to-many relationship?
I have two models - the Company and Department. The Company can have many Departments - this is all connected with Foreign Key and works as expected. I have URLs and templates/views nicely setup and I can add the Company and then I can add Depratments to it. I am also able to access and create new Departments and assign them to the Company. To see, say 5 last companies I have in the system I use this: class IndexView(generic.ListView): model = Company template_name = 'company/index.html' context_object_name = 'latest_company_list' def get_queryset(self): """Return the last five created companies.""" return Company.objects.order_by('company_name')[:5] And here are the models from models.py class Company(models.Model): company_name = models.CharField(max_length=200) company_dba = models.CharField(max_length=200) class Meta: verbose_name_plural = "companies" def __str__(self): return self.company_name # on submit click on the company entry page, it redirects to the url below. def get_absolute_url(self): return reverse('company:index') class Department(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) dept_name = models.CharField(max_length=200) dept_code = models.IntegerField(default=0) def __str__(self): return self.dept_name # on submit click on the department entry page, it redirects to the url below. def get_absolute_url(self): return reverse('company:index') My urls.py file looks like this app_name = 'company' urlpatterns = [ # Company management views path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('add/', … -
Factory-boy / Django - Factory instance not reflecting changes to model instance
I am writing tests for a website I'm working on and I'm representing the models with factoryboy Factory objects. However, I've run into some behavior I found somewhat confusing and I was wondering if anyone here would be so kind to explain it to me I'm running a test that contains the following model: STATUS = ( ('CALCULATING'), ('PENDING'), ('BUSY'), ('SUCCESS'), ('FAILED') ) class SchoolImport(models.Model): date = models.DateTimeField(auto_now_add=True) status = models.CharField( verbose_name=_('status'), choices=STATUS, max_length=50, default='CALCULATING' ) For which I've created the following factory. As you can see the status is set to its default value, which I found more realistic than having a randomly selected value class SchoolImportFactory(factory.DjangoModelFactory): class Meta: model = models.SchoolImport status = 'CALCULATING' school = factory.SubFactory(SchoolFactory) @factory.lazy_attribute def date(self): return timezone.now() - datetime.timedelta(days=10) Below you'll see both a (simplified) version of the function that is being tested, as well as the test itself. (I've currently commented out all other code on my laptop, so the function that you see below is an accurate representation) The gist of it is that the function receives an id value that it will use to fetch an SchoolImport object from the database and change its status. The function will be run … -
If possible, how can I automatically create a Many to Many class with a custom create function?
I came across a problem while creating an application. It essentially involves three different classes. The purpose is to create an object containing basic social media information for an artist, as the main model shows: class ArtistSocial(models.Model): artist = models.ForeignKey('core.Artist', on_delete=models.PROTECT) social_network = models.ForeignKey('core.SocialNetwork', on_delete=models.PROTECT) url = models.CharField(max_length=50) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) The premise of the challenge I'm faced with is that upon the creation of a new artist, I'll be sent a JSON with all the information I need. However, being quite new to programming applications like this, This makes me confused as to how exactly I need to prepare to properly receive that information and create the class. To me, making a custom create action is the clear solution, but I've tried this in many different ways both in ArtistSerializer and ArtistSocialSerializer. I'll post those two pieces of code here: class ArtistSerializer(ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Artist fields = ['id', 'user', 'name_alternative', 'labels', 'tags', 'country', 'bio', 'profile_image', 'created_at', 'updated_at'] read_only_fields = ['id', 'created_at', 'updated_at', 'user'] And here's the main one: class ArtistSocialSerializer(serializers.ModelSerializer): class Meta: model = ArtistSocial fields = ['id', 'created_at', 'updated_at', 'artist', 'social_network', 'url'] read_only_fields = ['id', 'created_at', 'updated_at'] Though … -
Django mixin and FormView template confusion with CBV
I'm still a noob at mixins in general so I'm just trying to understand what happens in this code that uses Ajax to submit forms. I've been scouring the docs for a whole day to try to figure out what happens. The code seems to work but I just don't entirely understand why. I still have a lot of question marks on the whole process so if anyone can correct my thinking that would be amazing The AjaxableResponseMixin extends the form_invalid() and form_valid() methods of the FormView to support Ajax requests Why is the Ajax class referring to itself with super()? How does the class know to extend FormView's methods? If the request is not Ajax it returns response What does the response object do/have? Does it show a template? Does it have context for the template? CreatePostView is a child class of the two parent classes that are passed in (AjaxableResponseMixin, FormView) Do the order of the classes in the params have an impact in general and more specifically when calling super()? When CreatePostView calls form_valid() and form_invalid() is it overwriting the Ajax class? If it isn't, what class methods is it changing? If the form is valid then … -
How to call a a field of one model A into another model B so that b can work as a view
I have created a model called Department, Course. Models are as follow This is the model for departments and course class Departments(models.Model): Department_Id = models.IntegerField(primary_key=True) Department_Name = models.CharField(max_length=200) Department_Code = models.CharField(max_length=200) class Course(models.Model): Course_Id = models.IntegerField(primary_key=True) Department_Id = models.ForeignKey(Departments, on_delete=models.CASCADE) Course_Name = models.CharField(max_length=200) Course_Code = models.CharField(max_length=200) I want to create a model called view which can be later on called for search. I want a view model in a such a way that it consit of the data in concat form i.e. name= Department_name+ Course_Name class View (models.model): view_id= models.IntegerField(primary_key=True) Name= Department_name(I want this from Departments table) + Course_Name(I want this from Course table) I try using one to one relation . I would really appricate the help -
Load data from model in settings.py Django
I have model: class Settings(models.Model): class Meta: verbose_name = "Ustawienia strony" verbose_name_plural = "Ustawienia strony" title = models.CharField(_('Tytuł strony'), max_length = 120, blank = True) description = models.TextField(_('Opis strony'), blank = True) facebook_title = models.CharField(_('Tytuł strony Open Graph'), max_length = 120, blank = True,) facebook_type = models.CharField(_('Typ strony Open Graph'), max_length = 120, blank = True,) facebook_url = models.CharField(_('Link strony Open Graph'), max_length = 500, blank = True,) facebook_description = models.TextField(_('Opis strony Open Graph'), blank = True, ) template = models.CharField(_("Wygląd sklepu"), choices = TEMPLATES_LIST, max_length = 100, default="DEFAULT") Now I would like load selected model in settings.py: CURRENT_TEMPLATE = Settings.objects.all().first() But in this way I have error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Is it available to load data from model in settings.py? -
Writing validators with Django: How to display Validation Error Message?
i am testing "Writing validators" from the Django Doc more or less. So i wrote my own validator and it seems to work, but i don´t know how to display the error message in my template. models.py <...> class Animal(models.Model): name = models.CharField(max_length=40) weight = models.DecimalField(max_digits=5, decimal_places=2) species = models.ForeignKey('Species', on_delete=models.CASCADE) farmer = models.ForeignKey('Farmer', related_name='farmername', on_delete=models.CASCADE) objects = AnimalManager() # --- link to Manager def __str__(self): return self.name def get_absolute_url(self): return reverse("datainput:animal_detail", kwargs={"id": self.id}) forms.py <...> from .validator import validate_gtr <...> class AnimalForm(forms.ModelForm): weight = forms.DecimalField(validators=[validate_gtr]) class Meta: model = Animal fields = [ 'name', 'weight', 'species', 'farmer', ] validator.py from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_gtr(value): if value > 100: raise ValidationError( _('(value) Kg. Animal is too heavy'), params={'value': value}, ) views.py class AnimalCreateView(CreateView): template_name ="datainput/create_animal.html" form_class = AnimalForm queryset = Animal.objects.all() create_animal.html {% extends 'base.html' %} {% load static %} {% block custom_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}"> {% endblock %} {% block content %} <div class="container-fluid"> <!-- Row --> <div class="row"> <div class="col-6 offset-md-3"> <h1>Please insert a new animal</h1> {% load widget_tweaks %} <form method="post"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor …