Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invoking a Google Cloud Function from a Django View
I have created a Google Cloud function that can be invoked through HTTP. The access to the function is limited to the Service account only. If I had a Django View which should invoke this function and expect a response? Here is what I have tried 1) Before starting Django I set the environment variable export GOOGLE_APPLICATION_CREDENTIALS 2) I tried invoking the function using a standalone code, but soon realised this was going nowhere, because I could not figure out the next step after this. from google.oauth2 import service_account from apiclient.http import call SCOPES = ['https://www.googleapis.com/auth/cloud-platform'] SERVICE_ACCOUNT_FILE = 'credentials/credentials.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) Google's documentation does give you documentation around the API, but there is no sample code on how to invoke the methods or what to import within your Python code and what are the ways to invoke those methods. How do you send a POST request with JSON data to an Cloud Function, with authorization through a service account? -
Css changes is not reflecting in Django
I'm doing Django project, my issue is when I change colors in style.css file in static folder, the changes aren't reflecting on the website again the same old colors are coming. ScreenShot of my project file directory -
Django Token Authentication with Cookie
I am using Django REST framework with OAuth2Toolkit library to implements OAuth2 on my site, My frontend is built with React, and I am trying to connect both with storing the token inside a httponly-cookie. The problem im facing is that the library OAuth2Toolkit checks the HttpRequest for an Authorization header with Bearer key and value. Tho I am sending the token via cookie... (I don't want to save the token in localStorage, I heard it is really unsafe to do it this way) How do I connect my BE and FE for a safe authentication? -
Django - How to use filter with exclude well?
I can't figure out the way to build a query, so I need some help here! This is the models: class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField() class Employee(models.Model): user = models.ForeignKey(User, primary_key=True) class Service(models.Model): id = models.UUIDField(primary_key=True) user = models.ForeignKey(User) employee = models.ForeignKey(Employee) views = models.ManyToManyField(Employee) So, an employee need to get the first service that does not have an assigned employee, the query would be the following: Services.objects.filter(employee__isnull=True)[:1] An employee can see a service only once, after the employee see the service is added to views in Service model like service.views.add(employee). Because the query is made for employees, I need to exclude the services that the employee has already seen before, I tried something like that: Services.objects.filter(employee__isnull=True).exclude(views__views__employee_id=1)[:1] How should I do it? Thanks. -
How to run Gunicorn on HTTPS on CloudFoundry
I need to host my Django application using Gunicorn on Cloudfoundry on port 443, HTTPS. I am getting error: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. Which is resulting into Internal server error. How should I add add SSL. What are server.cert and server.key files? How to add them. -
Need help in creating a database schema
Current Database Schema - I have these 3 tables, Curriculum, Assignment, and Student. Every Student is assigned a Curriculum through a ForeginKey relationship between Student and Curriculum. Every Assignment possesses the same relation with the Curriculum using a ForeginKey. Problem Statement - There are around 100 Assignments for each Curriculum, the problem is, some students need to be exempt from some assignments, so I want a way that I can exempt a Student from Assignments 1, 2, and 3 but have the rest of the students do the assignment 1, 2 and 3. My solution that failed - What I tried was, creating a ManyToManyField in Student table in relation to Assignment table. However, having to add hundreds of assignments manually would be ridiculously time-consuming for each student. class Curriculum(models.Model): name = models.CharField(max_length=50, null=False) subject = models.CharField(max_length=30, choices=SUBJECT) grade_level = models.CharField(max_length=20, choices=CURRICULUMGRADE, null=False) tracking = models.CharField(max_length=20, choices=TRACKING, null=False) required = models.CharField(max_length=20, null=True) recorded_from = models.CharField(max_length=20, choices=RECORDED, null=False) semesterend = models.CharField(max_length=50, null=True) username = models.CharField(max_length=50, null=True) password = models.CharField(max_length=50, null=True) loginurl = models.CharField(max_length=100, null=True) weight = models.IntegerField(null=True) level = models.CharField(max_length=20, choices=LEVEL, null=False) class Student(models.Model): epicenter_id = models.CharField( null=False, blank=False, unique=True, max_length=10 ) last_name = models.CharField(null=False, max_length=50) first_name = models.CharField(null=False, max_length=50) email … -
How to populate my heroku postgres database on Windows with db.sqlite3?
I have been stuck in a bit of a predicament where I had a working django server through Heroku for over a year. But then tried to redeploy now that I am on a Windows instead of Linux and have not been able to get things working again. The app is deploying properly and the postgres database is properly migrated and has all the correct tables. However, the tables are all empty. And I can not figure out a way to get the database populated like it had been before. I am filling up a db.sqlite3 database with csvs like this: # import allgifts with open(os.path.abspath(os.path.dirname(__name__)) + '/static/csvs/AllGifts.csv') as f: reader = csv.reader(f) for row in reader: _, created = AllGift.objects.get_or_create( giftId=row[0], title=row[1], productUrl=row[2], imageUrl=row[3], price=row[4], minAge=row[5], maxAge=row[6], gender=row[7], popularity=row[8], prime=row[9], nsfw=row[10], ) And this database still works great locally. But I am missing a step that gets this data onto heroku and I have been spinning in circles trying to find out how. Does anyone have any ideas for what I am missing? If not what is the best way for me to remedy this situation and get my database onto the server in one form or another. Thanks! -
How to order a Django query set, when only want one observation at the end?
I have a observation, "Other" that I want at the end of a queryset of other objects. However, if I order it alphabetic or any other way, "Other" comes in the middle. How do I make "Other" last? Queryset.objects.order_by('-names_of_objects') "sdnlks", "dklnldsk", "Other", "dfsdno", "cdksnodi", "cjsdkc" Instead I want: "sdnlks", "dklnldsk", "dfsdno", "cdksnodi", "cjsdkc", "Other" I don't care about the other objects order. -
How to access my python virtual env in vscode terminal
I've created a virtualenv for my django project. And i want to use vscode. But 'workon env_name' is not working in vscode terminal, but its working fine on my command prompt. -
Adding a new drop down menu item in django model field
I have a model field that is a foreign key. It shows as a drop down on the form based on the values in the table. I want to add another item in it saying 'Add New' that when selected, should open up a modal form. Could anybody please help on how to achieve this? models.py: class Agent(models.Model): agent_phone = models.CharField(max_length=15, null=True, blank=True) agent_desc = models.TextField(null=True, blank=True) agency = models.ForeignKey(Agency, on_delete=models.CASCADE, null=True) forms.py: class AgentForm(forms.ModelForm): class Meta: model = Agent fields = ('agent_phone', 'agency', 'agent_desc') The 'agency' field on the form is populated with rows in the 'Agency' table in a drop down. I want to add another item 'Add new' that should open up a form to add new agency or add a 'Add New' link on the side of drop down that should open up the Add form. Could anybody please advise how to achieve this? -
Implementing A Directory in Django Mezzanine
I'm fairly new to Mezzanine. I'm creating a website for a non profit organization. Mezzanine offers most of the requirements except a directory. What is the best way of implementing a directory of businesses? Their model are laid out as follows: class BusinessCategory(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Business(Page): name = models.CharField(max_length=50) about = models.CharField(max_length=300, blank=True) location = models.CharField(max_length=100, blank=True) category = models.ForeignKey("BusinessCategory") cover = models.ImageField(upload_to="businesses", blank=True) website = models.URLField(blank=True) phone_number = models.CharField(max_length=10, blank=True) hours = models.CharField(max_length=50, blank=True) days = models.CharField(max_length=50, blank=True) email = models.EmailField(blank=True) def __str__(self): return self.name Any advice as to the ideal way of implementing this? -
filter results from database by user_id
Hello All I have been trying for days to solve this issue, however I am really not sure where my error is. I am new to django and have been coding for a year. I have a model portfolio that takes in tickers and also linked to the user via a foreign key. In my models class Portfolio(models.Model): ticker = models.CharField(max_length=15) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='investor', null=True) def __str__(self): return self.ticker my form is as such: class PortfolioForm(forms.ModelForm): class Meta(): model = Portfolio fields = ['ticker'] def __init__(self, user, *args, **kwargs): super(PortfolioForm, self).__init__(*args, **kwargs) self.fields['ticker'].queryset = Portfolio.objects.filter(user=user) and in my views: if request.method == 'POST': form = PortfolioForm(request.POST or None, request.user) if form.is_valid(): ticker = form.save(commit=False) ticker.user = request.user ticker.save() return redirect('/add_stock') else: ticker = Portfolio.objects.filter(pk = request.user.id) output = [] for ticker_item in ticker: output.append(str(ticker)) return render(request, 'test_app/add_stock.html', {'ticker':ticker, 'output':output}) I want the user to add stocks to the Portfolio database but only return the stock tickers they added. Currently the stocks are being added to the database but nothing is returned to the user. Also stocks added to the database are available for any user to see not just the specific logged in user. I have added @login_required … -
Multiple inputs with same name to write to database
I have a form and with several fields with the same name, I need to get this data in django view and write to the database. For now I am just trying to get the HTML data and render in the view but only the last value of the html form is displayed. View def agenda_padrao(request): inicio = request.POST['inicio'] fim = request.POST['fim'] idempresa = request.POST['id'] if request.POST: for i in inicio: print(i) return render(request, 'core/agenda.html') agenda.html <form method="POST" action="/agenda/padrao/">{% csrf_token %} <div class="modal-body"> <div class="row "> <h3>Horários</h3><br/> <a class="btn btn-success" href="javascript:void(0)" id="addInput"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </a> </div> <div id="dynamicDiv"> <div class="row col-12"> <input type="time" class="form-control form-control" id="inicio" name="inicio[]" style="width: 150px; margin-right: 10px;"> <input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px;"> <input type="hidden" name="id" value="{{ user.id_empresa }}"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <button type="submit" class="btn btn-primary" >Confirmar Horário Padrão</button> </div> </form> Javascript adding the fields $(function () { var scntDiv = $('#dynamicDiv'); $(document).on('click', '#addInput', function () { $('<p>'+ '<input type="time" class="form-control form-control" id="inicio" name="inicio" style="width: 150px; margin-right: 10px;">'+ '<input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px; margin-right: 10px;">' + '<a class="btn btn-danger" href="javascript:void(0)" id="remInput">' + '<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>' + '</a><br/>'+ '</p>').appendTo(scntDiv); return false; }); … -
Loading python envvars without using `source`
I am looking for a solution to loading an envvars.sh file within a django application. I would prefer to do this within the settings module and keep a file outside of it. Here is what I currently have: SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) def source_envvars(fname='envvars.sh'): """Equivalent of `$ source {fname}` with lines in the form of `export key=value`""" envvars = os.path.join(SITE_ROOT, fname) if not os.path.exists(envvars): return with open(fname, 'r') as f: for line in f: if line.startswith('export '): line = line.strip() key = line.split('=')[0].split()[1] value = line.split('=')[1].strip('"\'') os.environ[key] = value if not os.environ.get('DB_HOST'): source_envvars() # rest of settings.py file... Are there any downsides of using this approach? I know this doesn't support complicated bash-type exports, but all I have are basic exports of the form: export DB_HOST=rds.amazon.com/12345 Does the above approach properly instantiate all the variables, or does it seem to be missing something or insecure in some way or other? -
Django/React deployment not serving static files on Heroku
I've hunted the Internet and manu SO posts but haven't found what solves my solution yet. I have a Django back end, and a React front end created with create-react-app. But all I'm getting is Django Rest Framework API Root page—from what I can tell, it's simply not serving up the static files properly. My files are located at https://github.com/acd37/lead-manager It would be a lot for me to copy and paste—but I'm hoping someone can look at this and see what the issue is, or will clone it and give it a shot. If I npm run build and then serve, I get a blank page saying that my this.props.leads.map function can't fun. If I run heroku local, I get the same API Root page. Any ideas!? New to Python——deploying NodeJS apps to Heroku is MUCH easier! -
Django group by for reverse relationship
Let's say I have the following: class A: .... class B: a = models.ForeignKey(A,....) class C: a = models.ForeignKey(A,....) b = models.ForeignKey(B,....) user = models.ForeignKey(User, ....) I want to use regroup to display all C objects grouped together by a, user in a table with fields from A and all C objects in a drop down upon clicking the row. So.... # regroup A queryset by C foreign key and user foreign key c.field1, c.field2, ...., user.email, user.first_name, .... + dropdown a.field1, a.field2, a.field3, ..... If C contains a foreign key to a with multiple users these should be distinct rows. Meaning.... First level regroup by model C... great we have C model with all related A model as drop down..... But, these can have duplicate users. So separate top level by user + C model relation. I'm lost on how to do the previous sentence. First level group by is easy. -
Django get subobjects in view
My two models: class BusinessType(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) description = models.CharField(max_length=200) class Business(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) description = models.CharField(max_length=200) bus_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE, name="type") class Appointment(models.Model): from datetime import datetime business = models.ForeignKey(Business, on_delete=models.CASCADE, name="appointments") done = False created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Now I add this context to my view: 'business':Business.objects.order_by('name'), My template: {{business|length}}<hr /> {%for business_entry in business%} {{business_entry.appointments.all|length}} {%endfor%} Now the business length outputs "2" and that's right, I have two business objects. But for the appointments I get the value "0" which is not true. What am I doing wrong? -
Django change ordering of items in a Postgres ArrayField
dm_scripts = ArrayField(models.TextField(blank=True, null=True), default=list) I have a Django model, and I wanted to use the ArrayField to store a list of TextFiles. The order matters, and I've been asked to allow a user to reorder these. How would you do that? I've googled and searched here, but found nothing. Even Django's official documentation doesn't mention this. -
Linking ManytoMany relationship with Modelform
I'm pretty new to Django and I am working on a project that currently requires the following: I have two basic structures: a Project model and a TeamMember model- both related to each other through a ManytoMany relationship. Then I have an TMAssigned 'through' class. The team member will have many projects assigned to it over time. I have a ModelFrom which creates a Project model through the creation of the form. My question is, How do I link the team member to the newly created project upon the submission of the form? Here is a bit of my model & form code: TeamMember class TeamMember(models.Model): firstname = models.CharField(max_length=100, default= "First Name") lastname = models.CharField(max_length=100, default= "Last Name") fullname = models.CharField(max_length=100, default= "Full Name") projects = models.ManyToManyField(Project, blank=True, through="TMAssigned") email = models.EmailField(max_length=254) cellphone = PhoneNumberField(null=False, blank=False, unique=True) numberofcases = models.IntegerField(max_length=10000, default=0) @property def fullnamefunc(self): fullname = "{} {}".format(self.firstname, self.lastname) return fullname def __str__(self): return self.fullname TMAssigned class TMAssigned(models.Model): teammember = models.ForeignKey(TeamMember, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) Project class Project(models.Model): pursuitname = models.CharField(max_length=500) datecreated = models.DateTimeField(auto_now=True) bdmember = models.CharField(max_length=200, default="None") Form.py class bdForm(forms.ModelForm): bdmemberlist = TeamMember.objects.all().order_by('lastname') pursuitname = forms.CharField() bdmember = forms.ModelChoiceField(queryset= bdmemberlist) addbdteam = forms.ModelMultipleChoiceField( queryset=TeamMember.objects.all().order_by('lastname'), widget=Select2MultipleWidget, required=False) #this class … -
Fetching https content via api on client site but browsers raising mixed content http errors
I'm trying to build an external API in a Django app to serve some content over to a production client Wordpress site. The client is on https and the javascript uses fetch to get https api url but browsers are claiming http mixed content. What gives? I've tried both Chrome and Firefox and both are returning similar errors fetch('https://mysite.pythonanywhere.com/apit?param1=100000&param2=1000',{ method: 'GET', }) .then(function(response) { if (response.status !== 200) { console.log(response); console.log('Looks like there was a problem. Status Code: ' + response.status); return; } }); my view for this in Django has: response = JsonResponse(the_content_dict,safe=False) return response I can visit the URL directly in my browser and view the json response as expected but when I place the code above on the client WP site, I see in the Firefox console: Blocked loading mixed active content “http://mysite.pythonanywhere.com/apit?param1=100000&param2=1000” TypeError: NetworkError when attempting to fetch resource. rank:154:3 Response { type: "cors", url: "https://mysite.pythonanywhere.com/apit?param1=100000&param2=1000", redirected: false, status: 500, ok: false, statusText: "Internal Server Error", headers: Headers, body: ReadableStream, bodyUsed: false } Looks like there was a problem. Status Code: 500 Similarly, in Chrome: (index):154 Mixed Content: The page at 'https://clientsite.com' was loaded over HTTPS, but requested an insecure resource 'http://mysite.pythonanywhere.com/apit?param1=100000&param2=1000'. This request has been … -
How to select from drop down in django
I have a bunch of tuples that I get from an API and I am displaying them as : |User1 ID| User1 Name | User1 Status | "Choose Button" |User2 ID| User2 Name | User2 Status | "Choose Button" |User3 ID| User3 Name | User3 Status | "Choose Button" I want the user to click on the choose button, and get the information back in the views.py wherein I can use the user. id to change its status. I'm new to Django and I am not understanding how to proceed with it. I am only being able to display it as shown above (without the choose button) PS: Sorry, I cant provide with any code as I dont even know how to do it. -
is there a way to save Data on another page in django?
I'm building a simple tool that will allow users to save contact information on another page and redirect back to the index page. I try many things and I still can't figure it out, thanks in advance. code below url.py url(r'^lead/$', views.lead, name='lead'), view.py def lead(request): new_item=Blogger.email new_item.save() return HttpResponseRedirect('/app') index.html <a href="/app/lead" title="add lead" >Add lead</a> models.py class Blogger(models.Model): email=models.EmailField() -
How to Form Submit after Server Side Changes Django
I have a Javascript function to get the id in a Select, and then send it to my Views so I can change the value of an attribute based on the id I got. Javascript: $('#venta_form').submit( function(event) { event.preventDefault(); //Detiene el submit del form para que se ejecute esta funcion var _this = $(this); //Obtengo el id del submit form pedido_id = $("#id_pedido").val(); var url = '/control/estado/'+pedido_id; console.log(pedido_id); $.ajax({ type: "POST", url: url, data: { 'pedido': pedido_id }, success: function () { console.log('Funciono!'); _this.unbind('submit').submit(); //Continua el submit del form si la funcion se realiza }, error: function() { alert('Ha ocurrido un error, intentalo de nuevo'); console.log("error"); } }); }); My View: def estado_pedido(request, pk): if request.method == 'POST': obj = Pedido.objects.get(pk=pk) obj.estado = "Finalizado" obj.save() return render(request, 'control/venta_list.html') But when I change that value, my form doesn´t work and doesn´t save the values. This my CreateView for the form: class VentaCreate(CreateView): model = Venta # fields = '__all__' form_class = VentaForm success_url = reverse_lazy('control:ventas') template_name_suffix = '_crear' @method_decorator(permission_required('control.add_venta',reverse_lazy('control:ventas'))) def dispatch(self, *args, **kwargs): return super(VentaCreate, self).dispatch(*args, **kwargs) What could be the problem that is causing the form to not work after I change the value in my View? -
How to handle Django Pagination with Nested tabs
I want to add pagination to my template,My template have Nested Tab(see code), all My inner tabs contain a table and i want to add pagination to all my tables in my inner tabs. I have so far added pagination to one of my table and it works but the problem is whenever page refresh it goes my to first tab <!-- overview--> , not the one that made the request, although pagination is working. This is the structure of my tabs.I am not using custom JS or CSS, only BS4 class <div class="tab-content" id="nav-tabContent"> <!--OVERVIEW TAB--> <!--STATIC TAB--> <!--TAB 1--> <!--TAB 2--> <!-- FILES TAB--> <!--TAB 1 --> <!--TAB 2 --> <!--TAB 3 --> <!--Registry TAB --> <!--TAB 1 --> <!--TAB 2 --> <!--Network TAB--> <!--TAB 1 --> <!--TAB 2 --> <!--TAB 3 --> </div> TEMPLATE.html <nav aria-label="Page navigation"> {% if strings.has_other_pages %} <ul class="pagination justify-content-center pagination-lg"> {% if strings.has_previous %} <li class="page-item"><a class="page-link" href="?page=1">First</a> </li> {% endif %} {% for i in strings.paginator.page_range %} {% if strings.number == i %} <li class="page-item active"><a class="page-link" href="{{ i }}">{{ i }}</a></li> {% elif i > strings.number|add:'-3' and i < strings.number|add:'3' %} <li><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif … -
Call source envvars from within python
In my django settings.py file, I would like to call an envvars.sh file to import things like DB_CREDENTIALS. I'm trying to do something like this: if not os.environ.get('DB_PASSWORD'): subprocess.call(['source', 'envvars.sh']) DB_PASSWORD = os.environ.get('DB_PASSWORD', '') It works from the terminal, doing $ source envvars.sh but not from within python. Is there another way to do this?