Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is possible to monitor a celery task in a django view without block the server
I have a long running task that I need to decouple from my normal django app. Is called from several clients, and wonder if is possible to give them the ilusion of a synchronous call, where the server take the job of monitor the job and return back when it finish. This mean, that I only need to offload the server and not need to worry about blocking the clients (this is already solved). @task def sync(): # A long process here... So, in my view is possible to do something like: def sync_database(request): while timeout(60): #Monitor task, if error or result: sleep(1) return sync.result without kill the performance? -
Why a call to a celery task block forever?
I follow the tutorial at http://docs.celeryproject.org/en/master/django/first-steps-with-django.html from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cobros.settings') app = Celery('cobros') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() # Settings CELERY_APP="cobros" CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE and call my first job: @task def add(x, y): logger.info("Sum ", x, y) return x + y def syncClientAsync(): baseDir = getBaseDir(str(cobrador.id)) print("Delay...") return add.delay(4, 4) #No work return add.delay(4, 4).get(timeout=1) #No work When I run the code python get stuck/blocked forever. Redis and Celery are running and not report any error or problem. -
Queryset contentype show fields name and values in template table
I got a view that receives a model and field the user passes via post (existing model and field inside the app of course) and makes a queryset filter on it, then i need to show in my template that result in a table (name fields must be the column headers) and their respective values. This what i got so far trying to serialize the queryset result in order to make it easier to show in template: Views.py: from django.contrib.contenttypes.models import ContentType class CommitteeReport(BaseView): template_name = 'committee/committee_report.html' def post(self, request, **kwargs): myfield = request.POST['field'].lower() my_model = request.POST['model'].lower() queryset_obj = ContentType.objects.get(model = my_model).model_class().objects.filter(**{myfield:True}) return render(request, self.template_name,{ 'requirements': queryset_obj, }) And my template: <div class="tab-pane active" id="tab_1"> <table class="datatable table table-striped table-hover" cellspacing="0"> <thead> <tr> {% for key in requirements %} <th>{{ key.fields }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in requirements %} <tr>{{ item.value }}</tr> {% endfor %} </tbody> </table> </div> Thing is, i don't get result or if i change the tag inside the termplate, i get the objects dictionary for every row. Any idea of how to achieve what i need ?, thanks in advance. -
NameError: name 'reload' is not defined python 3.6.4
After installing Xadmin, i encounter some problems. And there is my error details: [File "C:\Users\Harry\PycharmProjects\mxonline\lib\site-packages\xadmin\sites.py", line 9, in <module> reload(sys) NameError: name 'reload' is not defined]1 i've tried import importlib importlib.reload(sys) but it still doesn't work. i use python 3.6.4 -
Aldryn NewsBlog Designing a Template
The documentation for aldryn news-blog is very vague and i don't understand how to use articles. I'm trying to make a section page where each instance of an article creates a panel with the article's featured image and the name as the footer which will also be a button. Each article will create a new column. When there is 4 articles in a column, a new row will be started for the next article. I constantly receive the following errors when I adjust. Could not parse the remainder: '(loop.index,4)' from 'divisibleby(loop.index,4)' or for {% if loop.index|divisibleby 4 %} divisibleby requires 2 arguments, 1 provided How would I go about fixing this forloop and having it display. Django V- 1.8 {% load i18n staticfiles thumbnail cms_tags apphooks_config_tags %} {% extends "base.html" %} <div class="container"> <div class="row"> {% for article in article_list %} <div class="col-4"> <div class="panel panel-default"> <div class=panel-body> <img src="{% thumbnail article.featured_image 800x450 crop subject_location=article.featured_image.subject_location %}" alt="{{ article.featured_image.alt }}"> </div> <div class=panel-footer> <a href="{{ article.get_absolute_url }}" class="btn btn-light btn-lg btn-block aria-pressed=False label={{ article.slug_source.fieldname }}"> </div> {% if loop.index|divisiableby 4 %} </div> <div class="row"> {% endif %} {% endfor%} </div> </div> -
Django-Leaflet show custom layers on a form
I have two models, one that shows a marker(PointField) and one that generates PolygonFields. In my views, i can perfectly show all the data on a map. However, I would like to show the same data when creating a new geometry. Question is, how do I overlay the marker and the polygonField data as a layer in a form. models class MyPolygon(gis_models.Model): geom = gis_models.PolygonField() objects = gis_models.GeoManager() class MyPoints(gis_models.Model): geom = gis_models.PolygonField() objects = gis_models.GeoManager() views class PolygonCreateView(CreateView): form_class = PolygonForm template_name = 'applications/create_polygon.html' success_url = '/applications/polygon' def view_polygon(request): polygons= ReserveAirspace.objects.all() return render(request, 'applications/polygons.html',{'polygons':polygons}) same applies to the points. html {{form.geom}} How do i add all the existing polygons and points to the form field above in the template??? -
Django ManyToManyField that only works one way
I have my models set up as follows: class Product(models.Model): related_products = models.ManyToManyField('self', blank=True, related_name='related_products') As you can see, the relation is to itself. Now, lets say I have 3 products in my database: A, B, C. Product B's related product is Product C. Now, if I add Product B to the related product for product A, then Product B's related product changes from C to A, C. I don't want this, I want the change to only go one way. If I add B to A's related products, then B's related product won't change. Hope this is clear. How can I do this? Thanks! -
how o make django-autocomplete light return selected text not id
I have a simple form which lets a user select his country, state and district and redisplays the selected data. Everything works as expected apart from the fact that what is displayed is not the "text" but "ids" of the selected data. Expectation: You belong to India, Punjab, Jalandhar. Me too. ;) Output: You belong to 1, 2, 4. Me too. ;) # my form class MyInfoForm(forms.Form): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ListSelect2( url='country-autocomplete', ) ) state = forms.ModelChoiceField( queryset=State.objects.all(), widget=autocomplete.ListSelect2( url='state-autocomplete', forward=(forward.Field('country'),) ) ) district = forms.ModelChoiceField( queryset=District.objects.all(), widget=autocomplete.ListSelect2( url='district-autocomplete', forward=(forward.Field('state'),) ) ) # my view which handles MyInfoForm class CountryView(FormView): template_name = 'home.html' form_class = MyInfoForm success_url = '/thanks/' def form_valid(self, form): print("Request :", self.request.POST) country = self.request.POST["country"] state = self.request.POST["state"] district = self.request.POST["district"] msg = "You belong to {country}, {state}, {district}. Me too. ;)".format( country=country, state=state, district=district) return HttpResponse(msg) # other auto-complete views (similar to official tutorials) class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Country.objects.none() qs = Country.objects.all() if self.q: qs = qs.filter(country_name__istartswith=self.q) return qs class StateAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return State.objects.none() qs = State.objects.all() country = self.forwarded.get('country', None) if country: qs = … -
Implementing the custom permissions from the Django REST framework tutorial
I'm following the Django REST framework tutorial (part 4) but I'm observing a discrepancy between the behavior of my API and what is expected according to the tutorial. Here is my project-level urls.py: from django.contrib import admin from django.urls import path, include from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path('admin/', admin.site.urls), path('users/', views.UserList.as_view()), path('users/<int:pk>/', views.UserDetail.as_view()), path('', include('snippets.urls')) ] urlpatterns += [ path('api-auth/', include('rest_framework.urls')) ] and here is the included snippets.urls: from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path('snippets/', views.SnippetList.as_view()), path('snippets/<int:pk>/', views.SnippetDetail.as_view()) ] urlpatterns = format_suffix_patterns(urlpatterns) I've created a permissions.py with a custom permission class IsOwnerOrReadOnly: from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user and I've added this class to permission_classes in the SnippetDetail class in views.py: from django.contrib.auth.models import User from snippets.models import Snippet from snippets.serializers import SnippetSerializer, UserSerializer from rest_framework … -
How to deserialize data from multiple sources for one model using DRF?
I am transitioning some data over to use DRF. I have a POST endpoint that takes a JSON payload, parses relevant fields, and creates multiple objects out of that data. Each subsequent object created also relies on the previous object created (see example below). I am trying to figure out how to accomplish below, using DRF to deserialize data. It doesn't exactly have to be modeled like the code below, but I need the same end result. def job_start(request, plat_name="other", script_version="1"): a_product, created = Product.objects.get_or_create(name="Mobile") a_platform, created = Platform.objects.get_or_create(name=plat_name) tool, created = Tool.objects.get_or_create( product=a_product, platform=a_platform, url=jenkins_dump.url) job, created = Job.objects.get_or_create(name=jenkins_dump.job_name, tool=tool) job_in_progress, _ = Status.objects.get_or_create(name="IN_PROGRESS") start_time_raw = datetime.fromtimestamp(jenkins_dump.start_time / 1000) job_execution = JobExecution.objects.create(build_id=jenkins_dump.execution_number, job=job, time_start=start_time_raw, status=job_in_progress, pipeline_script_version=script_version) # what I want to do # serializer = ProductSerializer(request.data) # if serializer.is_valid(): # serializer.save() # serializer = ToolSerializer(request.data) # if serializer.is_valid(): # serializer.save() I'm wondering how I can serialize all these values and then when I create an object, append it to the serialized data, then pass that serialized data to the next object serializer, etc. -
Django. Comparing the model fields before saving for the admin panel
I'm new to Django and I have a question (Yes, yes, I was looking for and did't find ...). There are two models: class CounterDetail(models.Model): counter = models.ForeignKey(Counter, on_delete=models.CASCADE) date_placing = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) verifying_period_mounts = models.IntegerField(blank=False, null=False) and class Detail(models.Model): counterdetail = models.ForeignKey(CounterDetail, on_delete=models.CASCADE) date_last_verification = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) date_obxoda = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) How to implement the check when adding an entry to the second model through the admin panel: field date_obxoda = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False)more then date_placing = models.DateField(auto_now=False, auto_now_add=False, blank=False, null=False) from another model. Please give an example, thank you. -
Comment form in django didn't save the new comments
I have a little problem. I'v create a new form for comments the articles on website. When I add the new comment from django admin everythink works ok, but when I try to add the new comment directly from detail page nothings happen and I'am redirecting to the page with list of articles. here are my files models.py: class Komentarz(models.Model): post = models.ForeignKey(Wpisy, related_name="komentarze", verbose_name="Komentarze do artykułu", on_delete=models.CASCADE) name = models.CharField(max_length=80, verbose_name="Imię") email = models.EmailField(verbose_name="Email") content = models.TextField(verbose_name="Treść komentarza") created_date = models.DateTimeField(verbose_name="Utworzono", auto_now_add=True) active = models.BooleanField(verbose_name="Aktywny?", default=True) class Meta: ordering = ('created_date',) verbose_name="Komentarz" verbose_name_plural="Komentarze" def __str__(self): return 'Komentarz dodany przez {} dla strony {}'.format(self.name, self.post) vies.py with the function of details from django.shortcuts import render, get_object_or_404 from .models import Wpisy, Komentarz from .forms import KomentarzeForma .... def detale_bajki(request, slug, ): detale_bajki = get_object_or_404(Wpisy, slug=slug) komentarze = detale_bajki.komentarze.filter(active=True) if request.method == 'POST': formularz_komentarza = KomentarzeForma(data=request.POST) if formularz_komentarza.is_valid(): nowy_komentarz = formularz_komentarza.save(commit=False) nowy_komentarz.detale_bajki = detale_bajki nowy_komentarz.save() else: formularz_komentarza = KomentarzeForma() return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki, 'komentarze': komentarze, 'formularz_komentarza': formularz_komentarza}) forms.py from .models import Komentarz from django import forms class KomentarzeForma(forms.ModelForm): class Meta: model = Komentarz fields = ('name', 'email', 'content') and detail.html ... {% with komentarze.count as total_komentarze %} <h2> {{ total_komentarze }} … -
Django server crashes when accessing webcam with opencv
so I found out that everything works fine when I remove cv2.imshow("Face",img) from the code but when it is used the server crashes due to some reason, the code runs perfectly when run as a plain script excluding django code. Can anyone tell me why is this happening and the possible solution? thanks from django.shortcuts import render, redirect import cv2 import numpy as np from settings import BASE_DIR def index(request): return render(request, 'index.html') def create_dataset(request): userId = request.POST['userId'] faceDetect = cv2.CascadeClassifier(BASE_DIR+'/ml/haarcascade_frontalface_default.xml') cam = cv2.VideoCapture(0) id = userId sampleNum = 0 while(True): ret, img = cam.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceDetect.detectMultiScale(gray, 1.3, 5) for(x,y,w,h) in faces: sampleNum = sampleNum+1 cv2.imwrite(BASE_DIR+'/ml/dataset/user.'+str(id)+'.'+str(sampleNum)+'.jpg', gray[y:y+h,x:x+w]) cv2.rectangle(img,(x,y),(x+w,y+h), (0,255,0), 2) cv2.waitKey(500) cv2.imshow("Face",img) cv2.waitKey(1) if(sampleNum>35): break cam.release() cv2.destroyAllWindows() return redirect('/') -
User registration using extra fields by extending AbstractUser
I asked something similar before, but people don't seem to understand what I ask or maybe I just don't understand, but I'm really trying to find a solution here. So I have a student model which extends AbstractUser like: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password') class StudentForm(forms.ModelForm): class Meta: model = Student fields = ('phone', 'student_ID', 'photo') class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) photo = models.ImageField(upload_to='students_images') phone = models.CharField(max_length=15, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_student(sender, instance, created, **kwargs): if created: Student.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_student(sender, instance, **kwargs): instance.profile.save() And the expected output is this: I just don't know how the view is supposed to look like. I figured something in the past, but nothing would have been saved. I want that student will not be able to register unless he fills up all those fields: username, email, phone, student_ID etc. But also, I want that the fields of Student to be editable in database after the user is created by the form submission. I'm new to this, but I really need to … -
How to get pk of an instance of a django model before saving the instance
I am trying to upload an image using models.ImageField(upload_to=upload_location) def upload_location(instance,filename): print("%s/%s"%(instance.id,filename)) return "%s/%s"%(instance.id,filename) but its giving "GET /media/None/image_qacfEsv.jpg HTTP/1.1" I have tried using slug field it worked fine but neither id nor pk is working I want to use the obj ID to name the folder for image but its giving none here are my files def upload_location(instance,filename): print("%s/%s"%(instance.id,filename)) return "%s/%s"%(instance.id,filename) class Post(models.Model): draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False,auto_now_add=False) user = models.ForeignKey(settings.AUTH_USER_MODEL,default=1) slug = models.SlugField(unique=True) title = models.CharField(max_length=120) image = models.ImageField(upload_to=upload_location, null=True,blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) -
Django dont show block tags properly
im using 2 apps. blog and contact. i included 2 block tags in my index.html. but i can only get one working at the same time. when im on my blog it wont show the contact one, when im on my contact it wont show the blog block. My Project: https://github.com/bibschxz/bibsch_project -
Reset a value in a model for all users each year - Django.
I am developing a Django application that tracks an employees holiday. I am not to sure how I would go about resetting the holiday each year at a specific date. Are there any good known solutions/libraries for how to do this? class User(models.Model): avatar = models.ImageField( default='images/avatars/profile.png', upload_to=user_directory_path) name = models.CharField(max_length=100) title = models.CharField(max_length=200, default="Employee") email = models.EmailField(max_length=254) present = models.BooleanField(default=False) code = models.CharField(max_length=4, unique=True) date_created = models.DateTimeField(auto_now_add=True) date_clocked = models.DateTimeField(default=timezone.now) total_holiday = models.DecimalField( default=28.0, decimal_places=1, max_digits=4) holiday_remaining = models.DecimalField( default=28.0, decimal_places=1, max_digits=4) My model is shown above I need to reset the remaining_holiday field on a admin user defined day each year. -
returning record count in django restful api
I have a very complex API that accepts different filter fields via POST request. the result is a list of items from the database. The total result set can be thousands of items if the user does not filter good. The API will be returning only 30 items but I want to add the total amount of items that satisfied the search conditions. I know that I can add a custom field in the Serializer class to return the count but I don't know how to access the queryset to query for the count(). I am sure there is a simple solution for this which I am missing Thanks Eyal -
Pass related object's field in Django ModelForm
I have a Django model class that extends the django.contrib.auth.models.User: class MyModel(models.Model): user = models.OneToOneField(User, models.CASCADE, unique=True) bio = models.TextField() date_of_birth = models.DateField() and out of this model I'm making a ModelForm: class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['bio', 'date_of_birth'] How can I tell the MyModelForm to take in the User's fields such as username, first_name, last_name? Example in the class Meta fields I can add ['bio', 'date_of_birth', 'user'] but that will just provide me with the dropdown to select to whom shall the MyModel in the MyModelForm be related to. Doing ['bio', 'date_of_birth', 'user.first_name'] throws an exception django.core.exceptions.FieldError: Unknown field(s) (user.first_name) specified for MyModel -
Django views receiving FormData() object without keys
Here what i am basically trying is to stringify an array and append it to form data object and pass it to a view through ajax. The strange part is values are sent to the views but without keys. Here is my ajax formData = new FormData() var instrument = [136519172, 136485892] formData = new FormData() formData.append('instrument', JSON.stringify(instrument)) $.ajax({ type: 'POST', url: 'place_orders', cache:!1, processData:!1, data: formData, success:function(data){ }, error:function(){ } }); Here is my view def placeOrders(request): if request.is_ajax(): instrument = request.POST.get('instrument') return HttpResponse(instrument) The response i get is None This is the Formdata sent(took from headers of Network tab) ------WebKitFormBoundaryNPW2Q1atgClRKOyY Content-Disposition: form-data; name:"instrument" [136519172,136485892] ------WebKitFormBoundaryNPW2Q1atgClRKOyY-- -
Django - saving form to the built in database SQLite
This is my first time using django and I am very simply trying to save text to the database. I have created the table inputs in the database. I am getting the following error; Error - Page not found (404) My code is as follows; Models.py from django.db import models class Input(models.Model): waist = models.IntegerField(default=0) height = models.IntegerField(default=0) def __unicode__(self): return "{0} {1} {2}".format( self, self.waist, self.height) forms.py class InputForm(forms.ModelForm): class Meta: model = Input fields ={ 'waist', 'height' } views.py def InputView(request): if request.POST: form = InputForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('account/input') else: form = InputForm() args = {'form' : form} return render(request,'accounts/input.html', args) urls.py url(r'^input/$',views.InputView, name='view_input') input.html {% extends 'base.html' %} {% block head %} <title> Edit Profile </title> {% endblock %} {% block body %} <div class="container"> <h1> Enter Body Details </h1> <br> <br> <form action="account/input" method="post"> {% csrf_token %} <ul> {{form.as_ul}} </ul> <input type="Submit" name="submit" value="submit"/> </form> </div> {% endblock %} If any one can help it would be greatly appreciated. -
Class based view and call function to script
I'm learning django and I'm facing a problem I can't figure how to debug. I have a lobby_detail.html template that shows a button like this: <button type="button" href="{% url 'sign'%}" class="btn btn-primary btn-lg btn-block">Sign this Document</button> The template is a Detail view modelview: class LobbyDetailView(generic.DetailView): model = Lobby I would like the button to execute some code that requires both user connected and current lobby instances How can I use the button thanks to class based view? Thanks in advance. -
Django Q object AND operation not working
I have a listview of people with a filter. The filter has the following code: if textquery: qs = qs.filter() qs = qs.filter(Q(name__icontains=textquery) | Q(surname__icontains=textquery) | Q(surname__icontains=textquery) & Q(name__icontains=textquery) ) return qs People can have both a first and a last name, and searching for those works as expected. However, when I input both the first AND the lastname, the program does not return any results (even though I thought that the '&' operation in the end should include both variables). In summary: this is currently the result of my queries: Person: 'John Doe' Query: 'John' Result: 'John Doe' Person: 'John Doe' Query: 'Doe' Result: 'John Doe' Person 'John Doe' Query: 'Johh Doe' Result: '' Does anyone know what I am doing wrong, and why matches for both the NAME and SURNAME do not return any results? -
Django - multiple databases - how to define the router?
I would like to connect my application to 3 different databases. To do this, I've changed the following code in the settings file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'local_db', 'USER': 'root', 'PASSWORD': 'password1', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, 'firstExternalDb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'firstExternalDb', 'USER': 'userName', 'PASSWORD': 'password1', 'HOST': 'firstExternalDb.node.com', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, 'secondExternalDb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'secondExternalDb', 'USER': 'userName', 'PASSWORD': 'password1', 'HOST': 'secondExternalDb.node.com', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } }, } And I want to have a possibility to specify for which database I will create a datatable. For example all django tables like 'auth_group' , 'django_admin_log' I want to save in localhost. Was trying to create a router going through this tutorial https://docs.djangoproject.com/pl/1.11/topics/db/multi-db/#topics-db-multi-db-routing But I do not understand this. Could you answer my questions: Should I create new router for each application ? how to define that all django tables should be used by default database ? -
How to display twitter feeds based on users in django & tweepy?
I want to show twitter data based on twitter username in my template (Tweepy) but I don't know how to send data from my models into my views. models.py: <pre> from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL # Create your models here. class Feed(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) feed = models.CharField(max_length=211, blank=True, null=True) twitter = models.CharField(max_length=211, blank=True, null=True) # this is the twitter user name which the user can enter. def __str__(self): return self.feed </pre> views.py: <pre> from django.shortcuts import render from django.views.generic import TemplateView from .tweet import * from .models import Feed def feed(request): api = tweepyapi(request) username = Feed.objects.filter(owner=request.user) user = api.get_user(twitter) # I want this portion to be dynamic. findfriends = user.friends() return render(request, 'feeds/feeds.html', { 'user': user, 'findfriends': findfriends }) </pre>