Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieving access token from database
I'm attempting to create a client server which will make calls to a resource server (i.e. Google, Facebook) to retrieve an access token for a user. I'm assuming that this token shouldn't be given to the user, but I'm confused as to how I'm supposed to save this token so that when the user needs to make an API call, the token can be retrieved. I'm trying to construct a Django server to do this. As of right now, I'm up to the point where I'm able to retrieve an access token from the resource server. However, I don't know what to do with it -- I don't know how to save it so that the user can access it again. I've tried reading up on this but it's been confusing for me to understand. I'm new to Django/OAuth2, any help would be greatly appreciated! -
When I put in pip --version into the terminal I get this error: "The 'pip==9.0.1' distribution was not found and is required by the application"
Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 3095, in @_call_aside File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 3081, in _call_aside f(*args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 3108, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 658, in _build_master ws.require(requires) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 959, in require needed = self.resolve(parse_requirements(requirements)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 846, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application -
How do I make a Django filter with dropdown?
I have the following chained models: class Faculty(models.Model): name = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Faculties' def __str__(self): return self.name class Department(models.Model): faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "PhD Studies"), (3, "Integrated Studies")), default=0) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) class Meta: verbose_name = "Study Programme" verbose_name_plural = 'Study Programmes' def __str__(self): return self.name class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) I want to make to have a dropdown for faculty, and then when a faculty is selected a department can be selected from that faculty, and after that a study programme can be selected from that department and all courses specific to that study programme to be displayed. How can I achieve this ? -
Get common instance from two ManyToMany field in Django
class Category(models.Model): name = models.CharField(max_length=100) class UserProfile(models.Model): name = models.CharField(max_length=100) tags_liked = models.ManyToManyField(Category, related_name='liked_by') class Product(models.Model): name = models.CharField(max_length=100) product_tag = models.ManyToManyField(Category, related_name="products") How to find all the 'Category' instance that shares atleast one common field between 'UserProfile' and 'Product'? I will use it to recommended products to user. -
Online store on python. How to adjust the price of goods depending on the currency?
Just started writing on the python. I'm writing an online store. I have a "Category of goods" class. The child class "products", which indicates the price and all other attributes. I want that in the admin set the exchange rate and prices changed automatically. How can this be realized? Thanks for any help. -
django - combine the output of json views
I write a simple json api, I use one base class, and I mostly write one api view per one model class. What I want is to combine the output of few views into one url endpoint, with as least as possible additional code. code: # base class class JsonView(View): def get(self, request): return JsonResponse(self.get_json()) def get_json(self): return {} class DerivedView(JsonView): param = None def get_json(self): # .. use param.. return {'data': []} urls.py: url('/endpoint1', DerivedView.as_view(param=1)) url('/endpoint2', DerivedView2.as_view()) # What I want: url('/combined', combine_json_views({ 'output1': DerivedView.as_view(param=1), 'output2': DerivedView2.as_view() })) So /combined would give me the following json response: {'output1': {'data': []}, 'output2': output of DerivedView2} This is how combine_json_views could be implemented: def combine_json_views(views_dict): d = {} for key, view in views_dict.items(): d[key] = view() # The problem is here return json.dumps(d) The problem is that calling view() give me the encoded json, so calling json.dumps again gives invalid json. I could call json.loads(view()), but that looks bad to decode the json that I just encoded. How can I modify the code (maybe a better base class) here, while keeping it elegant and short? without adding too much code. Is there any way to access the data (dict) which is … -
How to order readonly M2M fields in django admin
I can't seem to work out how to hook into the queryset of a readonly field in Django admin. In particular I want to do this for an inline admin. # models.py class Value(models.Model): name = models.TextField() class AnotherModel(models.Model): values = models.ManyToMany(Value) class Model(models.Model): another_model = models.ForeignKey(AnotherModel) # admin.py class AnotherModelInline(admin.TabularInline): # How do I order values by 'name'? readonly_fields = ('values',) class ModelAdmin(admin.ModelAdmin): inlines = (AnotherModelInline,) Note that this could probably be done by overriding the form and then setting the widget to disabled, but that's a bit of a hack and doesn't look nice (I don't want greyed out multi-select, but a comma-separated list of words. -
How to randomise the order of a queryset
Consider the following query: candidates = Candidate.objects.filter(ElectionID=ElectionIDx) Objects in this query are ordered by their id field. How do I randomise the order of the objects in the query? Can it be done using .order_by()? -
Django datetime comparison not working as expected in save
I have a custom save routine in one of my models that compares datetime fields and then is supposed to modify a field on another model and save it based on the results. However, the comparison is not working as I would expect it to. Namely, my <= comparison is returning True regardless of the actual comparison. models.py class Session(models.Model): date = models.DateField() # etc... class Case(models.Model): summary = models.TextField(blank=True) session = models.ForeignKey(Session, on_delete=models.CASCADE, related_name='cases') case_type = models.ForeignKey(CaseType) # etc... class Person(models.Model): earliest_case = models.ForeignKey('Case', null=True, blank=True, related_name='person_to_earliest_case+') latest_case = models.ForeignKey('Case', null=True, blank=True, related_name='person_to_latest_case+') # etc... class Litigant(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='person_to_case') case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='case_to_person') # etc... def save(self, *args, **kwargs): try: person = Person.objects.get(id=self.person_id) earliest_case = person.earliest_case latest_case = person.latest_case if self.case.session.date <= earliest_case.session.date: person.earliest_case = self.case person.save() elif self.case.session.date >= latest_case.session.date: person.earliest_case = self.case person.save() except: pass super(Litigant, self).save(*args, **kwargs) As you can see, when I save a new Litigant, what I want it to do is call up the existing Person instance, compare that instance's entries for earliest_case and latest_case with the new Case instance tied to Litigant and then reassign the fields if necessary. What is happen instead is that the new case … -
How do I filter/search my items from a model dependent on other models, by using dropdown choice fields ?
I have 4 models dependent on each other, related by foreign keys: Faculty > Department > StudyProgramme > Course. I have a page where all my courses are displayed and paginated, and on it's left I want to implement a filter with dropdowns, that will let you choose a faculty, then choose a department of the faculty, then choose a study programme of the department and display the specific courses. Also, I want to able to search for a course by just it's name. The results then would replace all courses and of course have pagination as well. I don't want to use any high-level tools that I would not understand or Ajax, I just want to use plain Django if possible. Can someone advice or point me to something similar to what I want to achieve ? I learn by example. Here is the code so far: def index(request): course_list = Course.objects.all() paginator = Paginator(course_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> … -
How to set limit on models in Django
I have a little problem. I want to set the limit for users in my app. For example: The new user after register and login to his account can add only one record. After added if this same user want to add next record, the app will return the alert "You are permited to add only one record". How to solve it? -
Django LiveServerTestCase with SQLite3
I am using LiveServerTestCase for functional tests with selenium in a Django app. I am using sqlite3 as a backend for local development, and I'm running the tests with a local development server on port 8081. I wrote a test for user registration, and when I run this test more than once, I see that the test fails because my form throws an error saying the user already exists. When I delete the sqlite3 database file, I can run the test again and it works fine (but running again will fail). I thought that this class would use a new database each time a test within the class was run, but I am getting errors. My question is: Is there another way to run the tests with LiveServerTestCase so that I don't have to delete the sqlite3 database each time I want to run the test? -
Form not Displaying in Django 1.8
I am making a form using Django 1.8 and Python 3.5 But the form is not showing up,IDK why ? This are my files respectivel urlpatterns = [ url(r'^login', 'login.views.login', name='login'), url(r'^admin/', include(admin.site.urls)), ] + static(settings.STATIC_URL , document_root=settings.STATIC_ROOT) login/view.py== from django.shortcuts import render from .forms import allusers1 # Create your views here. def login(request): form1=allusers1() context = { "form1": form1 } return render(request, "login.html",context) login/forms.py== from django import forms from .models import allusers1 class signupform(forms.ModelForm): class Meta: model = allusers1 fields = ['name','phoneno'] login/models.py from django.db import models # Create your models here. class allusers1(models.Model): name=models.CharField(max_length=400) phoneno=models.CharField(max_length=10) otp=models.IntegerField() # def __str__(self): # return self.name login.html {{form1}} output allusers1 object But output should have been Name and ,Email fields for input WHAT IS THE ERROR ? -
How do I get django static files actually styling in Kubernetes?
This is my deployment for the django app with rest framework: #Deployment apiVersion: extensions/v1beta1 kind: Deployment metadata: labels: service: my-api-service e name: my-api-deployment spec: replicas: 1 template: metadata: labels: name: my-api-selector spec: containers: - name: nginx image: nginx command: [nginx, -g,'daemon off;'] imagePullPolicy: IfNotPresent volumeMounts: - name: shared-disk mountPath: /static readOnly: true - name: nginx-config mountPath: /etc/nginx/nginx.conf subPath: nginx.conf ports: - name: nginx containerPort: 80 - env: - name: STATIC_ROOT value: /src/static/ - name: MEDIA_ROOT value: /src/media/ - name: CLIENT_ORIGIN value: https://marketforce.platinumcredit.co.ke - name: DJANGO_SETTINGS_MODULE value: config.production - name: DEBUG value: "true" image: localhost:5000/workforce-api:0.2.0 command: [ "./entrypoint.sh" ] name: my-api-container imagePullPolicy: IfNotPresent ports: - name: my-api-port containerPort: 9000 protocol: TCP volumeMounts: - name: shared-disk mountPath: /src/static initContainers: - name: assets image: localhost:5000/workforce-api:0.2.0 command: [bash, -c] args: ["python manage.py collectstatic --noinput"] command: [bash, -c] args: ["sleep 10"] command: [bash, -c] args: ["cp -r static/* /data"] imagePullPolicy: IfNotPresent volumeMounts: - mountPath: /data name: shared-disk volumes: - name: shared-disk emptyDir: {} - name: nginx-config configMap: name: nginx-config My service: # Service apiVersion: v1 kind: Service metadata: name: my-api-service labels: label: my-api-service spec: type: NodePort ports: - port: 80 targetPort: 80 protocol: TCP name: http selector: name: my-api-selector And here's my nginx configuration: apiVersion: … -
Django Ajax Call to Return Quantity
Currently using the django-carton app, I have a django view that returns JSON data that I use in an ajax call. Broadly speaking, I have got it working but struggling to work out how I can pass my item quantity (using ajax). Within the template I can call my item quantities using: {% for item in cart.items %} {{ item.quantity }} The ajax call connects to the view to return the Json data: def cart_detail_api_view(request): # cart_obj, new_obj = Cart.objects.new_or_get(request) cart = Cart(request.session) products = [{"name": x.name, "price": x.price} for x in cart.products] cart_data = {"products": products, "total": cart.total} return JsonResponse(cart_data) This is my Jquery/Ajax call: $(document).ready(function() { var productForm = $(".form-product-ajax") // #form-product-ajax productForm.submit(function(event) { event.preventDefault(); // console.log("Form is not sending") var thisForm = $(this) //var actionEndpoint = thisForm.attr("action"); var actionEndpoint = thisForm.attr("data-endpoint"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function(data) { var submitSpan = thisForm.find(".submit-span") if (data.added) { submitSpan.html("In cart <button type='submit' class='btn btn-link'>Remove?</button>")} var currentPath = window.location.href if (currentPath.indexOf("") != -1) { refreshCart() } }, error: function(errorData) { console.log("error") console.log(errorData) } }) }) function refreshCart() { console.log("in current cart") var cartTable = $(".cart-table") var cartBody = cartTable.find(".cart-body") // … -
Twitter API and Python 3: Authorization error in apparently perfectly authorized request
Following this doc, I finally got the steps 1 and 2 working by copypasting this answer. Why my original solution didn't work is still beyond me, but whatever I was doing wrong there seems to carry on in this third step, since I get an HTTP Error 401: Authorization Required. The Oauth header I produce is the following: Oauth oauth_consumer_key="omitted", oauth_nonce="ozlmgbmrxftmmfaxnngbpsulickqwrkn", oauth_signature="3ZxJu%252Bv%2FjxyPmghiI85xnuPv3YQ%253D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1518820400", oauth_token="omitted", oauth_version="1.0" which seems to be exactly the way the doc I linked in the beginning wants it. So maybe my signature is wrong? I can't really figure it out since I do it in a pretty standard way. This is my code for the callback url up until the request to oauth/access_token: def logged(request): print('Processing request from redirected user...') token = request.GET.get('oauth_token', '') user = twitterer.objects.get(oauth_token=token) #my model for the user that's signing in with twitter verifier = user.oauth_verifier = request.GET.get('oauth_verifier', '') url = 'https://api.twitter.com/oauth/access_token' dir_path = path.dirname(path.realpath(__file__)) with open(path.join(dir_path, 'credentials.txt'), 'r') as TweetCred: creds = TweetCred.read().split(linesep) oauth_consumer_key = creds[0].split()[1] consumer_secret = creds[2].split()[1] oauth_nonce = '' for i in range(32): oauth_nonce += chr(random.randint(97, 122)) oauth_timestamp = str(int(time.time())) parameter_string = parameter_string = 'oauth_consumer_key=' + oauth_consumer_key + '&oauth_nonce=' + oauth_nonce + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + oauth_timestamp + '&oauth_token=' + … -
Link to a different view's template from one template Django
enter image description here I have a template that displays a detail of a dorm with a list of "room_numbers". The problem: I am trying to make "room_numbers" as a link to each specific dorm room details page (see screenshot above). A dorm room details page has the following format: rooms/<int:pk> as specified in my urls.py I have scoured through the web and can't find where I need to start. Django and Python newbie here so please bear with me. URLs.py > urlpatterns = [ path('', views.index, name='index'), path('list/', views.DormsListView.as_view(), name='dorms'), path('list/<int:pk>', views.DormsDetailView.as_view(), name='dorm-detail'), path('rooms/', views.DormsRoomView.as_view(), name='rooms'), path('rooms/<int:pk>', views.DormsRoomsDetailView.as_view(), name='rooms-detail'), ] Views.py (DormsDetailView) > class DormsDetailView(LoginRequiredMixin, generic.DetailView): model = Dorm def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['room_numbers'] = ", ".join(self.object.dormroom_set.values_list('room_number', flat=True)) return context Views.py (DormRoomsDetailView) > class DormsRoomsDetailView(LoginRequiredMixin, generic.DetailView): model = DormRoom Dorm_Detail.html > <div>Rooms: {{ room_numbers }}</div> -
Django: TemplateSyntaxError, Invalid filter
I'm trying to access a value from a dictionary using a variable, all in an HTML file that follows Django's Templating language. Django's templating language doesn't let you access a dictionary using a variable as a key, so I decided to use Django filters to do it. However, I am getting a "Invalid filter" error and I can't figure out why. My html file <table class="table"> <tbody> <tr> <th scope="row">Username</th> <th scope="row">Full Name</th> <th scope="row">Points</th> {% for subject in subjects %} <th scope="row">{{ subject }}</th> {% endfor %} </tr> {% for user in users %} <tr> <td> <a href="{% url 'profile' username=user.username %}">{{ user.username }}</a> </td> <td>{{ user.first_name }} {{ user.last_name }}</td> <td>{{ user.profile.points.total }}</td> {% for subject in subjects %} <td>{{ user.profile.points|keyvalue:subject }}</td> {% endfor %} </tr> {% endfor %} </tbody> My filter.py from django import template register = template.Library() @register.filter def keyvalue(dict, key): return dict[key] My error message TemplateSyntaxError at /leaderboard/ Invalid filter: 'keyvalue' Thank you for any help :D -
sudo: unknown user: root via PythonAnywhere
I'm using PythonAnywhere with Postgresql, and have run into several problems. When I try to do anything, such as python manage.py makemigrations, I get the following error : sudo: unknown user: root sudo: unable to initialize policy plugin Also, I tried to use postgres -V, but I get command not found, and yet I can't use sudo to install it. Finally, I'm also not sure what my UNIX password is, but all my permissions are denied to me. Strangely, I've noticed the creation of a dead.letter file, which contains: giles-liveconsole1 : Feb 17 09:25:05 : DMells123 : user NOT in sudoers ; TTY=unknown ; PWD=/home/DMells123/nomadpad/blog ; USER=DMells123 ; COMMAND=/bin/bash giles-liveconsole2 : Feb 17 11:43:08 : DMells123 : user NOT in sudoers ; TTY=unknown ; PWD=/etc ; USER=#0 ; COMMAND=/usr/bin/vi /etc/passwd giles-liveconsole2 : Feb 17 11:45:51 : DMells123 : user NOT in sudoers ; TTY=unknown ; PWD=/etc ; USER=#0 ; COMMAND=/usr/bin/vi /etc/passwd -
Contact_form not found when adding contact form in Django
I get a message contact form not found when trying to add a contact form in Django. I follwed this guide. https://atsoftware.de/2015/02/django-contact-form-full-tutorial-custom-example-in-django-1-7/ This should have worked. contact/contact_form.html Request Method: GET Request URL: http://127.0.0.1:8000/contact/ Django Version: 2.0 Exception Type: TemplateDoesNotExist Exception Value: contact/contact_form.html Exception Location: /home/karl/django/venv/lib/python3.5/site-packages /django/template/loader.py in get_template, line 19 Python Executable: /home/karl/django/venv/bin/python Python Version: 3.5.2 Python Path: ['/home/karl/django/myproject', '/home/karl/django/venv/lib/python35.zip', '/home/karl/django/venv/lib/python3.5', '/home/karl/django/venv/lib/python3.5/plat-x86_64-linux-gnu', '/home/karl/django/venv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/karl/django/venv/lib/python3.5/site-packages'] Settings.py INSTALLED_APPS = [ 'personal', 'blog', 'writing', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'contact', 'contact_form', I set up the email address. root urls. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'contact', include('contact.urls')), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), url(r'^writing/', include('writing.urls')), url(r'^contact/', include('contact.urls')), ] contact urls.py from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.index), ] contact views.py from django.shortcuts import render def index(request): return render(request, 'contact/contact_form.html') Please help. -
Pass API Keys to GET Request in Python
We are trying to GET data from multiple endpoints in Django using the below format. How do we pass variables through to the endpoint? (settings.EXAMPLE_API_KEY) is a single API key. We have a multitude of API keys stored securely. orders_endpoint = 'https://{api_key}:{password}@{shop}.example.com/admin/orders/count.json' orders_url = orders_endpoint.format(api_key=settings.EXAMPLE_API_KEY, password=settings.EXAMPLE_PASSWORD, shop=settings.EXAMPLE_SHOP) orders_response = requests.get(orders_url) orders_json = orders_response.json() orders = mark_safe(json.dumps(orders_json)) -
Display List of objects from another Model Django
I am new to stackoverflow and I don't know how to properly paste Django code. Please bear with me. Anyway, here's my problem: "I want to display DormRoom.room_number in a template as a list (sample: Rooms: 401, 402, 403, 404, etc)." enter image description here Models.py > class Dorm(models.Model): dorm_name = models.CharField(max_length=50, help_text="Enter dorm name") dorm_description = models.TextField(max_length=1000, help_text="Enter dorm description") dorm_primary_picture = models.ImageField(help_text="Enter dorm primary pic") dorm_room_count = models.IntegerField(help_text="Enter no. of rooms") dorm_address = models.CharField(max_length=100,help_text="Enter dorm address") dorm_caretaker = models.CharField(max_length=50,help_text="Enter caretaker name") dorm_contact_no = models.CharField(max_length=50,help_text="Enter dorm contact number") dorm_contact_email = models.EmailField(max_length=254,help_text="Enter dorm email") dorm_date_added = models.DateTimeField(help_text="Enter Date Dorm was created") dorm_availability = models.CharField(max_length=50, help_text="Is dorm available") dorm_date_updated = models.DateTimeField(help_text="Enter Date Dorm information was updated") dorm_house_rules = models.TextField(max_length=1000, help_text="Enter dorm house rules") class Meta: ordering = ["-dorm_name"] def get_absolute_url(self): return reverse('dorm-detail',args=[str(self.id)]) def __str__(self): return self.dorm_name class DormRoom(models.Model): room_number = models.CharField(max_length=20, help_text="Enter room number") room_maxusers = models.IntegerField(help_text="Enter maximum # of room users") room_dorm = models.ForeignKey(Dorm, on_delete=models.CASCADE) room_count = models.IntegerField(help_text="Enter # of rooms in this Dorm room") def get_absolute_url(self): return reverse('rooms-detail', args=[str(self.id)]) def __str__(self): return self.room_number class Meta: ordering = ('room_number',) URLs.py > from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('list/', views.DormsListView.as_view(), name='dorms'), path('list/<int:pk>', views.DormsDetailView.as_view(), … -
Group by and count values
Im new to Django. I have different classes (Stock, Portfolio, Trades) What Im trying to achieve is a summery of all trades per stock. So Basicly this is how my rows are now I want to combine or group by stock_id and do a sum of open_price and quantity. I tried with Trade.objects.filter(portfolio=1).values('stock__name').aggregate(stock_total=Count('stock',distinct=True)) But that doesnt work. How do I need to write the query to get that result? -
Load the csv data using html view into django database
I am trying to load a simple csv file into django model named as class Team class Team(models.Model): Team = models.CharField(max_length=255,primary_key=True) Description = models.CharField(max_length=255) def __str__(self): return self.Team I have create a simple html page to load the file into the following location MEDIA_ROOT=os.path.join(BASE_DIR,"media") I am able to load my file into that location but I need some help with passing on the data to the actual database and load the values into the table "Team". Any suggestiond on this? -
Django: Use inline with One to One field
I have 3 models User,Student and Teacher. class User(..): username=.. firstname=.. more_fields.. class Student(..): user = models.OneToOneField(User, ..) a = .. more_fields.... class Teacher(..): user = models.OneToOneField(User, ..) b = .. more_fields..... At admin side I want Student and Teacher models to be displayed such that I can fill fields of User table when I add new Student/Teacher i.e Add Student form should have User model Stacked below it. I am getting errors while using inlines that User model does not have foreign key to Student model