Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Amount of matches in two Django ManyToMany fields
In my application I would like to determine similarity between objects. The objects have a few ManyToMany fields and the amount of matching values in that list would give an indication of the similarity. (e.g. one song might be similar to another if it has a lot of common artists, genres or producers) class Song: genres = models.ManyToManyField(Genre) artists = models.ManyToManyField(Artist) producers = models.ManyToManyField(Producer) I can imagine a lot of the possible way to compare these fields would be very slow, because they load all the objects of the ManyToMany fields before comparing. Is there a quick way to count matches based on id's? -
Django 2.0 - How to deal with testing on only one database when we have several?
First of all, I'm new to asking question here, so bear with me if I don't do it perfectly :) Here goes... I am setting up a Django2.0 API that is going to deal with statistics. It has its own 'default' database to write stuff obviously, but I am going to need several other databases that will be read-only. This is what the settings look like for now. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dev_gpws', 'USER': 'dev_gpws_user', 'PASSWORD': 'gpws_pwd', 'HOST': 'localhost', 'PORT': '5432', }, 'other_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'other_db_name', 'USER': 'other_db_user', 'PASSWORD': 'other_db_pwd', 'HOST': 'other_db_host', 'PORT': '5432', }, } When fabric deploys the project into staging, part of the routine is ./manage.py test, which leads to the following error: (gpws) dev_gpws@af968cdb7653:~/gpws/project$ ./manage.py test Creating test database for alias 'default'... Creating test database for alias 'other_db'... Got an error creating the test database: ERREUR: permission denied to create database It makes total sense considering other_db_user is a read-only user, so I would like to disable django's testing for this database. Is there a clean way to do it ? Also, this stats app is going to be linked with quite a few databases later on, so I would … -
Django fails to load in iframe after update to version 2.1 (redirecting to login when it should not)
After update to Django 2.1 (from 2.0) and deployment to server, my site just goes blank (i.e. redirects me to login, but goes blank since it's loaded in <iframe>). This is my basic setup, a POST request hits the index view, which is then authenticated (custom auth backend) and user is logged in, redirecting the user to site view. However, instead of loading the site view, the Django's login page is displayed. # launch/ @xframe_options_exempt @csrf_exempt def index(request): if request.method == 'POST': uid = request.POST.get('user_id') origin = request.POST.get('orig_url') user = authenticate(uid, origin) login(request, user) return HttpResponseRedirect(reverse('launch:site')) # launch/site/ @xframe_options_exempt @csrf_exempt @login_required def site(request): if request.method == 'POST': return HttpResponseRedirect(reverse('timeline:grid')) return render( request, 'launch/site.html', { 'form': CredentialsForm(), 'errors': '', } ) This is what the apache logs display for an incoming request: xxx.xxx.xxx.xxx - - [26/Aug/2018:10:42:28 +0200] "POST /launch/ HTTP/1.1" 302 ... xxx.xxx.xxx.xxx - - [26/Aug/2018:10:42:28 +0200] "GET /launch/site/ HTTP/1.1" 302 ... xxx.xxx.xxx.xxx - - [26/Aug/2018:10:42:28 +0200] "GET /login/?next=/launch/site/ HTTP/1.1" 200 ... The second redirect (302) should not happen on the GET request. In my urls.py I've switched to class based login view, since the function one was deprecated in the new version, i.e. now I have: from django.contrib.auth import views … -
django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)")
I'm trying run django with mysql in docker containers: version: '2' services: db: image: mysql:latest volumes: - ./db:/var/lib/mysql ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: mypassword MYSQL_USER: root MYSQL_PASSWORD: mypassword MYSQL_DATABASE: django expose: - "3306" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db but after docker-compose up --build I got error: django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)") Most likely, the container with mysql did not have time to start. But I did specify depends_on: - db in theweb Who understands what might be the matter? -
Exception Value: build_attrs() got an unexpected keyword argument 'type'
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/payment/process/ Django Version: 1.11.11 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop', 'cart', 'orders', 'payment', 'paypal.standard.ipn'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/jarvis/Documents/myshop/shop/templates/shop/base.html, error at line 7 build_attrs() got an unexpected keyword argument 'type' 1 : {% load static %} 2 : <!DOCTYPE html> 3 : <html> 4 : <head> 5 : <meta charset="utf-8" /> 6 : <title>{% block title %}My shop{% endblock %}</title> 7 : <link href="{ % static "css/base.css" %}" rel="stylesheet"> 8 : </head> 9 : <body> 10 : <div id="header"> 11 : <a href="/" class="logo">My shop</a> 12 : </div> 13 : <div id="subheader"> 14 : <div class="cart"> 15 : {% with total_items=cart|length %} 16 : {% if cart|length > 0 %} 17 : Your cart: Traceback: File "/home/jarvis/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/jarvis/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/jarvis/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jarvis/Documents/myshop/payment/views.py" in payment_process 37. 'form':form}) File "/home/jarvis/anaconda3/lib/python3.6/site-packages/django/shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "/home/jarvis/anaconda3/lib/python3.6/site-packages/django/template/loader.py" in render_to_string 68. return template.render(context, request) File "/home/jarvis/anaconda3/lib/python3.6/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/home/jarvis/anaconda3/lib/python3.6/site-packages/django/template/base.py" in render 207. … -
internal server error in android with django server
my python code in django is: @csrf_exempt def login(request): data = {'a': '1'} if request.method == 'POST': form=login_form(request.POST) if form.is_valid(): f = form.cleaned_data if sign_in.objects.filter(username=f['user'], password=hashlib.md5(f['pas'].encode()).hexdigest()): return JsonResponse(data) and in android: ApiInterface apiInterface = ApiClinet.GetClinet().create(ApiInterface.class); Call<String> call = apiInterface.GetHome_call("x","y"); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { } @Override public void onFailure(Call<String> call, Throwable t) { } }); this code work in postman and recive: { "a": "1" } but when run in android. recive internal sever error! and I work on localhost. -
How to change parameter in serializer through view in django rest api
ok here is a deal serializer: from rest_framework import serializers from happytourist.models import PointsInterestData class PointsInterestSerializer(serializers.ModelSerializer, serializers.Serializer): distance = serializers.SerializerMethodField(default=None) def get_distance(self, obj): distance_view = self.context.get('distance') return distance_view class Meta: model = PointsInterestData fields = ('name', 'latitude', 'longtitude', 'distance') read_only_fields = fields my view: from rest_framework import generics from .serializers import PointsInterestSerializer from happytourist.models import PointsInterestData class PointsInterestList(generics.ListCreateAPIView, generics.ListAPIView): serializer_class = PointsInterestSerializer def get_queryset(self): queryset = PointsInterestData.objects.all() return queryset def post(self, request, *args, **kwargs): user_latitude = request.POST.get('latitude') user_longtitude = request.POST.get('longtitude') radius = request.POST.get('radius') usergeodata = {'user_latitude': user_latitude, 'user_longtitude': user_longtitude, 'radius': radius} return usergeodata def get_coordinates(self): latitude = PointsInterestData.objects.model.latitude longtitude = PointsInterestData.objects.model.longtitude geodata = {"latitude": latitude, "longtitude": longtitude} return geodata def distancecalc(self, request): user_latitude = self.post(request=self.request)['user_latitude'] user_longtitude = self.post(request=self.request)['user_longtitude'] latitude = self.get_coordinates()['latitude'] longtitude = self.get_coordinates()['latitude'] x = longtitude - user_longtitude y = latitude - user_latitude distance = int((x ** 2 + y ** 2) ** (1 / 2)) return distance def get_serializer_context(self): distance_result = PointsInterestList.distancecalc(self, request=self.request) context = super(PointsInterestList, self).get_serializer_context() context.update({'distance': distance_result}) return context What I need to do is to get post latitude, and longtitude, get latitude and longtitude from model, calculate the distance between them. My problem is to transform the distance into new value. In the view I … -
Choose between django.shortcuts.render and django.views.generic.TemplateView
I have gone through several Django tutorial. I notice to generate dynamic web content, based on a static HTML template file, there are 2 ways Use django.conf.urls.url in url.py. Point to a named function which will call django.shortcuts.render. Use django.urls.path in url.py. Point to a named class which inherits from django.views.generic.TemplateView. Both ways produce same outcome. I was wondering, how can we decide which ways to use for a given situation? -
Django app PDF rendering (django-easy-pdf)
I'm using django-easy-pdf to generate a PDF from an HTML file in my web application. I've followed the Quickstart tutorial (https://github.com/nigma/django-easy-pdf) but nothing happens when I click the "Download as PDF" link in detailedresearchputput_detail.html. There is no content displayed or .pdf file saved in the project. Could someone please advise where I'm going wrong. view.py: from easy_pdf.views import PDFTemplateResponseMixin class PDFUserDetailView(PDFTemplateResponseMixin, generic.DetailView): model = ResearchOutput template_name = 'cbib/detailedresearchoutput_detail.html' urls.py: from .views import PDFUserDetailView urlpatterns += [ ... **path('detailed_research_output/<int:pk>', PDFUserDetailView.as_view(), name='pdfdetailedresearchoutput-detail'),** ] models.py: def get_absolute_url_pdf(self): """Returns the url to access a detail record for this book.""" return reverse('pdfdetailedresearchoutput-detail', args=[str(self.id)]) detailedresearchputput_detail.html: Download as PDF -
Update data instead of creating a new row entry in django model
I have a page for editing existing data from a model. The model: class billitem(models.Model): code = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=35) description = models.CharField(max_length=60, null=True) price = models.DecimalField(decimal_places=2, max_digits=8) The form: class BillItem(forms.Form): code = forms.IntegerField(max_value=100000, disabled=True) name = forms.CharField(label='Item Name', max_length=32) description = forms.CharField( label='Description', max_length=57, required=False) price = forms.DecimalField(decimal_places=2, max_digits=8) The view is: def edit_bill_item(request, itemcode): if request.method == 'POST': form = BillItem(request.POST) code = request.POST.get('code') name = request.POST.get('name').title() description = request.POST.get('description') price = request.POST.get('price') billitem.objects.filter(code=code).update( name=name, description=description, price=price) msg = 'Successfully saved Billing item.' # form = BillItem(request.POST) return render(request, 'billing/edititem.html', {'form': form, 'msg': msg}) else: itemcode = int(itemcode) item = get_object_or_404(billitem, code=itemcode) form = BillItem(initial={ 'code': item.code, 'name': item.name, 'description': item.description, 'price': item.price }) return render(request, 'billing/edititem.html', {'form': form}) The problem is that every time POST is submitted, another entry gets added in the table, with a new code, instead of updating existing row. I also tried: item = billitem(code=code, name=name, description=description, price=price) item.save() Which also had the same effect. How can I handle updation of existing data only within my model and form. -
How to use update_or_create() and F() to create a new record in Django?
Assuming we have a wallet table with these field: id, user_id, total, freeze, active, update_time. Each user only have one record in this table, and will be updated all the time. e.g. { id: 1, user_id: 100, total: 50.5, freeze: 0, active: 50.5, update_time: 2018-07-17 16:43:41, } When the user earned $5, how could I use the update_or_create() method to update the total, freeze and active fields depend on their original value? income = 5.0 Wallet.objects.update_or_create( user_id=obj.user.id, defaults={ 'update_time': datetime.now(), 'active': F('active') + income, 'total': F('total') + income, } ) I tried the F() and it works great! { id: 1, user_id: 100, total: 55.5, freeze: 0, active: 55.5, update_time: 2018-08-26 07:12:15, } However, if the user doesn't have the record in the wallet table which means this is the first time he/she earned money, then something goes wrong: Failed to insert expression "Col(wallet, Wallet.total) + Value(5.0)" on Wallet.total. F() expressions can only be used to update, not to insert. How to fix this if I really wanna use update_or_create()? Need your help, thanks! -
Transferring Django from windows to ubuntu
I have written a project in windows with Django, It works well in windows, I wanted to transfer it to Ubuntu, first I installed the python3 and then made a virtualenv, activated it and installed django and required packages, I got some errors but the main irritating one is that, I have a INI file, I use the configobj to read it, it works well in windows but in Ubuntu it give 'Key error' here is my code: from configobj import ConfigObj ConfigPath = os.path.join(settings.MEDIA_ROOT, 'Vars.ini') ConfigParser = ConfigObj(ConfigPath) print(ConfigParser['FileNames']['MotionName']) and here is the file: [FileNames] MotionName = test1 I also tried to use only lowercase words but still no chance. -
Django render loop output to the template
I have a function in my view that crops thousands of images in background: def run_task(request): initialize() return render(request,'home/index.html') def postpone(function): def decorator(*args, **kwargs): t = Thread(target = function, args=args, kwargs=kwargs) t.daemon = True t.start() return decorator @postpone def initialize(): allimages = [] number = 0 if not os.path.exists('thumbnails'): os.makedirs('thumbnails') path = '/Users/shoaibrafa/Data/*.jpg' for image in glob.glob(path): print(image,"=====",number) im = Image.open(image) im.thumbnail((512, 512), Image.ANTIALIAS) im.save("thumbnails/" + os.path.basename(image), "JPEG") number = number + 1 my problem is how can I show in the template (index.html) how many images are processed so far! or simply how can I send the 'number' value to my template in each iteration? Thanks in advance -
how to access my written django libraries
i have a project in django named x and i have an app name y in x. in the directry of y i have my views and i write a function in one script named project that is wrapped into two other directories named dir1 and dir2 that dir1 is placed in y directory how to to access my function i tried: from dir1.dir2 import project and from .dir1.dir2 import project and from dir1.dir2.project import * and from .dir1.dir2.project import * my directory is like this: x x y views.py dir1 dir2 project how can i fix this -
Migrations to run properly on AWS
I uploaded a django project to AWS by using Elastic Beanstalk. I worte migration command to django.config and add postgrest DB instance to the environment from aws cosole. The problems is that according to log, migration command is properlly called but it logs "No migrations to apply" even the DB instance is brand new. If I check a page uses DB objects, it show DB related error. Project Environemnt Django 2.0.4 Python 3.6 Error When I opne a page with Car objects, following error appears. ProgrammingError at / relation "cars_car" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "cars_car" ^ Setting related code .ebextensions/django.config # .ebextensions/django.config container_commands: 01_migrate: command: 'source /opt/python/run/venv/bin/activate && python manage.py migrate --noinput' leader_only: true option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebaugustsix/wsgi.py Settings.py(only some import parts) # DB and debug settings from settings module from .base import * import os DEBUG = True if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } Migration file # migrations/0001_initial.py from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Car', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ], … -
Django/Python Beginner: Error when executing python manage.py migrate .No module named account
I'm new to django and I'm having issues figuring out what is causing errors in my project.I'm trying to learn django by maintaining and extending existing project. (BPS_SE~1) C:\Users\BPS_Server>python manage.py migrate Traceback (most recent call last): File "manage.pyenter code here", line 22, in execute_from_command_line(sys.argstrong textv) File "C:\Python27\lib\site-packages\django\core\management__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management__init__.py", line 341, in execute django.setup() File "C:\Python27\lib\site-packages\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Python27\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) ImportError: No module named account -
please help how to debug django in vs code
$ cd "e:\devu_class\16-aug" ; env "PYTHONIOENCODING=UTF-8" "PYTHONUNBUFFERED=1" "C:\Python\Python36\python.exe" "c: \Users\Welcome.vscode\extensions\ms-python.python-2018.7.1\pythonFiles\PythonTools\visualstudio_py_launcher.py" "e :\devu_class\16-aug" 27945 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput,DjangoDebugging "C:\P ython\Python36\python.exe" runserver --noreload --nothreading ValueError: source code string cannot contain null bytes -
Django - URL and namespace
I'm building a Django template in the Book app and using URL tag to redirect to the Account app's URLs. But it says account' is not a registered namespace. book.urls: app_name = 'book' urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('account/', include('account.urls', namespace='account')) ] book.views: class HomePageView(generic.TemplateView): template_name = 'book/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['all_books'] = Book.objects.all() return context templates/book/home.html: <div id="register"> <p> <a href="{% url 'account:register' %}"> Sign Up </a> </p> </div> account/urls: app_name='account' urlpatterns=( path('register/', views.RegisterView.as_view(), name='register'), path('successful/', views.successful_created, name='successful'), ) -
How class LoginView works??? why don't we define LoginView in Views.py?? if we dont define why we calling like that LoginView.as_view()?
views.py class RestaruntsCreateForm(LoginRequiredMixin,CreateView): form_class = RestaruntsCreateForm login_url = '/login/' template_name = 'restarunts/form.html' success_url = '/restarunts/' how LoginView works?` -
Django Cannot Insert ForeignKey into Database : It's Error ,MultiValueDictKeyError
I try to Insert Foreign Key into the database. But When I hit the submit, It's Error:MultiValueDictKeyError This is my code model.py from django.db import models class Candidate_Military(models.Model): """docstring forCandidate_Military.""" auto_increment_id = models.AutoField(primary_key=True) military_status = models.CharField(max_length=100,null=True) military_reason = models.CharField(max_length=250,null=True) def __int__(self): return self.auto_increment_id class Candidate_Basic(models.Model): """docstring for Candidate_basic.""" id_number = models.CharField(primary_key=True,max_length=13) position = models.CharField(max_length=250) salary = models.IntegerField() profile_pic = models.ImageField() nickname = models.CharField(max_length=100) name_title = models.CharField(max_length=50) firstname = models.CharField(max_length=250) lastname = models.CharField(max_length=250) candidate_military = models.ForeignKey(Candidate_Military, on_delete=models.CASCADE,null=True) def __int__(self): return self.id_number view.py from .models import Candidate_Basic, Candidate_Military def index(request): template=loader.get_template("index.html") return HttpResponse(template.render()) def submit_applyjob(request): print("ohh! It's sumbitted!") military_status = request.POST.get('military_status') military_reason = request.POST.get('military_reason') candidate_military = Candidate_Military(military_status=military_status,military_reason=military_reason) candidate_military.save() id_number = request.POST["id_number"] position = request.POST["position"] salary = request.POST["salary"] profile_pic = request.POST["profile_pic"] nickname = request.POST["nickname"] name_title = request.POST["name_title"] firstname = request.POST["firstname"] lastname = request.POST["lastname"] print("candidate_military" + "-->>>" + str(candidate_military)) candidate_military = request.POST["candidate_military"] candidate_basic = Candidate_Basic(id_number=id_number,position=position,salary=salary, profile_pic=profile_pic,nickname=nickname,name_title=name_title, firstname=firstname,lastname=lastname,candidate_military=candidate_military) candidate_basic.save() return render(request, "index.html") And When I fill the form and hit the submit button It's Error Like This enter image description here I don't Understand Why It cannot insert into my database. I try to print the value of 'candidate_military' It's Print the right value! enter image description here Plz Help me to Debug This issue … -
deploy django channels on nginx
I don't know about anything about nginx and how to configure it to run channels. My environment is django 2.x ubuntu 16 nginx daphne redis digitalocean I've tinkered around with my nginx config file for a weeks now unable to get my socket to connect. nginx config server { listen 80; server_name x.x.x.x; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/admin1/myproject/channels-examples/multichat/static/ ; } location / { include proxy_params; proxy_pass http://unix:/home/admin1/myproject/channels-examples/multichat/multichat.sock } } I will greatly appreciate any assistance. -
I want to return the content mash up from a certain model A and model B by API using Django
◆ Environment django + django-rest-framework ◆ What you want to do I want to return the content mashuped from a certain model A and model B by API In this case, instead of model A and model B, we would like to create a new model C as much as possible and put large business logic in it (Model C is a model only for mashing up model A and model B However, because there is no reusability, I do not want to store it in DB) ◆ Current situation You can make it by modeling a simple class as a model, but that can not be done well in the rest-framework. If you define it as a django's model, you try to save it in the DB, or an incomplete object with insufficient methods is generated and falls (for example, if managed = False is specified in -
DJANGO,DRF:request id returning a NONE value instead the user object
i want to create a follower option in django using DRF so here my models.py class Connect(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, unique = True, related_name = 'rel_from_set',on_delete=models.CASCADE) following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name = 'follwed_by') def __str__(self): return str(self.following.all().count()) urls.py url(r'^conn/(?P<id>\d+)', ConnectApi), serializer.py class ConnectSerializer(serializers.ModelSerializer): class Meta: model=Connect fields=('user','following') views.py @api_view(['GET','POST']) def ConnectApi(request,id): user_id=request.POST.get('id') print(user_id) # user_id=request.GET['id'] # action=request.POST.get('action') if user_id : # if user_id and action: try: user1=User.objects.get(id=user_id) if user1 : Connect.objects.get_or_create(user=request.user, following=user1) else: Connect.objects.filter(user=request.user, following=user).delete() return JsonResponse({'status':'ok'}) except: return JsonResponse({'status':'ki'}) return JsonResponse({'status':'ko'}) but whenever i fired up the url http://127.0.0.1:8000/connect/conn/2 this is the response {"status": "ko"} and in the terminal i could see "NONE " for print(user_id) command i don't understand where i have done the mistake and i dont think if this is the best practice to make followers function if you know one please let me know -
Django multiple choice and multi-select field in model and form
I am learning Django and have hit an inssue that I don't know what to Google for. I have the standard User model and a Profile model that points into the User model via a OneToOne field. That part plus the profile's Form and the CBVs all work. A profile holder can have one or more professional affiliations. This is not for a union but my Dad, for example, as a welder, was affiliated with: "The Iron Workers", "Steam Fitters", "Boiler Makers", "Pipe Fitters" and a couple other specific unions that used welders. So if I want the profile and form to allow multiple choices and multiple selected results for affiliations then I see that you might use class Profile(models.Model): GROUPS = ( ('IW', 'Iron Workers'), ('PF', 'Pipe Fitters'), ... ) affiliation = models.CharField( max_length=3, choices=RANK, default='U', blank=True, null=True, ) ... In the associated form it looks like you use a GROUPS = ( ('IW', 'Iron Workers'), ('PF', 'Pipe Fitters'), ... ) affiliation = forms.MultipleChoiceField( choices=GROUPS ) What if I want a db table of these choice items instead of tuples? If I have to add to a list of choices then editing the code might not be the most … -
Passing data/request to multiple html files
Is there a way to pass data to multiple html files? def topic(request, topic_id): topic = Topic.objects.get(id = topic_id) entries = topic.entry_set.order_by('-date_added') videos = topic.document_set.order_by('-upload_at') images = topic.image_set.order_by('-upload_at') context1 = {'topic': topic} context2 = {'entries': entries} return render(request, 'learning_logs/entry.html', context1) return render(request, 'learning_logs/text.html', context2) I want the data to passed onto both html files, but only one is actually rendered/displayed. The html file that is displayed will have an extends linking to the other one.