Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use Mysql data in Django
I am struggling with getting values from MySql and using in Django for calculations. It is school project where a teacher can enetr student name and get its grades and finals. I want to be able the program get values from database and implement calculation as wqell. In views.py i have : def home(request): if request.method == "POST": form = StudentForm(request.POST) if form.is_valid(): form = form.save(commit=True) name = form.student_name context={ 'name':name, } return render(request, 'school/analysis.html', context) else: form = StudentForm() return render(request, 'school/search.html', {'form': form}) in models.py: from django.db import models class Profile(models.Model): student_name = models.CharField(max_length=255) class Meta: managed = False db_table = 'profile' class Class10(models.Model): profile_id = models.IntegerField() math = models.IntegerField() literature = models.IntegerField() biology = models.IntegerField() student = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='stud_name',) class Meta: managed = True db_table = 'class_10' formy.py from django import forms from .models import Profile, Class10 class StudentForm(forms.ModelForm): SUB = ( ('math', 'math'), ('literature', 'literature'), ('biology', 'biology') ) student_name = forms.CharField(max_length=150, label='', widget=forms.TextInput) class Meta: model = Profile fields = ('student_name',) I have 2 issues: 1) my database is filling the input requests and the same values has multiple copies thereby 2. i cannot get grade for math score . I would appreciate to get … -
django model get all values with empty list
I need to filter results from db based on certain conditions. If a list of IDs where provided it should return values related to those IDs and if an empty list is provided it should return all the values. Lets say a table has 5 rows of values, Model.object.filter(id__in=[1,2]) should return values of ID 1 and 2. And Model.object.filter(id__in=[]) should return all the values. Could this be done with single query or by chaining filters? -
How to make Django Forms JSON serializable
I am running a website using Django framework. Below is the code. Forms.py : class ProfileForm(forms.ModelForm): class Meta: model=Profile widgets = { 'address_line_1': forms.TextInput(attrs={'placeholder': 'Door No,Building'}), 'address_line_2': forms.TextInput(attrs={'placeholder': 'Area,Locality'}), } fields=('first_name','last_name','mobile_no','email','address_line_1','address_line_2','postal_code','city','country','image','referral_contact','promo_coupon','ic') views.py : def signup(request): registered=False failed_ref=False wrong_ref=False if request.method=='POST': user_form = UserForm(data=request.POST) profile_form = ProfileForm(request.POST) if 'city' in request.POST: if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user else: print(user_form.errors,profile_form.errors) user_err='' mobile_err='' if user_form.errors: user_err="A profile with this username already exists!" if profile_form.errors: mobile_err="A profile with this mobile number already exists!" data={'registered':registered,'failed_ref':failed_ref,'wrong_ref':wrong_ref,'user_error':user_err, 'profile_error':mobile_err} return JsonResponse(data) else: user_form=UserForm() profile_form=ProfileForm() return JsonResponse({'profile_form':profile_form,'registered':registered, 'failed_ref':failed_ref,'wrong_ref':wrong_ref}) I want to get response in JSON . The error i am getting is "TypeError: Object of type ProfileForm is not JSON serializable". Can anyone help to solve this? -
Is there an way to use a specific authentication backend among multiple backed on settings to use upon each request on django?
I was wondering how to tell Django which authentication backend to use upon each request. Can this be done? -
Django3.0.1: after use ForeignKey then show this problem - This field cannot be null
I'm using Django 3.0.1 and MySQL database. models.py views.py migrations already done the problem -
Email not sending from admin panel
I am trying to have the Django admin send emails to the users of the site. However, I cannot get the email to send to a user's email inbox. There doesn't seem to be any compile issues but I don't get anything in my inbox. What exactly is going wrong? I made sure to set up email in Django correctly, too. Here is my code: views.py def sendUserEmails(request): form = SendEmailForm(request.POST) print("going here") if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] users = form.cleaned_data['users'] for user in users: send_mail(subject, message, from_email, user.email, fail_silently = True) user_message = '{0} users emailed successfully!'.format(form.cleaned_data['users'].count()) messages.success(self.request, user_message) return render(request, 'admin/send_email.html', {'form': form}) forms.py class SendEmailForm(forms.Form): subject = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Subject'})) message = forms.CharField(widget=forms.Textarea) users = forms.ModelMultipleChoiceField(label = "To", queryset = Account.objects.all(), widget = forms.SelectMultiple()) email function in admin.py def send_email(self, request, queryset): form = SendEmailForm(initial = {'users' : queryset}) return render(request, 'admin/send_email.html', {'form': form}) urls.py path('admin/solutions/account/', views.sendUserEmails, name='email'), I tried to debug with no success. Please help. -
How to prevent selecting a choice in DAL dependent choice field
I am using Django Autocomplete Light in my application. In some of the views I have dependent choices with a parent - child relationship (eg. Country < Cities). For chaining of choices I am using "forward" function as mandated in DAL documentation, as shown below. 'country': autocomplete.ModelSelect2(url='country-autocomplete', attrs={'style': 'width:80px', 'data-placeholder': 'Click here to select...', 'data-minimum-input-length': 2}), 'city': autocomplete.ModelSelect2(url='city-autocomplete', forward=['country'], attrs={'style': 'width:40px', 'data-placeholder': 'Click here to select...', 'data-minimum-input-length': 2}), The page is working fine as expected with the caveat that, with no country choice picked up prior to city choices, the "city" choice field shows all available options (following are the images displaying the scenario). Scenario 1. Country choice not filled: In this instance, we can see all city choices with "lo" in their names are generated when only the "city" choice field is used (without first filling in the "country" choice field). Scenario 2. Country choice filled: In the second instance, when the city choice field is selected after picking up the "country" choice first, the names generated in the "city" choice field are limited to the country "United Kingdom". My question is: Is there a way I may prevent selection from the child field (field "city" here) without first … -
adding latex rendering script to django-markdownx admin
I' am making a personal homepage with Django. I am using django-markdownx for the content of article model. In addision, Katex has been implemented to the project with lines of JS in the Django template HTML to render Latex. What I'm having a hard time is applying this Katex JS code to the Django admin page. How can I implement the JS code below to specific elements of the Django admin page? I don't want the script to be applied to all elements of the admin page, because editing text boxes should show raw Latex code, but only the preview part should render Latex parts as equations. Here are django-markdownx, and Katex references: https://neutronx.github.io/django-markdownx/ https://katex.org/docs/api.html This is a JS code block that I'm using for Latex rendering. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous" /> <!-- The loading of KaTeX is deferred to speed up page rendering --> <script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js" integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous" ></script> <!-- To automatically render math in text elements, include the auto-render extension: --> <script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js" integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous" onload="renderMathInElement(document.body);" ></script> <script> document.addEventListener("DOMContentLoaded", function() { renderMathInElement(document.body, { delimiters: [ { left: "$$", right: "$$", display: true }, { left: "\\[", right: "\\]", display: true }, { left: "$", right: … -
cannot get frontend Angular form POST working with Django backend
I am using Angular 8 as a frontend and Django 3 as a back end. I have an app that is thus far just trying to create Restaurant objects. I can query the django backend with a GET request and see all the Restaurant objects in the database, but I am struggling to create and post a new Restaurant object to the backend. I can create (I think) the Restaurant object using ReactiveFormModules with the data binding and console.log it and I see the name and food attributes, but for some reason I never get the Restaurant object to post to the backend. I have tried debugging the django backend and the code never even gets to the elif request.method == 'POST': part of the django backend views.py. Angular add-restaurant.component.html <h3>Create a Restaurant:</h3> <div *ngIf = "!submitted"> <form [formGroup] = "restaurantForm" (ngSubmit)="onSubmit()" novalidate> <label>Restaurant Name: <input formControlName = "name" type="text" id="name" name="name" required> </label> <br><br> <label>Restaurant Food: <input formControlName = "food" type="text" id="food" name="food" required> </label> <br> <button type="submit">Create Restaurant</button> </form> Angular add-restaurant.component.ts import { Component, OnInit } from '@angular/core'; import { RestaurantService } from '../restaurant.service' import { Restaurant } from '../restaurant' //import ExpressionWithTypeArguments = ts.ExpressionWithTypeArguments; import {NgForm, FormControl, FormGroup, … -
Get distinct django objects from queryset sorted by latest
I have this model (irrelevant fields hidden): class Blog(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) is_published = models.BooleanField(default=False) published_date = models.DateTimeField(null=True, default=None, blank=True) I only want to get the latest post of each author, sorted by published date. I have tried the following in my view: blog_list = Blog.objects.filter(is_published=True).order_by('author', '-published_date').distinct('author') Which works except this sorts all of the blog post in order of the author, not by published date. The following would actually do the trick by switching the order by, but this throws an error in django: blog_list = Blog.objects.filter(is_published=True).order_by('-published_date', 'author').distinct('author') I've checked all of the similar questions to this one and haven't encountered a solution that works. I think this request should be pretty simple but I don't see any way of achieving this. -
How to show the actual foreign key id in Django admin?
When I'm in admin looking at a Bar record, the dropdown for the foreign key shows the title of Foo, and not the id of Foo. There can be multiple titles with the same name, so this is not helpful. I would like to see the id of Foo while I'm looking at Bar in admin. Here's my models.py from django.db import models class Foo(models.Model): created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) class Bar(models.Model): created_at = models.DateTimeField(auto_now_add=True) foo = models.ForeignKey(Foo, on_delete=models.CASCADE) Herey's my admin.py from django.contrib import admin from .models import Foo, Bar class FooAdmin(admin.ModelAdmin): readonly_fields = ('id',) class BarAdmin(admin.ModelAdmin): readonly_fields = ('id',) admin.site.register(Foo, FooAdmin) admin.site.register(Bar, BarAdmin) -
Pathos multiprocessing pool hangs
I'm trying to use multiprocessing inside docker container. However, I'm facing two issues. (I'm using python 2.7) Creating ProcessingPool()/Pool() (I tried both) takes abnormally long time to create. Maybe over a minute or two. After it processes the function, it hangs. I basically trying to run a very simple case inside my container. Here's what I have.. import pathos.multiprocessing import ProcessingPool import multiprocessing class MultiprocessClassExample(): . . . def worker(self, number): return "Printing number %s" %(number) . . def generateNumber(self): PROCESSES = multiprocessing.cpu_count() - 1 NUMBER = ['One', 'Two', 'Three', 'Four', 'Five'] result = ProcessingPool(PROCESSES).map(self.worker, NUMBER) print("Finished processing.") print(result) and I call using the following code. MultiprocessClassExample().generateNumber() Now, this seems fairly straight forward enough. I ran this on a jupyter notebook and it ran without an issue. I also tried running python inside my docker container, and tried running the above code inside, and it went fine. So I'm assuming it has to do with the complete code that I have. Obviously I didn't write out all the code, but that's the main section of the code I'm trying to handle right now. I would expect the above code to work as well. However, first thing I notice is that … -
Apache + Django + wsgi.py. Site can't be reached
I am trying to setup Apache2 on EC2 machine. However i am unable to access my website through Apache. I tried listing different ports like 80, 443, 8000 but no luck. Here is my /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com Alias /static /home/ubuntu/project/django_project/django_project/static <Directory /home/ubuntu/project/django_project/django_project/static> Require all granted </Directory> <Directory /home/ubuntu/project/django_project/django_project/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django_project python-path=/home/ubuntu/project/django_project python-home=/home/ubuntu/env_folder/my_env3.6 user=ubuntu WSGIProcessGroup django_project WSGIScriptAlias / /home/ubuntu/project/django_project/django_project/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files … -
Django count nested ManyToManyField Objects
I have the following model, which has 3 classes Project,CrawlerProject,CrawlerResults class CrawlerProject(models.Model): user = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) cralwer_results_M2M = models.ManyToManyField(CrawlerResults,blank=True) class Project(models.Model): user = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) crawler_project_M2M = models.ManyToManyField(CrawlerProject,blank=True) Here, i want to count the total number of CrawlerResults objects are present for all CrawlerProjects within individual Project object. projects = Project.objects.all().prefetch_related('crawler_project_M2M') for each_proj in projects: total_num_of_crawler_results = each_proj.crawler_project_M2M__cralwer_results_M2M.count() ## count all the crawler_results objects of all crawler_project present in current `project` object. How do I achieve in an efficient way(single query) to get the total count of nested ManyToMany class? -
Crontab Launches Python Script but SystemD Does Not?
I can log into my AWS EC2 server via ssh and type: cd /opt/myWebApp sudo python3 /opt/myWebApp/manage.py myCronJob ...and it runs. I can also launch the same script via crontab: 0 */6 * * * sudo python3 /opt/myWebApp/manage.py myCronJob --settings=server.settings.production But when I try to run it in SystemD, with .service file: ExecStart='/usr/bin/python3.7' /opt/myWebApp/manage.py myCronJob --settings=server.settings.production ...I get: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? $PYTHONPATH and $VIRTUAL_ENV are empty. /opt/myWebApp/server_venv is empty as well. There's a python at /usr/bin/python3.7, but I'm referencing that in the SystemD .service file as noted above, and it's throwing that error. What am I missing? -
Django Will Not Open Up Static File Image, Django 3
So I have been trying to figure out why the image will not show and I have watched and read numerous things, but i still can't find anything. This is my first question on here. Thanks for helping out HTML {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Nikhil's Portfolio</title> </head> <body> test <img scr="{% static 'static/homepage/wpap.jpg' %}" alt="why is it not working"> <img scr="{% static 'static/homepage/download.jpg' %}" alt="why is it not working"> </body> </html> url.py of my website (not app url) from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('homepage.urls')) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] How my files are arranged img of file organization -
Django NameError at /dashboard/video/external
I'm new to Django and writing a video site now. I wrote a dashboard to manage external videos and wanted to add a new page to add more information, like cast and URLs. But after I added the new page, I can't even open the previous working dashboard page. Could anyone help me with it? Thank you so much for your time and help! views from django.views.generic import View from django.shortcuts import redirect, reverse from app.libs.base_render import render_to_response from app.utils.permission import dashboard_auth from app.model.video import VideoType, FromType, NationalityType, RoleType, Video, VideoSub, VideoCast from app.utils.common import check_and_get_video_type class ExternalVideo(View): TEMPLATE = 'dashboard/video/external_video.html' @dashboard_auth def get(self, request): error = request.GET.get('error', '') data = {'error': error} videos = Video.objects.exclude(from_to=FromType.custom.value) data['videos'] = videos return render_to_response(request, self.TEMPLATE, data=data) def post(self, request): name = request.POST.get('name') image = request.POST.get('image') video_type = request.POST.get('video_type') from_to = request.POST.get('source_type') nationality = request.POST.get('nationality_type') info = request.POST.get('info') if not all([name, image, video_type, from_to, nationality, info]): return redirect('{}?error={}'.format(reverse('external_video'), 'missing required field(s)')) result = check_and_get_video_type(VideoType, video_type, 'invalid video type') if result.get('code') != 0: return redirect('{}?error={}'.format(reverse('external_video'), result['msg'])) result = check_and_get_video_type(FromType, from_to, 'invalid source type') if result.get('code') != 0: return redirect('{}?error={}'.format(reverse('external_video'), result['msg'])) result = check_and_get_video_type(NationalityType, nationality, 'invalid nationality') if result.get('code') != 0: return redirect('{}?error={}'.format(reverse('external_video'), result['msg'])) try: Video.objects.create( … -
Django database from local_settings.py
I have a local database for testing and a remote database for production. I specify which database to use in local_settings.py file which is imported at the end of settings.py ... try: from .local_settings import * except ImportError: ... local_settings.py defines the database as: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'clemente', 'HOST': 'localhost', 'PORT': '', } } but in the manage.py shell, if I print DATABASES, I get: In [5]: settings.DATABASES Out[5]: {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/Users/dan/ponto/db.sqlite3', 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'NAME': None, 'MIRROR': None}}} which is a sqlite database (which is what I believe is the django default). How do I get django to point to the database defined in local_settings.py? -
django 3.0.1 fetching data from api, looping and saving to db
I most likely I have a logic error in my view: def lob_import(request): raw_data = requests.get("https://....news.json") data = json.loads(raw_data.content) try: for post in data: print (post["title"]) print (post["created_at"]) News.objects.update_or_create( title = post["title"], date = post["created_at"], by = post["submitter_user"], url = post["short_id_url"] , lid = post["short_id"] ) print(f"[+] Finished {str(title)} [+]") except Exception as e: print ("error saving to db") print(e) #print(data) articles = News.objects.all() return render(request, 'lob.html', {'articles': articles}) if I comment out the News.objects.update_or_create I get the items through the loop Vim9 2020-01-03T08:28:01.000-06:00 V is for Vvork in Progress 2020-01-03T15:20:59.000-06:00 What tools do you use to maintain a personal log/journal ? 2020-01-03T12:28:48.000-06:00 Don't bet on an expected value but when I run it with the News.objects.update_or_create only the first article is saved and then an error is returned: > Vim9 2020-01-03T08:28:01.000-06:00 error saving to db name 'title' is > not defined -
How to return __str__(self) in ModelAdmin list_display
I have the following model: class Administrator(models.Model): // code def __str__(self): title = 'Administrator ' + str(self.pk) return title This returns titles for the objects as Administrator 1, Administrator 2, etc. How do I return the title in list_display for a ModelAdmin?: class AdministratorAdmin(ModelAdmin): model = Administrator list_display = ('pk', 'id', 'title???') -
retrieving value of chosen foreignkey in modelform django
I have the following in my models.py class CustomerRecords (models.Model): TarMagic = models.AutoField(primary_key=True) first_name = models.CharField(('First Name'), max_length=50) def __str__(self): return self.first_name C_MONTHS_PERIOD_CHOICES = (('0', '0 Month'), ('1', '1 Month'), ('2', '2 Months'), ('3', '3 Months'), ('4', '4 Months'), ('5', '5 Months'), ('6', '6 Months'), ('7', '7 Months'), ('8', '8 Months'), ('9', '9 Months'), ('10', '10 Months'), ('11', '11 Months'), ('12', '12 Months'), ('13', '13 Months'), ('14', '14 Months'), ('15', '15 Months'), ('16', '16 Months'), ('17', '17 Months'), ('18', '18 Months'), ) C_Days_PERIOD_CHOICES = (('0', '0 Days'), ('1', '1 Day'), ('2', '2 Days'), ('3', '3 Days'), ('4', '4 Days'), ('5', '5 Days'), ('6', '6 Days'), ('7', '7 Days'), ('8', '8 Days'), ('9', '9 Days'), ('10', '10 Days'), ('11', '11 Days'), ('12', '12 Days'), ('13', '13 Days'), ('14', '14 Days'), ('15', '15 Days'), ('16', '16 Days'), ('17', '17 Days'), ('18', '18 Days'), ('19', '19 Days'), ('20', '20 Days'), ('21', '21 Day'), ('22', '22 Day'), ('23', '23 Day'), ('24', '24 Day'), ('25', '25 Day'), ('26', '26 Day'), ('27', '27 Day'), ('28', '28 Day'), ('29', '29 Day'), ('30', '30 Day'), ('31', '31 Day'), ) class subscriptionScheme(models.Model) : title = models.CharField(('Subscription Title'), max_length=250) durationbyMonths = models.CharField(('Months of Subscriptions'), max_length=30, choices=C_MONTHS_PERIOD_CHOICES, default=C_MONTHS_PERIOD_CHOICES[0][0]) durationbyDays = models.CharField(('Days … -
Complex django form
I want to take input as a list. This is my forms. py from django import forms from .models import answer class SchoolInput(forms.Form): school_name = forms.CharField( max_length=255, required=True, widget=forms.TextInput( attrs={ 'class': 'input' } )) num_of_days = forms.IntegerField(min_value=1, max_value=7, required=True) level_of_grades = forms.IntegerField(min_value=1, required=True) num_of_subjects = forms.IntegerField(min_value=1, widget=forms.NumberInput( attrs={ 'class': 'second_input' } )) name_of_subjects = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'third_input' } )) num_of_lectures = forms.IntegerField(min_value=1, widget=forms.NumberInput( attrs={ 'class': 'second_input' } )) division_check = forms.ChoiceField( label='Do you have multiple divisions for your grades?', choices=answer, widget=forms.RadioSelect(attrs={ 'class': 'radiobuttons', 'style': 'display: block' }) ) num_of_subjects field and num_of_lectures field are the fields where I wanna take input as a list and the number of iterations depend upon the value that'll be provided in level_of_grades field. Tried list comprehensive in those field but didn't think it was a good idea. Though these are not forms made in html, is it a good idea to use django forms for this task or make html form? For better understanding these should be values I would want school_name = 'something' level_of_grades = 5 num_of_days = 5 num_of_subjects = ['4','3','5','6','9'] num_of_lectures = ['6','7','9','4','3''] name_of_subjects = this will be list with number of lists inside which I'll create once ill understand … -
Filtering on column of ManyToManyField?
I have this (simplified for discussion) data model, and I can't seem to filter on a field of the many to many table; the property below results in "Related Field got invalid lookup: person": class Person(Model): traveler_trips = ManyToManyField('Trip', related_name='travelers') @property def mungee_trips(self): return Trip.objects.filter(travelers__person=self).all() Again, this is a simplified example of what I'm trying to do; I realize person.traveler_trips would give me the same result as this property, I'd like to know what I need to do to explicitly filter on columns of a ManyToManyField's underlying table - another filter I'm trying to use looks like travelers__person__idx__lt=self.idx. Here is the schema for this join table (it does have the expected person_id column): Column | Type | Collation | Nullable | Default ----------------+---------+-----------+----------+---------------------------------------------- id | integer | | not null | nextval('ms_traveler_trip_id_seq'::regclass) person_id | integer | | not null | trip_id | integer | | not null | -
Multilevel dropdown menu in a django form
Django beginner here. I would like to create a 2-level dropdown menu in a django form. Something like this: [2-level dropdown menu][1] I would like to be able to fill a form field with strings 'A1', 'B3', 'C2' or whatever I choose from the dropdown menu. I tried using a choice field in the model to create the choices for the form but I don't know how to turn this into a 2-level dropdown menu. Maybe there is a hint in the documentation but I was unable to find it... https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices Thanks in advance for the help! # models.py from django.db import models class Player(models.Model): name = models.CharField(max_length=100) POSITION_CHOICES = [ ('A', 'A'), ('B', 'B'), ('C', 'C'), ] """ how do I specify the second level of choices here(1,2,3)? also, the second level is always the same for A,B and C and I would like to avoid repeating code. """ position = models.CharField( max_length=2, choices=POSITION_CHOICES) # forms.py from django import forms from .models import Player class PlayerForm(forms.ModelForm): class Meta: model = Player fields = ('name', 'position',) # views.py from django.views import generic class PlayerCreateView(generic.CreateView): model = Player form_class = PlayerForm template_name = 'player_form.html' def form_valid(self, form): ### do I have … -
Python - SMB Connection
So, I have a windows server that is hosting the django web app and is mounted with a network drive. When I see the parameters, I am little confused with the context of "server" here. Is the server_ip/server_name the ip/name of my hosting server? or is it some other server that is related to the network drive? Based on my understanding, USERID : admin windows username PASSWORD : admin windows password CLIENT_MACHINE_NAME : my server's computer name (arbitrary) SERVER_NAME : server name of my windows server SERVER_IP : ip address of my windows server Can anyone please help guiding me on the parameters for the SMB connection (userid, password, client_machine_name, server_name, server_ip)? Thank you!